task_id
stringlengths 5
19
| buggy_code
stringlengths 44
3.26k
| fixed_code
stringlengths 67
3.31k
| file_path
stringlengths 36
95
| issue_title
stringlengths 0
150
| issue_description
stringlengths 0
2.85k
| start_line
int64 9
4.43k
| end_line
int64 11
4.52k
|
|---|---|---|---|---|---|---|---|
JacksonDatabind-94
|
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
|
public void validateSubType(DeserializationContext ctxt, JavaType type) throws JsonMappingException
{
// There are certain nasty classes that could cause problems, mostly
// via default typing -- catch them here.
final Class<?> raw = type.getRawClass();
String full = raw.getName();
main_check:
do {
if (_cfgIllegalClassNames.contains(full)) {
break;
}
// 18-Dec-2017, tatu: As per [databind#1855], need bit more sophisticated handling
// for some Spring framework types
// 05-Jan-2017, tatu: ... also, only applies to classes, not interfaces
if (raw.isInterface()) {
;
} else if (full.startsWith(PREFIX_SPRING)) {
for (Class<?> cls = raw; (cls != null) && (cls != Object.class); cls = cls.getSuperclass()){
String name = cls.getSimpleName();
// looking for "AbstractBeanFactoryPointcutAdvisor" but no point to allow any is there?
if ("AbstractPointcutAdvisor".equals(name)
// ditto for "FileSystemXmlApplicationContext": block all ApplicationContexts
|| "AbstractApplicationContext".equals(name)) {
break main_check;
}
}
} else if (full.startsWith(PREFIX_C3P0)) {
// [databind#1737]; more 3rd party
// s.add("com.mchange.v2.c3p0.JndiRefForwardingDataSource");
// s.add("com.mchange.v2.c3p0.WrapperConnectionPoolDataSource");
// [databind#1931]; more 3rd party
// com.mchange.v2.c3p0.ComboPooledDataSource
// com.mchange.v2.c3p0.debug.AfterCloseLoggingComboPooledDataSource
if (full.endsWith("DataSource")) {
break main_check;
}
}
return;
} while (false);
throw JsonMappingException.from(ctxt,
String.format("Illegal type (%s) to deserialize: prevented for security reasons", full));
}
|
src/main/java/com/fasterxml/jackson/databind/jsontype/impl/SubTypeValidator.java
|
Block two more gadgets to exploit default typing issue (c3p0, CVE-2018-7489)
|
From an email report there are 2 other c3p0 classes (above and beyond ones listed in #1737) need to be blocked.
EDIT 21-Jun-2021: Fix included in:
* `2.9.5`
* `2.8.11.1`
* `2.7.9.3`
* `2.6.7.5`
| 71 | 111 |
JacksonDatabind-96
|
protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
// Looks like there's bit of magic regarding 1-parameter creators; others simpler:
if (1 != candidate.paramCount()) {
// Ok: for delegates, we want one and exactly one parameter without
// injection AND without name
int oneNotInjected = candidate.findOnlyParamWithoutInjection();
if (oneNotInjected >= 0) {
// getting close; but most not have name
if (candidate.paramName(oneNotInjected) == null) {
_addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
return;
}
}
_addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
return;
}
AnnotatedParameter param = candidate.parameter(0);
JacksonInject.Value injectId = candidate.injection(0);
PropertyName paramName = candidate.explicitParamName(0);
BeanPropertyDefinition paramDef = candidate.propertyDef(0);
// If there's injection or explicit name, should be properties-based
boolean useProps = (paramName != null) || (injectId != null);
if (!useProps && (paramDef != null)) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
// 25-May-2018, tatu: as per [databind#2051], looks like we have to get
// not implicit name, but name with possible strategy-based-rename
paramName = candidate.findImplicitParamName(0);
paramName = candidate.findImplicitParamName(0);
useProps = (paramName != null) && paramDef.couldSerialize();
}
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[] {
constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
};
creators.addPropertyCreator(candidate.creator(), true, properties);
return;
}
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
}
|
protected void _addExplicitAnyCreator(DeserializationContext ctxt,
BeanDescription beanDesc, CreatorCollector creators,
CreatorCandidate candidate)
throws JsonMappingException
{
// Looks like there's bit of magic regarding 1-parameter creators; others simpler:
if (1 != candidate.paramCount()) {
// Ok: for delegates, we want one and exactly one parameter without
// injection AND without name
int oneNotInjected = candidate.findOnlyParamWithoutInjection();
if (oneNotInjected >= 0) {
// getting close; but most not have name
if (candidate.paramName(oneNotInjected) == null) {
_addExplicitDelegatingCreator(ctxt, beanDesc, creators, candidate);
return;
}
}
_addExplicitPropertyCreator(ctxt, beanDesc, creators, candidate);
return;
}
AnnotatedParameter param = candidate.parameter(0);
JacksonInject.Value injectId = candidate.injection(0);
PropertyName paramName = candidate.explicitParamName(0);
BeanPropertyDefinition paramDef = candidate.propertyDef(0);
// If there's injection or explicit name, should be properties-based
boolean useProps = (paramName != null) || (injectId != null);
if (!useProps && (paramDef != null)) {
// One more thing: if implicit name matches property with a getter
// or field, we'll consider it property-based as well
// 25-May-2018, tatu: as per [databind#2051], looks like we have to get
// not implicit name, but name with possible strategy-based-rename
paramName = candidate.findImplicitParamName(0);
paramName = candidate.paramName(0);
useProps = (paramName != null) && paramDef.couldSerialize();
}
if (useProps) {
SettableBeanProperty[] properties = new SettableBeanProperty[] {
constructCreatorProperty(ctxt, beanDesc, paramName, 0, param, injectId)
};
creators.addPropertyCreator(candidate.creator(), true, properties);
return;
}
_handleSingleArgumentCreator(creators, candidate.creator(), true, true);
// one more thing: sever link to creator property, to avoid possible later
// problems with "unresolved" constructor property
if (paramDef != null) {
((POJOPropertyBuilder) paramDef).removeConstructors();
}
}
|
src/main/java/com/fasterxml/jackson/databind/deser/BasicDeserializerFactory.java
|
Implicit constructor property names are not renamed properly with PropertyNamingStrategy
|
(note: spin-off from FasterXML/jackson-modules-java8#67)
Looks like something with linking of creator properties (constructor arguments for annotated/discovered constructor) to "regular" properties does not work when using PropertyNamingStrategy. Apparently this was working better until 2.9.1, but broke with 2.9.2.
| 701 | 752 |
JacksonDatabind-97
|
public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException
{
if (_value == null) {
ctxt.defaultSerializeNull(gen);
} else if (_value instanceof JsonSerializable) {
((JsonSerializable) _value).serialize(gen, ctxt);
} else {
// 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
// this to preserve contextual information
gen.writeObject(_value);
}
}
|
public final void serialize(JsonGenerator gen, SerializerProvider ctxt) throws IOException
{
if (_value == null) {
ctxt.defaultSerializeNull(gen);
} else if (_value instanceof JsonSerializable) {
((JsonSerializable) _value).serialize(gen, ctxt);
} else {
// 25-May-2018, tatu: [databind#1991] do not call via generator but through context;
// this to preserve contextual information
ctxt.defaultSerializeValue(_value, gen);
}
}
|
src/main/java/com/fasterxml/jackson/databind/node/POJONode.java
|
Context attributes are not passed/available to custom serializer if object is in POJO
|
Below is a test case where I create a custom serializer and use it to serialize an object 1) in a HashMap and 2) in an ObjectNode. In both cases I pass attribute to the serializer like this:
mapper.writer().withAttribute("myAttr", "Hello!")
Serializing HashMap works as expected, but during ObjectNode serialization the attribute is null . It seems that in both cases the custom serializer should get access to the passed attribute and so both lines in the output should contain "Hello!"
Produced output from running testCase.test()
{"data":{"aStr":"The value is: Hello!"}}
{"data":{"aStr":"The value is: NULL"}}
Test case:
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ser.std.StdSerializer;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
public class TestCase {
public final static ObjectMapper mapper = new ObjectMapper();
@JsonSerialize(using = TestCase.CustomSer.class)
public static class Data {
public String aStr;
}
public static class CustomSer extends StdSerializer<Data> {
public CustomSer() {
super(Data.class);
}
@Override
public void serialize(Data value, JsonGenerator gen, SerializerProvider provider) throws IOException {
String attrStr = (String) provider.getAttribute("myAttr");
gen.writeStartObject();
gen.writeObjectField("aStr", "The value is: " + (attrStr == null ? "NULL" : attrStr));
gen.writeEndObject();
}
}
public static void test() throws IOException {
Data data = new Data();
data.aStr = "Hello";
Map<String, Object> mapTest = new HashMap<>();
mapTest.put("data", data);
ObjectNode treeTest = mapper.createObjectNode();
treeTest.putPOJO("data", data);
String mapOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(mapTest);
System.out.println(mapOut);
String treeOut = mapper.writer().withAttribute("myAttr", "Hello!").writeValueAsString(treeTest);
System.out.println(treeOut);
}
}
| 105 | 116 |
JacksonDatabind-99
|
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
return sb.toString();
}
|
protected String buildCanonicalName()
{
StringBuilder sb = new StringBuilder();
sb.append(_class.getName());
sb.append('<');
sb.append(_referencedType.toCanonical());
sb.append('>');
return sb.toString();
}
|
src/main/java/com/fasterxml/jackson/databind/type/ReferenceType.java
|
Canonical string for reference type is built incorrectly
|
Canonical string for reference type is built incorrectly.
E.g.:
new ReferenceType(new TypeFactory(new LRUMap<Object, JavaType>(0, 10000)).constructType(Object.class), new PlaceholderForType(0)).toCanonical()
yields:
java.lang.Object<$1
while the expected value is:
java.lang.Object<$1>
| 163 | 170 |
JacksonXml-2
|
private final int _next() throws XMLStreamException
{
switch (_currentState) {
case XML_ATTRIBUTE_VALUE:
++_nextAttributeIndex;
// fall through
case XML_START_ELEMENT: // attributes to return?
if (_nextAttributeIndex < _attributeCount) {
_localName = _xmlReader.getAttributeLocalName(_nextAttributeIndex);
_namespaceURI = _xmlReader.getAttributeNamespace(_nextAttributeIndex);
_textValue = _xmlReader.getAttributeValue(_nextAttributeIndex);
return (_currentState = XML_ATTRIBUTE_NAME);
}
// otherwise need to find START/END_ELEMENT or text
String text = _collectUntilTag();
// If we have no/all-whitespace text followed by START_ELEMENT, ignore text
if (_xmlReader.getEventType() == XMLStreamReader.START_ELEMENT) {
return _initStartElement();
}
// For END_ELEMENT we will return text, if any
if (text != null) {
_textValue = text;
return (_currentState = XML_TEXT);
}
return _handleEndElement();
case XML_ATTRIBUTE_NAME:
// if we just returned name, will need to just send value next
return (_currentState = XML_ATTRIBUTE_VALUE);
case XML_TEXT:
// mixed text with other elements
// text followed by END_ELEMENT
return _handleEndElement();
case XML_END:
return XML_END;
// throw new IllegalStateException("No more XML tokens available (end of input)");
}
// Ok: must be END_ELEMENT; see what tag we get (or end)
switch (_skipUntilTag()) {
case XMLStreamConstants.END_DOCUMENT:
return (_currentState = XML_END);
case XMLStreamConstants.END_ELEMENT:
return _handleEndElement();
}
// START_ELEMENT...
return _initStartElement();
}
|
private final int _next() throws XMLStreamException
{
switch (_currentState) {
case XML_ATTRIBUTE_VALUE:
++_nextAttributeIndex;
// fall through
case XML_START_ELEMENT: // attributes to return?
if (_nextAttributeIndex < _attributeCount) {
_localName = _xmlReader.getAttributeLocalName(_nextAttributeIndex);
_namespaceURI = _xmlReader.getAttributeNamespace(_nextAttributeIndex);
_textValue = _xmlReader.getAttributeValue(_nextAttributeIndex);
return (_currentState = XML_ATTRIBUTE_NAME);
}
// otherwise need to find START/END_ELEMENT or text
String text = _collectUntilTag();
final boolean startElementNext = _xmlReader.getEventType() == XMLStreamReader.START_ELEMENT;
// If we have no/all-whitespace text followed by START_ELEMENT, ignore text
if (startElementNext) {
if (text == null || _allWs(text)) {
_mixedText = false;
return _initStartElement();
}
_mixedText = true;
_textValue = text;
return (_currentState = XML_TEXT);
}
// For END_ELEMENT we will return text, if any
if (text != null) {
_mixedText = false;
_textValue = text;
return (_currentState = XML_TEXT);
}
_mixedText = false;
return _handleEndElement();
case XML_ATTRIBUTE_NAME:
// if we just returned name, will need to just send value next
return (_currentState = XML_ATTRIBUTE_VALUE);
case XML_TEXT:
// mixed text with other elements
if (_mixedText){
_mixedText = false;
return _initStartElement();
}
// text followed by END_ELEMENT
return _handleEndElement();
case XML_END:
return XML_END;
// throw new IllegalStateException("No more XML tokens available (end of input)");
}
// Ok: must be END_ELEMENT; see what tag we get (or end)
switch (_skipUntilTag()) {
case XMLStreamConstants.END_DOCUMENT:
return (_currentState = XML_END);
case XMLStreamConstants.END_ELEMENT:
return _handleEndElement();
}
// START_ELEMENT...
return _initStartElement();
}
|
src/main/java/com/fasterxml/jackson/dataformat/xml/deser/XmlTokenStream.java
|
Mixed content not supported if there are child elements.
|
@XmlText is only supported if there are no child elements, support could be improved with some changes in XmlTokenStream.
I successfully made some changes in XmlTokenStream, it's working in my personal case, but it needs more tests.
If agreed, I could provide a patch.
Example:
Input string : `"<windSpeed units=\"kt\">27<radius>20</radius></windSpeed>"`
"CxmlWindSpeed" class :
```
public class WindSpeed {
public static class Radius {
@JacksonXmlProperty(isAttribute = true)
private String sector;
@JacksonXmlProperty(isAttribute = true)
private String units;
@JacksonXmlText
private int value;
..../ Getters and Setters code/....
}
@JacksonXmlProperty(isAttribute = true)
private String units;
@JacksonXmlProperty(isAttribute = true)
private String source;
@JacksonXmlText
private int value;
@JacksonXmlElementWrapper(useWrapping = false)
private List<Radius> radius;
..../ Getters and Setters code/....
}
```
| 309 | 356 |
JacksonXml-4
|
protected void _serializeXmlNull(JsonGenerator jgen) throws IOException
{
// 14-Nov-2016, tatu: As per [dataformat-xml#213], we may have explicitly
// configured root name...
if (jgen instanceof ToXmlGenerator) {
_initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);
}
super.serializeValue(jgen, null);
}
|
protected void _serializeXmlNull(JsonGenerator jgen) throws IOException
{
// 14-Nov-2016, tatu: As per [dataformat-xml#213], we may have explicitly
// configured root name...
QName rootName = _rootNameFromConfig();
if (rootName == null) {
rootName = ROOT_NAME_FOR_NULL;
}
if (jgen instanceof ToXmlGenerator) {
_initWithRootName((ToXmlGenerator) jgen, rootName);
}
super.serializeValue(jgen, null);
}
|
src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java
|
XmlSerializerProvider does not use withRootName config for null
|
In jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java
Line 203, I think _rootNameFromConfig() should be used if available instead of ROOT_NAME_FOR_NULL, so that withRootName() config can be used.
I don't know whether/how deser would be affected
jackson-dataformat-xml/src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java
Line 203
in
ca1c671
_initWithRootName((ToXmlGenerator) jgen, ROOT_NAME_FOR_NULL);
| 200 | 208 |
JacksonXml-5
|
protected XmlSerializerProvider(XmlSerializerProvider src) {
super(src);
// 21-May-2018, tatu: As per [dataformat-xml#282], should NOT really copy
// root name lookup as that may link back to diff version, configuration
_rootNameLookup = src._rootNameLookup;
}
|
protected XmlSerializerProvider(XmlSerializerProvider src) {
super(src);
// 21-May-2018, tatu: As per [dataformat-xml#282], should NOT really copy
// root name lookup as that may link back to diff version, configuration
_rootNameLookup = new XmlRootNameLookup();
}
|
src/main/java/com/fasterxml/jackson/dataformat/xml/ser/XmlSerializerProvider.java
|
@JacksonXmlRootElement malfunction when using it with multiple XmlMappers and disabling annotations
|
Found this in version 2.9.4 running some tests that go back and forth serializing with an XML mapper that uses annotations, and another one that ignores them. May be related to issue #171 and the cache of class annotations.
When running this code, the second print statement should use the annotation's localName but it instead uses the class name.
@JacksonXmlRootElement(localName = "myname")
public class XMLTest {
public static void main(String[] s) throws Exception {
final ObjectMapper xmlMapper = new XmlMapper();
final ObjectMapper noAnnotationsXmlMapper = xmlMapper.copy()
.configure(MapperFeature.USE_ANNOTATIONS, false)
.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
System.out.println(noAnnotationsXmlMapper.writeValueAsString(new XMLTest()));
System.out.println(xmlMapper.writeValueAsString(new XMLTest()));
}
}
Output:
<XMLTest/>
<XMLTest/>
| 55 | 60 |
Jsoup-1
|
private void normalise(Element element) {
List<Node> toMove = new ArrayList<Node>();
for (Node node: element.childNodes) {
if (node instanceof TextNode) {
TextNode tn = (TextNode) node;
if (!tn.isBlank())
toMove.add(tn);
}
}
for (Node node: toMove) {
element.removeChild(node);
body().appendChild(new TextNode(" ", ""));
body().appendChild(node);
}
}
|
private void normalise(Element element) {
List<Node> toMove = new ArrayList<Node>();
for (Node node: element.childNodes) {
if (node instanceof TextNode) {
TextNode tn = (TextNode) node;
if (!tn.isBlank())
toMove.add(tn);
}
}
for (Node node: toMove) {
element.removeChild(node);
body().prependChild(node);
body().prependChild(new TextNode(" ", ""));
}
}
|
src/main/java/org/jsoup/nodes/Document.java
|
Parsing a HTML snippet causes the leading text to be moved to back
|
Code:
String html = "foo <b>bar</b> baz";
String text = Jsoup.parse(html).text();
System.out.println(text);
Result:
bar baz foo
Expected:
foo bar baz
| 113 | 128 |
Jsoup-10
|
public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
String relUrl = attr(attributeKey);
if (!hasAttr(attributeKey)) {
return ""; // nothing to make absolute with
} else {
URL base;
try {
try {
base = new URL(baseUri);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute may be abs on its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
// workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
URL abs = new URL(base, relUrl);
return abs.toExternalForm();
} catch (MalformedURLException e) {
return "";
}
}
}
|
public String absUrl(String attributeKey) {
Validate.notEmpty(attributeKey);
String relUrl = attr(attributeKey);
if (!hasAttr(attributeKey)) {
return ""; // nothing to make absolute with
} else {
URL base;
try {
try {
base = new URL(baseUri);
} catch (MalformedURLException e) {
// the base is unsuitable, but the attribute may be abs on its own, so try that
URL abs = new URL(relUrl);
return abs.toExternalForm();
}
// workaround: java resolves '//path/file + ?foo' to '//path/?foo', not '//path/file?foo' as desired
if (relUrl.startsWith("?"))
relUrl = base.getPath() + relUrl;
URL abs = new URL(base, relUrl);
return abs.toExternalForm();
} catch (MalformedURLException e) {
return "";
}
}
}
|
src/main/java/org/jsoup/nodes/Node.java
|
attr("abs:href") , absUrl("href")
|
Document doc = Jsoup.parse(new URL("http://www.oschina.net/bbs/thread/12975"), 5*1000);
Elements es = doc.select("a[href]");
for(Iterator it = es.iterator();it.hasNext();){
Element e = it.next();
System.out.println(e.absUrl("href"));
}
attr("abs:href") ------ <a href="?p=1">1</a>
result: ------------------- http://www.oschina.net/bbs/thread/?p=1
I think it's a wrong result~.
The correct results should be "http://www.oschina.net/bbs/thread/12975?p=1"
| 156 | 179 |
Jsoup-13
|
public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
return attributes.hasKey(attributeKey);
}
|
public boolean hasAttr(String attributeKey) {
Validate.notNull(attributeKey);
if (attributeKey.toLowerCase().startsWith("abs:")) {
String key = attributeKey.substring("abs:".length());
if (attributes.hasKey(key) && !absUrl(key).equals(""))
return true;
}
return attributes.hasKey(attributeKey);
}
|
src/main/java/org/jsoup/nodes/Node.java
|
abs: attribute prefix does not work on Elements.attr()
|
Elements.attr() iterates on its element to look for the first one with the given attrbute.
If I try to get the attribute abs:href, the test element.hasAttr("abs:herf") fails, and the returned value is an empty string.
| 104 | 108 |
Jsoup-19
|
private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
String value = el.absUrl(attr.getKey());
if (!preserveRelativeLinks)
attr.setValue(value);
for (Protocol protocol : protocols) {
String prot = protocol.toString() + ":";
if (value.toLowerCase().startsWith(prot)) {
return true;
}
}
return false;
}
|
private boolean testValidProtocol(Element el, Attribute attr, Set<Protocol> protocols) {
// try to resolve relative urls to abs, and optionally update the attribute so output html has abs.
// rels without a baseuri get removed
String value = el.absUrl(attr.getKey());
if (value.length() == 0)
value = attr.getValue(); // if it could not be made abs, run as-is to allow custom unknown protocols
if (!preserveRelativeLinks)
attr.setValue(value);
for (Protocol protocol : protocols) {
String prot = protocol.toString() + ":";
if (value.toLowerCase().startsWith(prot)) {
return true;
}
}
return false;
}
|
src/main/java/org/jsoup/safety/Whitelist.java
|
Cleaning html containing the cid identifier breaks images
|
Ok, so in mail type HTML the following is common
The item after CID: can be almost anything (US-ASCII I think) and of any length. It corresponds to an image linked elsewhere in MIME say like this
--mimebounday
Content-ID:
Content-Type: image/jpeg.....
(snip)
So, to mark a long story somewhat shorter, I use Jsoup's sanitizer extensively. However, I need these CID references to be preserved post sanitization. addProtocols does not work because the items are not valid URLs. As a result
the above becomes . Which for my purposes is not good :)
| 338 | 352 |
Jsoup-2
|
private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (tagName.length() == 0) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
Element child = new Element(tag, baseUri, attributes);
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
addChildToParent(child, isEmptyElement);
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
Node dataNode;
if (tag.equals(titleTag) || tag.equals(textareaTag)) // want to show as text, but not contain inside tags (so not a data tag?)
dataNode = TextNode.createFromEncoded(data, baseUri);
else
dataNode = new DataNode(data, baseUri); // data not encoded but raw (for " in script)
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (href.length() != 0) { // ignore <base target> etc
baseUri = href;
doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
}
|
private void parseStartTag() {
tq.consume("<");
String tagName = tq.consumeWord();
if (tagName.length() == 0) { // doesn't look like a start tag after all; put < back on stack and handle as text
tq.addFirst("<");
parseTextNode();
return;
}
Attributes attributes = new Attributes();
while (!tq.matchesAny("<", "/>", ">") && !tq.isEmpty()) {
Attribute attribute = parseAttribute();
if (attribute != null)
attributes.put(attribute);
}
Tag tag = Tag.valueOf(tagName);
Element child = new Element(tag, baseUri, attributes);
boolean isEmptyElement = tag.isEmpty(); // empty element if empty tag (e.g. img) or self-closed el (<div/>
if (tq.matchChomp("/>")) { // close empty element or tag
isEmptyElement = true;
} else {
tq.matchChomp(">");
}
addChildToParent(child, isEmptyElement);
// pc data only tags (textarea, script): chomp to end tag, add content as text node
if (tag.isData()) {
String data = tq.chompTo("</" + tagName);
tq.chompTo(">");
popStackToClose(tag);
Node dataNode;
if (tag.equals(titleTag) || tag.equals(textareaTag)) // want to show as text, but not contain inside tags (so not a data tag?)
dataNode = TextNode.createFromEncoded(data, baseUri);
else
dataNode = new DataNode(data, baseUri); // data not encoded but raw (for " in script)
child.appendChild(dataNode);
}
// <base href>: update the base uri
if (child.tagName().equals("base")) {
String href = child.absUrl("href");
if (href.length() != 0) { // ignore <base target> etc
baseUri = href;
doc.setBaseUri(href); // set on the doc so doc.createElement(Tag) will get updated base
}
}
}
|
src/main/java/org/jsoup/parser/Parser.java
|
Unadorned text following data-only tags doesn't parse properly
|
This HTML, parsed and immediately printed out, results in:
<html>
<body>
<script type="text/javascript">
var inside = true;
</script>
this should be outside.
</body>
</html>
Results:
<html>
<head>
</head>
<body>
<script type="text/javascript">
var inside = true;
this should be outside.
</script>
</body>
</html>
Note how "this should be outside" ends up inside the <script> tag, instead of following it. From what I can tell, this only happens to data-only tags.
| 116 | 165 |
Jsoup-20
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset");
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (doc == null) {
// there are times where there is a spurious byte-order-mark at the start of the text. Shouldn't be present
// in utf-8. If after decoding, there is a BOM, strip it; otherwise will cause the parser to go straight
// into head mode
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = meta.hasAttr("http-equiv") ? getCharsetFromContentType(meta.attr("content")) : meta.attr("charset");
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (doc == null) {
// there are times where there is a spurious byte-order-mark at the start of the text. Shouldn't be present
// in utf-8. If after decoding, there is a BOM, strip it; otherwise will cause the parser to go straight
// into head mode
if (docData.charAt(0) == 65279)
docData = docData.substring(1);
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
src/main/java/org/jsoup/helper/DataUtil.java
|
Some html file's head element will be empty
|
Hello, Jonathan
I love Jsoup, and handling many html files.
But today, I'm under the problem.
When parse with Jsoup, some html file's head element will be empty.
Sample html is here -> http://dl.dropbox.com/u/972460/test.html
Please help me.
| 73 | 103 |
Jsoup-24
|
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
r.advance();
return;
}
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
anythingElse(t, r);
break;
}
} else {
anythingElse(t, r);
}
}
|
void read(Tokeniser t, CharacterReader r) {
if (r.matchesLetter()) {
String name = r.consumeLetterSequence();
t.tagPending.appendTagName(name.toLowerCase());
t.dataBuffer.append(name);
return;
}
if (t.isAppropriateEndTagToken() && !r.isEmpty()) {
char c = r.consume();
switch (c) {
case '\t':
case '\n':
case '\f':
case ' ':
t.transition(BeforeAttributeName);
break;
case '/':
t.transition(SelfClosingStartTag);
break;
case '>':
t.emitTagPending();
t.transition(Data);
break;
default:
t.dataBuffer.append(c);
anythingElse(t, r);
break;
}
} else {
anythingElse(t, r);
}
}
|
src/main/java/org/jsoup/parser/TokeniserState.java
|
1.6.0 dropping a ' on a particular javascript string
|
Loses a single quote when the javascript contains a partial tag, exampled pared from ad section of http://scienceblogs.com/pharyngula. Note in the result that '</scr is missing closing ' :
Input:
<HTML>
<body>
<div>
<script language="JavaScript1.1">
document.write('</scr' + 'ipt>');
</script>
</div>
</body>
</HTML>
Result:
<html>
<body>
<div>
<script language="JavaScript1.1">
document.write('</scr + 'ipt>');
</script>
</div>
</body>
</html>
| 553 | 586 |
Jsoup-26
|
public Document clean(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
copySafeNodes(dirtyDocument.body(), clean.body());
return clean;
}
|
public Document clean(Document dirtyDocument) {
Validate.notNull(dirtyDocument);
Document clean = Document.createShell(dirtyDocument.baseUri());
if (dirtyDocument.body() != null) // frameset documents won't have a body. the clean doc will have empty body.
copySafeNodes(dirtyDocument.body(), clean.body());
return clean;
}
|
src/main/java/org/jsoup/safety/Cleaner.java
|
NullpointerException when applying Cleaner to a frameset
|
To reproduce:
Create/find a html document of a frameset.
Parse the html.
Create a Cleaner instance and call the clean method with the document from step 2.
NullPointerException
Cause:
In Cleaner.clean(Document) (https://github.com/jhy/jsoup/blob/master/src/main/java/org/jsoup/safety/Cleaner.java#L43) the copySafeNodes is called with the document.body(). However, this is null when handling a frameset document.
Expected:
An empty document or perhaps null returned. But not a nullpointerException.
| 39 | 46 |
Jsoup-27
|
static String getCharsetFromContentType(String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
charset = charset.toUpperCase(Locale.ENGLISH);
return charset;
}
return null;
}
|
static String getCharsetFromContentType(String contentType) {
if (contentType == null) return null;
Matcher m = charsetPattern.matcher(contentType);
if (m.find()) {
String charset = m.group(1).trim();
if (Charset.isSupported(charset)) return charset;
charset = charset.toUpperCase(Locale.ENGLISH);
if (Charset.isSupported(charset)) return charset;
}
return null;
}
|
src/main/java/org/jsoup/helper/DataUtil.java
|
Invalid HTTP-Response header leads to exception
|
In particular case a HTTP-Webpage responses with a invalid HTTP-Charset field (delivered UFT8 instead of UTF8).
This leads to an UnsupportedCharsetException in org.jsoup.helper.DataUtil at around Line 93(?) where :
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
I fixed it by wrapping a try catch statement around these two lines such that:
try{
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
} catch(UnsupportedCharsetException e){
return parseByteData(byteData,(String)null,baseUri,parser);
}
It now falls back to the none charset argument assigned clause, and tries to detect the character set via HTML.
| 127 | 136 |
Jsoup-32
|
public Element clone() {
Element clone = (Element) super.clone();
clone.classNames();
return clone;
}
|
public Element clone() {
Element clone = (Element) super.clone();
clone.classNames = null; // derived on first hit, otherwise gets a pointer to source classnames
return clone;
}
|
src/main/java/org/jsoup/nodes/Element.java
|
Element.clone() wrongly shared a same classNames Set instance
|
In the clone() method of Node, the Object.clone() is called, if the original element's classNames Set had been initialized before clone, the original classNames Set will be set to the new cloned Element instance due to the JDK's clone mechanism. Thus, the old element and the newly cloned Element will share a same classNames Set instance.
| 1,136 | 1,140 |
Jsoup-33
|
Element insert(Token.StartTag startTag) {
// handle empty unknown tags
// when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag.
if (startTag.isSelfClosing()) {
Element el = insertEmpty(startTag);
stack.add(el);
tokeniser.emit(new Token.EndTag(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing
return el;
}
Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);
insert(el);
return el;
}
|
Element insert(Token.StartTag startTag) {
// handle empty unknown tags
// when the spec expects an empty tag, will directly hit insertEmpty, so won't generate this fake end tag.
if (startTag.isSelfClosing()) {
Element el = insertEmpty(startTag);
stack.add(el);
tokeniser.transition(TokeniserState.Data); // handles <script />, otherwise needs breakout steps from script data
tokeniser.emit(new Token.EndTag(el.tagName())); // ensure we get out of whatever state we are in. emitted for yielded processing
return el;
}
Element el = new Element(Tag.valueOf(startTag.name()), baseUri, startTag.attributes);
insert(el);
return el;
}
|
src/main/java/org/jsoup/parser/HtmlTreeBuilder.java
|
Self-closing script tag causes remainder of document to be html-escaped.
|
When a self-closing script block is encountered it appears that the state transitions do not account for the closing tag, so the rest of the document is considered to be in the body of the script tag, and so is escaped.
The unit test HtmlParserTest.handlesKnownEmptyBlocks() will fail if a self-closing script tag is included in the String h.
| 156 | 169 |
Jsoup-34
|
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]);
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
|
int nextIndexOf(CharSequence seq) {
// doesn't handle scanning for surrogates
char startChar = seq.charAt(0);
for (int offset = pos; offset < length; offset++) {
// scan to first instance of startchar:
if (startChar != input[offset])
while(++offset < length && startChar != input[offset]);
int i = offset + 1;
int last = i + seq.length()-1;
if (offset < length && last <= length) {
for (int j = 1; i < last && seq.charAt(j) == input[i]; i++, j++);
if (i == last) // found full sequence
return offset - pos;
}
}
return -1;
}
|
src/main/java/org/jsoup/parser/CharacterReader.java
|
Parser error on commented CDATA
|
Jsoup gives the following error when trying to parse this HTML: https://gist.github.com/felipehummel/6122799
java.lang.ArrayIndexOutOfBoundsException: 8666
at org.jsoup.parser.CharacterReader.nextIndexOf(CharacterReader.java:92)
at org.jsoup.parser.CharacterReader.consumeTo(CharacterReader.java:112)
at org.jsoup.parser.TokeniserState$67.read(TokeniserState.java:1789)
at org.jsoup.parser.Tokeniser.read(Tokeniser.java:42)
at org.jsoup.parser.TreeBuilder.runParser(TreeBuilder.java:47)
at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:41)
at org.jsoup.parser.HtmlTreeBuilder.parse(HtmlTreeBuilder.java:37)
at org.jsoup.parser.Parser.parse(Parser.java:90)
at org.jsoup.Jsoup.parse(Jsoup.java:58)
...
The HTML is from a entry in a RSS feed. If I remove the line:
// ]]
or just the
]]
Then it parses the HTML nicely.
Does this syntax error should really throw an exception or it should be silently ignored?
| 82 | 98 |
Jsoup-37
|
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return accum.toString().trim();
}
|
public String html() {
StringBuilder accum = new StringBuilder();
html(accum);
return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString();
}
|
src/main/java/org/jsoup/nodes/Element.java
|
Whitespaces are discared in Element.html() method
|
Hi,
I'm trying to make an exact copy of a document (changing just a couple of attributes and appending a few nodes) and the trim() inside the Element.html() is killing me.
I'm using Parsers.xml() and no prettyPrint.
I think this trim should be enabled for prettyPrint only.
| 1,098 | 1,102 |
Jsoup-39
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
} else {
foundCharset = meta.attr("charset");
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
// UTF-8 BOM indicator. takes precedence over everything else. rarely used. re-decodes incase above decoded incorrectly
if (docData.length() > 0 && docData.charAt(0) == 65279) {
byteData.rewind();
docData = Charset.forName(defaultCharset).decode(byteData).toString();
docData = docData.substring(1);
charsetName = defaultCharset;
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
} else {
foundCharset = meta.attr("charset");
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
// UTF-8 BOM indicator. takes precedence over everything else. rarely used. re-decodes incase above decoded incorrectly
if (docData.length() > 0 && docData.charAt(0) == 65279) {
byteData.rewind();
docData = Charset.forName(defaultCharset).decode(byteData).toString();
docData = docData.substring(1);
charsetName = defaultCharset;
doc = null;
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
src/main/java/org/jsoup/helper/DataUtil.java
|
JSoup incorrectly moves content from the <head> section into <body> for sample URL
|
If you load the following URL:
http://jornutzon.sydneyoperahouse.com/home.htm
into:
http://try.jsoup.org/
then it will move the content from the "head" section into the "body" section. The URL
being parsed validates using the W3C validator:
http://validator.w3.org/check?uri=http%3A%2F%2Fjornutzon.sydneyoperahouse.com%2Fhome.htm&charset=%28detect+automatically%29&doctype=Inline&ss=1&group=0&user-agent=W3C_Validator%2F1.3+http%3A%2F%2Fvalidator.w3.org%2Fservices
We are using JSoup 1.7.2
| 76 | 125 |
Jsoup-40
|
public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
Validate.notEmpty(name);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
}
|
public DocumentType(String name, String publicId, String systemId, String baseUri) {
super(baseUri);
attr("name", name);
attr("publicId", publicId);
attr("systemId", systemId);
}
|
src/main/java/org/jsoup/nodes/DocumentType.java
|
"<!DOCTYPE>" IllegalArgumentException: String must not be empty
|
While this may be a contrived example, Jsoup.parse("<!DOCTYPE>") throws an exception, this was unexpected. Possibly related, a proper document with <!DOCTYPE> (no name) is generating corrupt html e.g. "<!DOCTYPE <html> ..." (missing right angle bracket on DOCTYPE.)
Spec says "When a DOCTYPE token is created, its name, public identifier, and system identifier must be marked as missing (which is a distinct state from the empty string), [...]"
| 19 | 26 |
Jsoup-41
|
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return this == o;
}
|
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
if (!super.equals(o)) return false;
Element element = (Element) o;
return tag.equals(element.tag);
}
|
src/main/java/org/jsoup/nodes/Element.java
|
Element.hashCode() ignores the content text of the element.
|
Found this question on SO, OP was using Element.hashCode() and it wasn't woring right.
The problem is that when jsoup generates the hashCode of an Element, the content text of the element will be ignored, and the hashCode is generated only based on the attributes, and the hashCode of the parent Element.
Using the following HTML:
<html>
<head>
</head>
<body>
<div style="blah">TODO: write content</div>
<div style="blah">Nothing here</div>
<p style="test">Empty</p>
<p style="nothing">Empty</p>
</body>
</html>
And the following code:
String html = //HTML posted above
Document doc = Jsoup.parse(html);
Elements elements = doc.select("[style]");
for (Element e : elements) {
System.out.println(e.hashCode());
}
It gives:
-148184373
-148184373
-1050420242
2013043377
I believe the hashCode should be different for the first two Elements, since the content is text is different. Or is this intended behaviour?
| 1,168 | 1,176 |
Jsoup-43
|
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element.equals(search))
return i;
}
return null;
}
|
private static <E extends Element> Integer indexInList(Element search, List<E> elements) {
Validate.notNull(search);
Validate.notNull(elements);
for (int i = 0; i < elements.size(); i++) {
E element = elements.get(i);
if (element == search)
return i;
}
return null;
}
|
src/main/java/org/jsoup/nodes/Element.java
|
Unexpected behavior in elementSiblingIndex
|
The documentation for elementSiblingIndex states "Get the list index of this element in its element sibling list. I.e. if this is the first element sibling, returns 0".
This would imply that if
n=myElem.elementSiblingIndex();
then
myElem.parent().children().get(n)==myElem.
However, this is not how elementSiblingIndex behaves. What is guaranteed is that
myElem.parent().children().get(n).equals(myElem).
For example, if both row 2 and row 5 of a table are
<tr><td>Cell1</td><td>Cell2</td></tr>
then the Element object associated with both rows will have the same elementSiblingIndex().
| 568 | 578 |
Jsoup-45
|
void resetInsertionMode() {
boolean last = false;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (pos == 0) {
last = true;
node = contextElement;
}
String name = node.nodeName();
if ("select".equals(name)) {
transition(HtmlTreeBuilderState.InSelect);
break; // frag
} else if (("td".equals(name) || "td".equals(name) && !last)) {
transition(HtmlTreeBuilderState.InCell);
break;
} else if ("tr".equals(name)) {
transition(HtmlTreeBuilderState.InRow);
break;
} else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) {
transition(HtmlTreeBuilderState.InTableBody);
break;
} else if ("caption".equals(name)) {
transition(HtmlTreeBuilderState.InCaption);
break;
} else if ("colgroup".equals(name)) {
transition(HtmlTreeBuilderState.InColumnGroup);
break; // frag
} else if ("table".equals(name)) {
transition(HtmlTreeBuilderState.InTable);
break;
} else if ("head".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
} else if ("body".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break;
} else if ("frameset".equals(name)) {
transition(HtmlTreeBuilderState.InFrameset);
break; // frag
} else if ("html".equals(name)) {
transition(HtmlTreeBuilderState.BeforeHead);
break; // frag
} else if (last) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
}
}
}
|
void resetInsertionMode() {
boolean last = false;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (pos == 0) {
last = true;
node = contextElement;
}
String name = node.nodeName();
if ("select".equals(name)) {
transition(HtmlTreeBuilderState.InSelect);
break; // frag
} else if (("td".equals(name) || "th".equals(name) && !last)) {
transition(HtmlTreeBuilderState.InCell);
break;
} else if ("tr".equals(name)) {
transition(HtmlTreeBuilderState.InRow);
break;
} else if ("tbody".equals(name) || "thead".equals(name) || "tfoot".equals(name)) {
transition(HtmlTreeBuilderState.InTableBody);
break;
} else if ("caption".equals(name)) {
transition(HtmlTreeBuilderState.InCaption);
break;
} else if ("colgroup".equals(name)) {
transition(HtmlTreeBuilderState.InColumnGroup);
break; // frag
} else if ("table".equals(name)) {
transition(HtmlTreeBuilderState.InTable);
break;
} else if ("head".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
} else if ("body".equals(name)) {
transition(HtmlTreeBuilderState.InBody);
break;
} else if ("frameset".equals(name)) {
transition(HtmlTreeBuilderState.InFrameset);
break; // frag
} else if ("html".equals(name)) {
transition(HtmlTreeBuilderState.BeforeHead);
break; // frag
} else if (last) {
transition(HtmlTreeBuilderState.InBody);
break; // frag
}
}
}
|
src/main/java/org/jsoup/parser/HtmlTreeBuilder.java
|
An issue where a table nested within a TH cell would parse to an incorrect tree
| 382 | 429 |
|
Jsoup-48
|
void processResponseHeaders(Map<String, List<String>> resHeaders) {
for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
String name = entry.getKey();
if (name == null)
continue; // http/1.1 line
List<String> values = entry.getValue();
if (name.equalsIgnoreCase("Set-Cookie")) {
for (String value : values) {
if (value == null)
continue;
TokenQueue cd = new TokenQueue(value);
String cookieName = cd.chompTo("=").trim();
String cookieVal = cd.consumeTo(";").trim();
// ignores path, date, domain, validateTLSCertificates et al. req'd?
// name not blank, value not null
if (cookieName.length() > 0)
cookie(cookieName, cookieVal);
}
} else { // combine same header names with comma: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
if (!values.isEmpty())
header(name, values.get(0));
}
}
}
|
void processResponseHeaders(Map<String, List<String>> resHeaders) {
for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) {
String name = entry.getKey();
if (name == null)
continue; // http/1.1 line
List<String> values = entry.getValue();
if (name.equalsIgnoreCase("Set-Cookie")) {
for (String value : values) {
if (value == null)
continue;
TokenQueue cd = new TokenQueue(value);
String cookieName = cd.chompTo("=").trim();
String cookieVal = cd.consumeTo(";").trim();
// ignores path, date, domain, validateTLSCertificates et al. req'd?
// name not blank, value not null
if (cookieName.length() > 0)
cookie(cookieName, cookieVal);
}
} else { // combine same header names with comma: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
if (values.size() == 1)
header(name, values.get(0));
else if (values.size() > 1) {
StringBuilder accum = new StringBuilder();
for (int i = 0; i < values.size(); i++) {
final String val = values.get(i);
if (i != 0)
accum.append(", ");
accum.append(val);
}
header(name, accum.toString());
}
}
}
}
|
src/main/java/org/jsoup/helper/HttpConnection.java
|
A small bug for duplicate tuple in response header
|
for response headers have duplicate tuple,
in this case
X-Powered-By:PHP/5.2.8
X-Powered-By:ASP.NET
Jsoup can only get the second one
if I run header(“X-powered-by”)
I got Asp.NET
URL:http://01pt.com/
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Content-Encoding:gzip
Content-Length:16224
Content-Type:text/html;charset=gb2312
Date:Thu, 27 Aug 2015 09:22:40 GMT
Expires:Thu, 19 Nov 1981 08:52:00 GMT
Pragma:no-cache
Server:Microsoft-IIS/7.5
Vary:Accept-Encoding
X-Powered-By:PHP/5.2.8
X-Powered-By:ASP.NET
The bug is because
if (!values.isEmpty()) header(name, values.get(0));
I change it to
if (!values.isEmpty()) {
String val = "";
for(String str: values) {
val = val.concat(str).concat(" ");
}
header(name, val);
}
then I am able to get “PHP/5.2.8 ASP.NET” when I run header(“X-powered-by”)
void processResponseHeaders(Map<String, List> resHeaders) {
for (Map.Entry<String, List> entry : resHeaders.entrySet()) {
String name = entry.getKey();
if (name == null)
continue; // http/1.1 line
List<String> values = entry.getValue();
if (name.equalsIgnoreCase("Set-Cookie")) {
for (String value : values) {
if (value == null)
continue;
TokenQueue cd = new TokenQueue(value);
String cookieName = cd.chompTo("=").trim();
String cookieVal = cd.consumeTo(";").trim();
// ignores path, date, domain, validateTLSCertificates et al. req'd?
// name not blank, value not null
if (cookieName.length() > 0)
cookie(cookieName, cookieVal);
}
} else { // only take the first instance of each header
if (!values.isEmpty())
header(name, values.get(0));
}
}
}
| 753 | 777 |
Jsoup-49
|
protected void addChildren(int index, Node... children) {
Validate.noNullElements(children);
ensureChildNodes();
for (int i = children.length - 1; i >= 0; i--) {
Node in = children[i];
reparentChild(in);
childNodes.add(index, in);
}
reindexChildren(index);
}
|
protected void addChildren(int index, Node... children) {
Validate.noNullElements(children);
ensureChildNodes();
for (int i = children.length - 1; i >= 0; i--) {
Node in = children[i];
reparentChild(in);
childNodes.add(index, in);
reindexChildren(index);
}
}
|
src/main/java/org/jsoup/nodes/Node.java
|
Bug in Element.insertChildren()
|
When using org.jsoup.nodes.Element.insertChildren(int, Collection<? extends Node>) to move (more than one!) child-elements from one parent-element to the same parent, but different index then it produces wrong results.
The problem is that the first Element's 'move' leaves the siblingIndex unchanged and then the second 'move' removes a wrong element and produces some crap. Maybe calling reindexChildren() inside the loop in addChildren() fixes this.
Version 1.8.3.
Workaround: call remove() on the elements before passing them to insertChildren()
Easy Test Case:
@Test
public void mustCorrectlyMoveChildrenInsideOneParentElement() {
Document doc = new Document( "" );
Element body = doc.appendElement( "body" );
body.appendElement( "div1" );
body.appendElement( "div2" );
Element div3 = body.appendElement( "div3" );
Element div4 = body.appendElement( "div4" );
ArrayList<Element> toMove = new ArrayList<Element>() {
{
add( div3 );
add( div4 );
}
};
body.insertChildren( 0, toMove );
String result = doc.toString().replaceAll( "\\s+", "" );
assertEquals( "<body><div3></div3><div4></div4><div1></div1><div2></div2></body>", result );
}
| 438 | 447 |
Jsoup-5
|
private Attribute parseAttribute() {
tq.consumeWhitespace();
String key = tq.consumeAttributeKey();
String value = "";
tq.consumeWhitespace();
if (tq.matchChomp("=")) {
tq.consumeWhitespace();
if (tq.matchChomp(SQ)) {
value = tq.chompTo(SQ);
} else if (tq.matchChomp(DQ)) {
value = tq.chompTo(DQ);
} else {
StringBuilder valueAccum = new StringBuilder();
// no ' or " to look for, so scan to end tag or space (or end of stream)
while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) {
valueAccum.append(tq.consume());
}
value = valueAccum.toString();
}
tq.consumeWhitespace();
}
if (key.length() != 0)
return Attribute.createFromEncoded(key, value);
else {
tq.consume();
return null;
}
}
|
private Attribute parseAttribute() {
tq.consumeWhitespace();
String key = tq.consumeAttributeKey();
String value = "";
tq.consumeWhitespace();
if (tq.matchChomp("=")) {
tq.consumeWhitespace();
if (tq.matchChomp(SQ)) {
value = tq.chompTo(SQ);
} else if (tq.matchChomp(DQ)) {
value = tq.chompTo(DQ);
} else {
StringBuilder valueAccum = new StringBuilder();
// no ' or " to look for, so scan to end tag or space (or end of stream)
while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) {
valueAccum.append(tq.consume());
}
value = valueAccum.toString();
}
tq.consumeWhitespace();
}
if (key.length() != 0)
return Attribute.createFromEncoded(key, value);
else {
if (value.length() == 0) // no key, no val; unknown char, keep popping so not get stuck
tq.advance();
return null;
}
}
|
src/main/java/org/jsoup/parser/Parser.java
|
StringIndexOutOfBoundsException when testing whether String content is valid HTML
|
If I try to parse a tag with an equals sign (an empty attribute) but without any single or double quotes around an attribute value, then I get a StringIndexOutOfBoundsException. The stack trace is pasted below.
An example String would be "<a =a"
The following JUnit test case should not throw a StringIndexOutOfBoundsException:
import static org.junit.Assert.assertTrue;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
import org.junit.Test;
public class BadAttributeTest {
@test
public void aTagWithABadAttributeIsValid() throws Exception {
assertTrue(Jsoup.isValid("<a =a", Whitelist.relaxed()));
}
}
java.lang.StringIndexOutOfBoundsException: String index out of range: 13
at java.lang.String.charAt(String.java:686)
at org.jsoup.parser.TokenQueue.consume(TokenQueue.java:130)
at org.jsoup.parser.Parser.parseAttribute(Parser.java:207)
at org.jsoup.parser.Parser.parseStartTag(Parser.java:142)
at org.jsoup.parser.Parser.parse(Parser.java:91)
at org.jsoup.parser.Parser.parseBodyFragment(Parser.java:64)
at org.jsoup.Jsoup.parseBodyFragment(Jsoup.java:99)
at org.jsoup.Jsoup.isValid(Jsoup.java:155)
| 181 | 210 |
Jsoup-50
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
// look for BOM - overrides any other header or input
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = null;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
}
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (docData.length() > 0 && docData.charAt(0) == UNICODE_BOM) {
byteData.rewind();
docData = Charset.forName(defaultCharset).decode(byteData).toString();
docData = docData.substring(1);
charsetName = defaultCharset;
doc = null;
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) {
String docData;
Document doc = null;
// look for BOM - overrides any other header or input
byteData.mark();
byte[] bom = new byte[4];
byteData.get(bom);
byteData.rewind();
if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF || // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { // LE
charsetName = "UTF-32"; // and I hope it's on your system
} else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF || // BE
bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) {
charsetName = "UTF-16"; // in all Javas
} else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) {
charsetName = "UTF-8"; // in all Javas
byteData.position(3); // 16 and 32 decoders consume the BOM to determine be/le; utf-8 should be consumed
}
if (charsetName == null) { // determine from meta. safe parse as UTF-8
// look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312">
docData = Charset.forName(defaultCharset).decode(byteData).toString();
doc = parser.parseInput(docData, baseUri);
Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first();
if (meta != null) { // if not found, will keep utf-8 as best attempt
String foundCharset = null;
if (meta.hasAttr("http-equiv")) {
foundCharset = getCharsetFromContentType(meta.attr("content"));
}
if (foundCharset == null && meta.hasAttr("charset")) {
try {
if (Charset.isSupported(meta.attr("charset"))) {
foundCharset = meta.attr("charset");
}
} catch (IllegalCharsetNameException e) {
foundCharset = null;
}
}
if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode
foundCharset = foundCharset.trim().replaceAll("[\"']", "");
charsetName = foundCharset;
byteData.rewind();
docData = Charset.forName(foundCharset).decode(byteData).toString();
doc = null;
}
}
} else { // specified by content type header (or by user on file load)
Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML");
docData = Charset.forName(charsetName).decode(byteData).toString();
}
if (doc == null) {
doc = parser.parseInput(docData, baseUri);
doc.outputSettings().charset(charsetName);
}
return doc;
}
|
src/main/java/org/jsoup/helper/DataUtil.java
|
UTF16 streams with BOM are processed as UTF-8
|
The handling of the character encoding in org.jsoup.helper.DataUtil.parseByteData(...) is bugged when the input is an UTF16 stream with unicode BOM. This method does a check for presence of a BOM and, if it finds one, incorrectly assumes that this was a UTF-8 BOM. To fix this, the code would have to check the raw BOM bytes as the distinction between the various BOMs is lost after conversion to characters. See also: http://unicode.org/faq/utf_bom.html#bom4
| 88 | 138 |
Jsoup-51
|
boolean matchesLetter() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z');
}
|
boolean matchesLetter() {
if (isEmpty())
return false;
char c = input[pos];
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c);
}
|
src/main/java/org/jsoup/parser/CharacterReader.java
|
Problem in reading XML file containing Japanese tag names
|
Hello,
I have XML file containing Japanese tag names and values.
JSOUP is not parsing this Japanese tags.
I am using JSOUP library (version: 1.8.3).
Please help me to solve this issue.
e.g. ( XML File to reproduce problem )
<進捗推移グラフ>
<開始予定凡例名 表示状態="0" 線色="00CED1">①設計 開始予定</開始予定凡例名>
</進捗推移グラフ>
//// **** Source Code ******
Document doc = Jsoup.parse(XMLString.toString(),"UTF-8",Parser.xmlParser());
Elements objElementCollection = doc.getAllElements();
int iElementsSize=objElementCollection.size();
for(Element objCurrent : objElementCollection)
{
String szTag=objCurrent.tagName();
for (TextNode tnTextNode : objCurrent.textNodes())
{
String szVal=tnTextNode.text();
}
}
| 296 | 301 |
Jsoup-53
|
public String chompBalanced(char open, char close) {
int start = -1;
int end = -1;
int depth = 0;
char last = 0;
do {
if (isEmpty()) break;
Character c = consume();
if (last == 0 || last != ESC) {
if (c.equals(open)) {
depth++;
if (start == -1)
start = pos;
}
else if (c.equals(close))
depth--;
}
if (depth > 0 && last != 0)
end = pos; // don't include the outer match pair in the return
last = c;
} while (depth > 0);
return (end >= 0) ? queue.substring(start, end) : "";
}
|
public String chompBalanced(char open, char close) {
int start = -1;
int end = -1;
int depth = 0;
char last = 0;
boolean inQuote = false;
do {
if (isEmpty()) break;
Character c = consume();
if (last == 0 || last != ESC) {
if (c.equals('\'') || c.equals('"') && c != open)
inQuote = !inQuote;
if (inQuote)
continue;
if (c.equals(open)) {
depth++;
if (start == -1)
start = pos;
}
else if (c.equals(close))
depth--;
}
if (depth > 0 && last != 0)
end = pos; // don't include the outer match pair in the return
last = c;
} while (depth > 0);
return (end >= 0) ? queue.substring(start, end) : "";
}
|
src/main/java/org/jsoup/parser/TokenQueue.java
|
Parse failed with org.jsoup.select.Selector$SelectorParseException when selector has unbalanced '(' or '[' or ')' or ']'
|
Selector I am having as following div.card-content2:has(a.subtitle[title= MySubTitle:)]) OR a.title[title=MyTitle :] ]
| 260 | 284 |
Jsoup-54
|
private void copyAttributes(org.jsoup.nodes.Node source, Element el) {
for (Attribute attribute : source.attributes()) {
// valid xml attribute names are: ^[a-zA-Z_:][-a-zA-Z0-9_:.]
String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", "");
el.setAttribute(key, attribute.getValue());
}
}
|
private void copyAttributes(org.jsoup.nodes.Node source, Element el) {
for (Attribute attribute : source.attributes()) {
// valid xml attribute names are: ^[a-zA-Z_:][-a-zA-Z0-9_:.]
String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", "");
if (key.matches("[a-zA-Z_:]{1}[-a-zA-Z0-9_:.]*"))
el.setAttribute(key, attribute.getValue());
}
}
|
src/main/java/org/jsoup/helper/W3CDom.java
|
INVALID_CHARACTER_ERR when converting Document to W3C
|
A recent ClearQuest version has an HTML generation bug, which is ignored by both Chrome and Internet Explorer. Jsoup.parse is also successful:
org.jsoup.nodes.Document doc = Jsoup.parse("<html><head></head><body style=\"color: red\" \"></body></html>");
(Please note the single quotation mark at the end of the body start tag.)
But trying to convert this to a W3C document fails:
new W3CDom().fromJsoup(doc);
Exception in thread "main" org.w3c.dom.DOMException: INVALID_CHARACTER_ERR: An invalid or illegal XML character is specified.
at org.apache.xerces.dom.CoreDocumentImpl.createAttribute(Unknown Source)
at org.apache.xerces.dom.ElementImpl.setAttribute(Unknown Source)
at org.jsoup.helper.W3CDom$W3CBuilder.copyAttributes(W3CDom.java:124)
at org.jsoup.helper.W3CDom$W3CBuilder.head(W3CDom.java:92)
at org.jsoup.select.NodeTraversor.traverse(NodeTraversor.java:31)
at org.jsoup.helper.W3CDom.convert(W3CDom.java:66)
at org.jsoup.helper.W3CDom.fromJsoup(W3CDom.java:46)
Perhaps copyAttributes() should ignore invalid attributes, or catch exactly this error, and ignore it, or W3CDom could have flags to ignore such errors...
| 122 | 128 |
Jsoup-55
|
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.tagPending.selfClosing = true;
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
t.transition(BeforeAttributeName);
}
}
|
void read(Tokeniser t, CharacterReader r) {
char c = r.consume();
switch (c) {
case '>':
t.tagPending.selfClosing = true;
t.emitTagPending();
t.transition(Data);
break;
case eof:
t.eofError(this);
t.transition(Data);
break;
default:
t.error(this);
r.unconsume();
t.transition(BeforeAttributeName);
}
}
|
src/main/java/org/jsoup/parser/TokeniserState.java
|
Parse slash in attibutes
|
Hello,
I don't know if it is a bug or not, but when I'm parsing:
<img /onerror="a()"/>
The result of the parsers is:
<img nerror="a()"/>
Is it OK? can I change the parser behavior for those types of tags?
| 869 | 885 |
Jsoup-57
|
public void removeIgnoreCase(String key) {
Validate.notEmpty(key);
if (attributes == null)
return;
for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext(); ) {
String attrKey = it.next();
if (attrKey.equalsIgnoreCase(key))
attributes.remove(attrKey);
}
}
|
public void removeIgnoreCase(String key) {
Validate.notEmpty(key);
if (attributes == null)
return;
for (Iterator<String> it = attributes.keySet().iterator(); it.hasNext(); ) {
String attrKey = it.next();
if (attrKey.equalsIgnoreCase(key))
it.remove();
}
}
|
src/main/java/org/jsoup/nodes/Attributes.java
|
removeIgnoreCase ConcurrentModificationException
|
When testing out the removeIgnoreCase method, I'm now seeing a ConcurrentModificationException with code like: element.select("abc").first().removeAttr("attr1").removeAttr("attr2");
It appears to be due to using a foreach loop over the LinkedHashMap to do the removal. Changing to do the removal directly with an iterator fixes this issue.
Like so:
for (Iterator<Map.Entry<String, Attribute>> iter = attributes.entrySet().iterator(); iter.hasNext();) {
Map.Entry<String, Attribute> entry = iter.next();
if (entry.getKey().equalsIgnoreCase("key1")) {
iter.remove();
}
}
| 118 | 127 |
Jsoup-59
|
final void newAttribute() {
if (attributes == null)
attributes = new Attributes();
if (pendingAttributeName != null) {
// the tokeniser has skipped whitespace control chars, but trimming could collapse to empty for other control codes, so verify here
pendingAttributeName = pendingAttributeName.trim();
Attribute attribute;
if (hasPendingAttributeValue)
attribute = new Attribute(pendingAttributeName,
pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS);
else if (hasEmptyAttributeValue)
attribute = new Attribute(pendingAttributeName, "");
else
attribute = new BooleanAttribute(pendingAttributeName);
attributes.put(attribute);
}
pendingAttributeName = null;
hasEmptyAttributeValue = false;
hasPendingAttributeValue = false;
reset(pendingAttributeValue);
pendingAttributeValueS = null;
}
|
final void newAttribute() {
if (attributes == null)
attributes = new Attributes();
if (pendingAttributeName != null) {
// the tokeniser has skipped whitespace control chars, but trimming could collapse to empty for other control codes, so verify here
pendingAttributeName = pendingAttributeName.trim();
if (pendingAttributeName.length() > 0) {
Attribute attribute;
if (hasPendingAttributeValue)
attribute = new Attribute(pendingAttributeName,
pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS);
else if (hasEmptyAttributeValue)
attribute = new Attribute(pendingAttributeName, "");
else
attribute = new BooleanAttribute(pendingAttributeName);
attributes.put(attribute);
}
}
pendingAttributeName = null;
hasEmptyAttributeValue = false;
hasPendingAttributeValue = false;
reset(pendingAttributeValue);
pendingAttributeValueS = null;
}
|
src/main/java/org/jsoup/parser/Token.java
|
Jsoup.clean control characters throws: IllegalArgumentException: String must not be empty
|
I found that when running Jsoup.clean() on a string that contains the format below, Jsoup throws: IllegalArgumentException: String must not be empty.
The problematic string format:
'<a/*>', (where * is a control char).
i.e. < char followed by a letter (a-z), then any chars, / and any control char (ASCII 0-31) except 0, 9-10, 12-13, any chars, and a > char.
| 100 | 122 |
Jsoup-6
|
static String unescape(String string) {
if (!string.contains("&"))
return string;
Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);?
StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs
// todo: replace m.appendReplacement with own impl, so StringBuilder and quoteReplacement not required
while (m.find()) {
int charval = -1;
String num = m.group(3);
if (num != null) {
try {
int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator
charval = Integer.valueOf(num, base);
} catch (NumberFormatException e) {
} // skip
} else {
String name = m.group(1);
if (full.containsKey(name))
charval = full.get(name);
}
if (charval != -1 || charval > 0xFFFF) { // out of range
String c = Character.toString((char) charval);
m.appendReplacement(accum, c);
} else {
m.appendReplacement(accum, m.group(0));
}
}
m.appendTail(accum);
return accum.toString();
}
|
static String unescape(String string) {
if (!string.contains("&"))
return string;
Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);?
StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs
// todo: replace m.appendReplacement with own impl, so StringBuilder and quoteReplacement not required
while (m.find()) {
int charval = -1;
String num = m.group(3);
if (num != null) {
try {
int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator
charval = Integer.valueOf(num, base);
} catch (NumberFormatException e) {
} // skip
} else {
String name = m.group(1);
if (full.containsKey(name))
charval = full.get(name);
}
if (charval != -1 || charval > 0xFFFF) { // out of range
String c = Character.toString((char) charval);
m.appendReplacement(accum, Matcher.quoteReplacement(c));
} else {
m.appendReplacement(accum, Matcher.quoteReplacement(m.group(0))); // replace with original string
}
}
m.appendTail(accum);
return accum.toString();
}
|
src/main/java/org/jsoup/nodes/Entities.java
|
StringIndexOutOfBoundsException when parsing link http://news.yahoo.com/s/nm/20100831/bs_nm/us_gm_china
|
java.lang.StringIndexOutOfBoundsException: String index out of range: 1
at java.lang.String.charAt(String.java:686)
at java.util.regex.Matcher.appendReplacement(Matcher.java:711)
at org.jsoup.nodes.Entities.unescape(Entities.java:69)
at org.jsoup.nodes.TextNode.createFromEncoded(TextNode.java:95)
at org.jsoup.parser.Parser.parseTextNode(Parser.java:222)
at org.jsoup.parser.Parser.parse(Parser.java:94)
at org.jsoup.parser.Parser.parse(Parser.java:54)
at org.jsoup.Jsoup.parse(Jsoup.java:30)
| 45 | 77 |
Jsoup-62
|
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {
String name = t.asEndTag().normalName();
ArrayList<Element> stack = tb.getStack();
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (node.nodeName().equals(name)) {
tb.generateImpliedEndTags(name);
if (!name.equals(tb.currentElement().nodeName()))
tb.error(this);
tb.popStackToClose(name);
break;
} else {
if (tb.isSpecial(node)) {
tb.error(this);
return false;
}
}
}
return true;
}
|
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) {
String name = t.asEndTag().name(); // matches with case sensitivity if enabled
ArrayList<Element> stack = tb.getStack();
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element node = stack.get(pos);
if (node.nodeName().equals(name)) {
tb.generateImpliedEndTags(name);
if (!name.equals(tb.currentElement().nodeName()))
tb.error(this);
tb.popStackToClose(name);
break;
} else {
if (tb.isSpecial(node)) {
tb.error(this);
return false;
}
}
}
return true;
}
|
src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java
|
Wrong parsing of case sensitive HTML
|
Executing :
String xml="<r><X>A</X><y>B</y></r>";
Parser parser = Parser.htmlParser();
parser.settings(ParseSettings.preserveCase);
org.jsoup.nodes.Document _doc = parser.parseInput(xml, "/");
Results in :
<html>
<head></head>
<body>
<r>
<X>
A
<y>
B
</y>
</X>
</r>
</body>
</html>
Manual hacking : remove all .toLowerCase() invocations from Token.java (normalName=...)
| 763 | 782 |
Jsoup-64
|
private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {
tb.insert(startTag);
tb.tokeniser.transition(TokeniserState.Rawtext);
tb.markInsertionMode();
tb.transition(Text);
}
|
private static void handleRawtext(Token.StartTag startTag, HtmlTreeBuilder tb) {
tb.tokeniser.transition(TokeniserState.Rawtext);
tb.markInsertionMode();
tb.transition(Text);
tb.insert(startTag);
}
|
src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java
|
Incorrect handling of self-closing tags noframes, style and title cause remainder of document to be html-escaped
|
Given the input:
<html>
<head>
<style /> <!-- < - - this is the culprit -->
</head>
<body>
<p>Whatever</p>
</body>
</html>
JSoup 1.8.2 and also http://try.jsoup.org/~lJwWpjXYUSTBeBZhdEnS3Mt56g4 will produce:
<html>
<head>
<style></style>
</head>
<body>
</head> <body> <p>Whatever</p> </body> </html>
</body>
</html>
With <title/> instead of <style/>, the result is different but still wrong (http://try.jsoup.org/~BZ3uoMki-r904fZxUOWJgLJO7r8 ):
<html>
<head>
<title></title>
</head>
<body>
</head>
<p>Whatever</p>
</body>
</html>
That weirdness was fixed for <script> with Issue #305: http://try.jsoup.org/~3Ms6TQCrrdaA_uPgxgURYYvwFAg
<html>
<head>
<script></script>
</head>
<body>
<p>Whatever</p>
</body>
</html>
Looking at the source, it seems only the HtmlTreeBuilderState handling for <noframes>, <style> and <title> in the methods handleRawText and handleRcData doesn't get along with the self-closing tags.
Any other tagname I've checked (and I tried to cover all branches of that case StartTag switch) results in a good parse similar to the <script> case, which is what I'd expect.
Thanks for looking into this!
| 1,488 | 1,493 |
Jsoup-68
|
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {
// https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope
int bottom = stack.size() -1;
if (bottom > MaxScopeSearchDepth) {
bottom = MaxScopeSearchDepth;
}
final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;
// don't walk too far up the tree
for (int pos = bottom; pos >= top; pos--) {
final String elName = stack.get(pos).nodeName();
if (inSorted(elName, targetNames))
return true;
if (inSorted(elName, baseTypes))
return false;
if (extraTypes != null && inSorted(elName, extraTypes))
return false;
}
//Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes)
return false;
}
|
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) {
// https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope
final int bottom = stack.size() -1;
final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0;
// don't walk too far up the tree
for (int pos = bottom; pos >= top; pos--) {
final String elName = stack.get(pos).nodeName();
if (inSorted(elName, targetNames))
return true;
if (inSorted(elName, baseTypes))
return false;
if (extraTypes != null && inSorted(elName, extraTypes))
return false;
}
//Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes)
return false;
}
|
src/main/java/org/jsoup/parser/HtmlTreeBuilder.java
|
version 1.11.1 java.lang.StackOverflowError
|
version 1.10.3 no problem
version 1.11.1 java.lang.StackOverflowError
Example URL:
http://szshb.nxszs.gov.cn/
http://www.lnfsfda.gov.cn/
http://www.beihai.gov.cn/
http://www.fsepb.gov.cn/
http://www.bhem.gov.cn
| 466 | 486 |
Jsoup-70
|
static boolean preserveWhitespace(Node node) {
// looks only at this element and five levels up, to prevent recursion & needless stack searches
if (node != null && node instanceof Element) {
Element el = (Element) node;
if (el.tag.preserveWhitespace())
return true;
else
return el.parent() != null && el.parent().tag.preserveWhitespace();
}
return false;
}
|
static boolean preserveWhitespace(Node node) {
// looks only at this element and five levels up, to prevent recursion & needless stack searches
if (node != null && node instanceof Element) {
Element el = (Element) node;
int i = 0;
do {
if (el.tag.preserveWhitespace())
return true;
el = el.parent();
i++;
} while (i < 6 && el != null);
}
return false;
}
|
src/main/java/org/jsoup/nodes/Element.java
|
Whitespaces not properly handled in <pre> tag
|
If a "pre" tag contains deep nested tags, whitespaces in nested tags are not preserved.
Example:
String s = "<pre><code>\n"
+ " message <span style=\"color:red\"> other \n message with \n"
+ " whitespaces </span>\n"
+ "</code></pre>";
Document doc = Jsoup.parse(s);
System.out.println(doc.select("pre").first().outerHtml());
Will output:
<pre><code>
message <span style="color:red"> other message with whiptespaces </span>
</pre></code>
Output is OK if we omit the "code" tag
| 1,087 | 1,097 |
Jsoup-72
|
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {
// limit (no cache):
if (count > maxStringCacheLen)
return new String(charBuf, start, count);
// calculate hash:
int hash = 0;
int offset = start;
for (int i = 0; i < count; i++) {
hash = 31 * hash + charBuf[offset++];
}
// get from cache
final int index = hash & stringCache.length - 1;
String cached = stringCache[index];
if (cached == null) { // miss, add
cached = new String(charBuf, start, count);
stringCache[index] = cached;
} else { // hashcode hit, check equality
if (rangeEquals(charBuf, start, count, cached)) { // hit
return cached;
} else { // hashcode conflict
cached = new String(charBuf, start, count);
stringCache[index] = cached; // update the cache, as recently used strings are more likely to show up again
}
}
return cached;
}
|
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) {
// limit (no cache):
if (count > maxStringCacheLen)
return new String(charBuf, start, count);
if (count < 1)
return "";
// calculate hash:
int hash = 0;
int offset = start;
for (int i = 0; i < count; i++) {
hash = 31 * hash + charBuf[offset++];
}
// get from cache
final int index = hash & stringCache.length - 1;
String cached = stringCache[index];
if (cached == null) { // miss, add
cached = new String(charBuf, start, count);
stringCache[index] = cached;
} else { // hashcode hit, check equality
if (rangeEquals(charBuf, start, count, cached)) { // hit
return cached;
} else { // hashcode conflict
cached = new String(charBuf, start, count);
stringCache[index] = cached; // update the cache, as recently used strings are more likely to show up again
}
}
return cached;
}
|
src/main/java/org/jsoup/parser/CharacterReader.java
|
StringIndexOutOfBoundsException as of jsoup 1.11.1
|
Example:
Jsoup.parse(new URL("https://gist.githubusercontent.com/valodzka/91ed27043628e9023009e503d41f1aad/raw/a15f68671e6f0517e48fdac812983b85fea27c16/test.html"), 10_000);
| 423 | 451 |
Jsoup-75
|
final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {
final int sz = size;
for (int i = 0; i < sz; i++) {
// inlined from Attribute.html()
final String key = keys[i];
final String val = vals[i];
accum.append(' ').append(key);
// collapse checked=null, checked="", checked=checked; write out others
if (!(out.syntax() == Document.OutputSettings.Syntax.html
&& (val == null || val.equals(key) && Attribute.isBooleanAttribute(key)))) {
accum.append("=\"");
Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false);
accum.append('"');
}
}
}
|
final void html(final Appendable accum, final Document.OutputSettings out) throws IOException {
final int sz = size;
for (int i = 0; i < sz; i++) {
// inlined from Attribute.html()
final String key = keys[i];
final String val = vals[i];
accum.append(' ').append(key);
// collapse checked=null, checked="", checked=checked; write out others
if (!Attribute.shouldCollapseAttribute(key, val, out)) {
accum.append("=\"");
Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false);
accum.append('"');
}
}
}
|
src/main/java/org/jsoup/nodes/Attributes.java
|
Regression - Boolean attributes not collapsed when using HTML syntax
|
Hello,
First off, thanks for a really useful library.
So, upgrading from 1.10.2 to 1.11.2 we see that boolean attributes are no longer collapsed when using html syntax. Example test case:
@Test
public void test() {
Document document = Jsoup.parse(
"<html><head></head><body><hr size=\"1\" noshade=\"\"></body></html>");
assertEquals("<html>\n" +
" <head></head>\n" +
" <body>\n" +
" <hr size=\"1\" noshade>\n" +
" </body>\n" +
"</html>",
document.outerHtml());
}
Tracked it down to commit "Refactored Attributes to be an array pair vs LinkedHashSet " ea1fb65. The Attibutes.html(final Appendable accum, final Document.OutputSettings out) method no longer uses Attribute and fails to check the value of the attribute for an empty string(line 320).
If I may also suggest to use Attribute.shouldCollapseAttribute(String key, String val, Document.OutputSettings out) instead as a single source of truth as the boolean expression is complex enough and easy to make a mistake. Not sure if this would have an impact in performance though but I am guessing that optimizer will inline the call at some point anyways?
| 310 | 326 |
Jsoup-77
|
private void popStackToClose(Token.EndTag endTag) {
String elName = endTag.name();
Element firstFound = null;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (next.nodeName().equals(elName)) {
firstFound = next;
break;
}
}
if (firstFound == null)
return; // not found, skip
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos);
if (next == firstFound)
break;
}
}
|
private void popStackToClose(Token.EndTag endTag) {
String elName = endTag.normalName();
Element firstFound = null;
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
if (next.nodeName().equals(elName)) {
firstFound = next;
break;
}
}
if (firstFound == null)
return; // not found, skip
for (int pos = stack.size() -1; pos >= 0; pos--) {
Element next = stack.get(pos);
stack.remove(pos);
if (next == firstFound)
break;
}
}
|
src/main/java/org/jsoup/parser/XmlTreeBuilder.java
|
xmlParser() with ParseSettings.htmlDefault does not put end tag to lower case
|
@Test public void test() {
Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault);
Document document = Jsoup.parse("<div>test</DIV><p></p>", "", parser);
assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // fail -> toString() = "<div>\n test\n <p></p>\n</div>"
}
@Test public void test1() {
Parser parser = Parser.xmlParser().settings(ParseSettings.htmlDefault);
Document document = Jsoup.parse("<DIV>test</div><p></p>", "", parser);
assertEquals("<div>\n test\n</div>\n<p></p>", document.toString()); // pass
}
| 116 | 136 |
Jsoup-80
|
void insert(Token.Comment commentToken) {
Comment comment = new Comment(commentToken.getData());
Node insert = comment;
if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml)
// so we do a bit of a hack and parse the data as an element to pull the attributes out
String data = comment.getData();
if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) {
Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser());
Element el = doc.child(0);
insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!"));
insert.attributes().addAll(el.attributes());
}
}
insertNode(insert);
}
|
void insert(Token.Comment commentToken) {
Comment comment = new Comment(commentToken.getData());
Node insert = comment;
if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml)
// so we do a bit of a hack and parse the data as an element to pull the attributes out
String data = comment.getData();
if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) {
Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser());
if (doc.childNodeSize() > 0) {
Element el = doc.child(0);
insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!"));
insert.attributes().addAll(el.attributes());
} // else, we couldn't parse it as a decl, so leave as a comment
}
}
insertNode(insert);
}
|
src/main/java/org/jsoup/parser/XmlTreeBuilder.java
|
Faulty Xml Causes IndexOutOfBoundsException
|
@Test
public void parseFaultyXml() {
String xml = "<?xml version='1.0'><val>One</val>";
Document doc = Jsoup.parse(xml, "", Parser.xmlParser());
}
Results in:
java.lang.IndexOutOfBoundsException: Index: 0, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at org.jsoup.nodes.Element.child(Element.java:254)
at org.jsoup.parser.XmlTreeBuilder.insert(XmlTreeBuilder.java:91)
at org.jsoup.parser.XmlTreeBuilder.process(XmlTreeBuilder.java:49)
at org.jsoup.parser.TreeBuilder.runParser(TreeBuilder.java:52)
at org.jsoup.parser.TreeBuilder.parse(TreeBuilder.java:45)
at org.jsoup.parser.Parser.parseInput(Parser.java:34)
at org.jsoup.Jsoup.parse(Jsoup.java:45)
| 83 | 97 |
Jsoup-84
|
public void head(org.jsoup.nodes.Node source, int depth) {
namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack
if (source instanceof org.jsoup.nodes.Element) {
org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source;
String prefix = updateNamespaces(sourceEl);
String namespace = namespacesStack.peek().get(prefix);
String tagName = sourceEl.tagName();
Element el =
doc.createElementNS(namespace, tagName);
copyAttributes(sourceEl, el);
if (dest == null) { // sets up the root
doc.appendChild(el);
} else {
dest.appendChild(el);
}
dest = el; // descend
} else if (source instanceof org.jsoup.nodes.TextNode) {
org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source;
Text text = doc.createTextNode(sourceText.getWholeText());
dest.appendChild(text);
} else if (source instanceof org.jsoup.nodes.Comment) {
org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source;
Comment comment = doc.createComment(sourceComment.getData());
dest.appendChild(comment);
} else if (source instanceof org.jsoup.nodes.DataNode) {
org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source;
Text node = doc.createTextNode(sourceData.getWholeData());
dest.appendChild(node);
} else {
// unhandled
}
}
|
public void head(org.jsoup.nodes.Node source, int depth) {
namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack
if (source instanceof org.jsoup.nodes.Element) {
org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source;
String prefix = updateNamespaces(sourceEl);
String namespace = namespacesStack.peek().get(prefix);
String tagName = sourceEl.tagName();
Element el = namespace == null && tagName.contains(":") ?
doc.createElementNS("", tagName) : // doesn't have a real namespace defined
doc.createElementNS(namespace, tagName);
copyAttributes(sourceEl, el);
if (dest == null) { // sets up the root
doc.appendChild(el);
} else {
dest.appendChild(el);
}
dest = el; // descend
} else if (source instanceof org.jsoup.nodes.TextNode) {
org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source;
Text text = doc.createTextNode(sourceText.getWholeText());
dest.appendChild(text);
} else if (source instanceof org.jsoup.nodes.Comment) {
org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source;
Comment comment = doc.createComment(sourceComment.getData());
dest.appendChild(comment);
} else if (source instanceof org.jsoup.nodes.DataNode) {
org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source;
Text node = doc.createTextNode(sourceData.getWholeData());
dest.appendChild(node);
} else {
// unhandled
}
}
|
src/main/java/org/jsoup/helper/W3CDom.java
|
W3CDom Helper fails to convert whenever some namespace declarations are missing
|
Hello
I've been running into an issue where if I convert my Jsoup parsed document into a org.w3c.dom.Document with the W3CDom helper and that document happens to be missing namespace declarations we get the following exception:
NAMESPACE_ERR: An attempt is made to create or change an object in a way which is incorrect with regard to namespaces.
I've looked into this a bit and first thing I tried was using a locally forked version of the W3CDom helper that simply turned this flag off:
factory.setNamespaceAware(false);
However the issue continued, so instead I simply hacked the code to completely ignore namespaces
// (csueiras): We purposely remove any namespace because we get malformed HTML that might not be
// declaring all of it's namespaces!
Element el = doc.createElementNS("", sourceEl.tagName());
I am not completely sure if this will have any side effects, but it resolved the issues with the document I'm interacting with. I would be glad to provide a pull request if I have some guidance regarding how to properly handle this issue if it can be handled by Jsoup.
The document I'm having issues is simply making use of the Facebook like buttons using tags like this:
<fb:like ...
But there's no namespace declaration for "fb".
| 82 | 115 |
Jsoup-85
|
public Attribute(String key, String val, Attributes parent) {
Validate.notNull(key);
this.key = key.trim();
Validate.notEmpty(key); // trimming could potentially make empty, so validate here
this.val = val;
this.parent = parent;
}
|
public Attribute(String key, String val, Attributes parent) {
Validate.notNull(key);
key = key.trim();
Validate.notEmpty(key); // trimming could potentially make empty, so validate here
this.key = key;
this.val = val;
this.parent = parent;
}
|
src/main/java/org/jsoup/nodes/Attribute.java
|
Attribute.java line 45 variable key scope error, it seems should be "this.key"
|
Attribute.java Line 45, it should be:
Validate.notEmpty(this.key);
rather than
Validate.notEmpty(key);
This issue only happens when key is blank or empty, in reality this would rarely happen, but in the syntax context it is still an issue, so better fix this.
| 42 | 48 |
Jsoup-86
|
public XmlDeclaration asXmlDeclaration() {
String data = getData();
Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser());
XmlDeclaration decl = null;
if (doc.childNodeSize() > 0) {
Element el = doc.child(0);
decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!"));
decl.attributes().addAll(el.attributes());
}
return decl;
}
|
public XmlDeclaration asXmlDeclaration() {
String data = getData();
Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser());
XmlDeclaration decl = null;
if (doc.children().size() > 0) {
Element el = doc.child(0);
decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!"));
decl.attributes().addAll(el.attributes());
}
return decl;
}
|
src/main/java/org/jsoup/nodes/Comment.java
|
Jsoup 1.11.3: IndexOutOfBoundsException
|
Hi, I am using Jsoup 1.11.3. While trying to parse HTML content, I'm getting IndexOutOfBoundsException.
I am using such Jsoup call as this is the only way to parse iframe content.
Jsoup call:
Jsoup.parse(html, "", Parser.xmlParser())
HTML is here: https://files.fm/u/v43yemgb. I can't add it to the body as it's huge.
| 74 | 84 |
Jsoup-88
|
public String getValue() {
return val;
}
|
public String getValue() {
return Attributes.checkNotNull(val);
}
|
src/main/java/org/jsoup/nodes/Attribute.java
|
Attribute.getValue() broken for empty attributes since 1.11.1
|
Document doc = Jsoup.parse("<div hidden>");
Attributes attributes = doc.body().child(0).attributes();
System.out.println(String.format("Attr: '%s', value: '%s'", "hidden",
attributes.get("hidden")));
Attribute first = attributes.iterator().next();
System.out.println(String.format("Attr: '%s', value: '%s'",
first.getKey(), first.getValue()));
Expected output, as in 1.10.x
Attr: 'hidden', value: ''
Attr: 'hidden', value: ''
Output in 1.11.1-1.11.3:
Attr: 'hidden', value: ''
Attr: 'hidden', value: 'null'
| 79 | 81 |
Jsoup-89
|
public String setValue(String val) {
String oldVal = parent.get(this.key);
if (parent != null) {
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound)
parent.vals[i] = val;
}
this.val = val;
return Attributes.checkNotNull(oldVal);
}
|
public String setValue(String val) {
String oldVal = this.val;
if (parent != null) {
oldVal = parent.get(this.key); // trust the container more
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound)
parent.vals[i] = val;
}
this.val = val;
return Attributes.checkNotNull(oldVal);
}
|
src/main/java/org/jsoup/nodes/Attribute.java
|
NPE in Attribute.setValue() for attribute without parent
|
public String setValue(String val) {
String oldVal = parent.get(this.key);
if (parent != null) {
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound)
parent.vals[i] = val;
}
this.val = val;
return oldVal;
}
Its useless to check parent for null after it has been dereferenced. I guess this is a copy-paste-bug:
public void setKey(String key) {
Validate.notNull(key);
key = key.trim();
Validate.notEmpty(key); // trimming could potentially make empty, so validate here
if (parent != null) {
int i = parent.indexOfKey(this.key);
if (i != Attributes.NotFound)
parent.keys[i] = key;
}
this.key = key;
}
| 87 | 96 |
Jsoup-90
|
private static boolean looksLikeUtf8(byte[] input) {
int i = 0;
// BOM:
if (input.length >= 3 && (input[0] & 0xFF) == 0xEF
&& (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {
i = 3;
}
int end;
for (int j = input.length; i < j; ++i) {
int o = input[i];
if ((o & 0x80) == 0) {
continue; // ASCII
}
// UTF-8 leading:
if ((o & 0xE0) == 0xC0) {
end = i + 1;
} else if ((o & 0xF0) == 0xE0) {
end = i + 2;
} else if ((o & 0xF8) == 0xF0) {
end = i + 3;
} else {
return false;
}
while (i < end) {
i++;
o = input[i];
if ((o & 0xC0) != 0x80) {
return false;
}
}
}
return true;
}
|
private static boolean looksLikeUtf8(byte[] input) {
int i = 0;
// BOM:
if (input.length >= 3 && (input[0] & 0xFF) == 0xEF
&& (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) {
i = 3;
}
int end;
for (int j = input.length; i < j; ++i) {
int o = input[i];
if ((o & 0x80) == 0) {
continue; // ASCII
}
// UTF-8 leading:
if ((o & 0xE0) == 0xC0) {
end = i + 1;
} else if ((o & 0xF0) == 0xE0) {
end = i + 2;
} else if ((o & 0xF8) == 0xF0) {
end = i + 3;
} else {
return false;
}
if (end >= input.length)
return false;
while (i < end) {
i++;
o = input[i];
if ((o & 0xC0) != 0x80) {
return false;
}
}
}
return true;
}
|
src/main/java/org/jsoup/helper/HttpConnection.java
|
ArrayIndexOutOfBoundsException when parsing with some URL
|
error
Caused by: java.lang.ArrayIndexOutOfBoundsException: 11
at org.jsoup.helper.HttpConnection$Base.looksLikeUtf8(HttpConnection.java:437)
at org.jsoup.helper.HttpConnection$Base.fixHeaderEncoding(HttpConnection.java:400)
at org.jsoup.helper.HttpConnection$Base.addHeader(HttpConnection.java:386)
at org.jsoup.helper.HttpConnection$Response.processResponseHeaders(HttpConnection.java:1075)
at org.jsoup.helper.HttpConnection$Response.setupFromConnection(HttpConnection.java:1019)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:752)
at org.jsoup.helper.HttpConnection$Response.execute(HttpConnection.java:722)
at org.jsoup.helper.HttpConnection.execute(HttpConnection.java:306)
code
try {
String url = "https://www.colisprive.com/moncolis/pages/detailColis.aspx?numColis=P4000000037777930";
Connection connection = Jsoup.connect(url).referrer(url).
userAgent("Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36")
.ignoreContentType(true).timeout(20000);
connection.method(Method.GET);
return connection.execute().parse();
} catch (Exception e) {
throw new RuntimeException(e);
}
| 398 | 434 |
Jsoup-93
|
public List<Connection.KeyVal> formData() {
ArrayList<Connection.KeyVal> data = new ArrayList<>();
// iterate the form control elements and accumulate their values
for (Element el: elements) {
if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable
if (el.hasAttr("disabled")) continue; // skip disabled form inputs
String name = el.attr("name");
if (name.length() == 0) continue;
String type = el.attr("type");
if ("select".equals(el.normalName())) {
Elements options = el.select("option[selected]");
boolean set = false;
for (Element option: options) {
data.add(HttpConnection.KeyVal.create(name, option.val()));
set = true;
}
if (!set) {
Element option = el.select("option").first();
if (option != null)
data.add(HttpConnection.KeyVal.create(name, option.val()));
}
} else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// only add checkbox or radio if they have the checked attribute
if (el.hasAttr("checked")) {
final String val = el.val().length() > 0 ? el.val() : "on";
data.add(HttpConnection.KeyVal.create(name, val));
}
} else {
data.add(HttpConnection.KeyVal.create(name, el.val()));
}
}
return data;
}
|
public List<Connection.KeyVal> formData() {
ArrayList<Connection.KeyVal> data = new ArrayList<>();
// iterate the form control elements and accumulate their values
for (Element el: elements) {
if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable
if (el.hasAttr("disabled")) continue; // skip disabled form inputs
String name = el.attr("name");
if (name.length() == 0) continue;
String type = el.attr("type");
if (type.equalsIgnoreCase("button")) continue; // browsers don't submit these
if ("select".equals(el.normalName())) {
Elements options = el.select("option[selected]");
boolean set = false;
for (Element option: options) {
data.add(HttpConnection.KeyVal.create(name, option.val()));
set = true;
}
if (!set) {
Element option = el.select("option").first();
if (option != null)
data.add(HttpConnection.KeyVal.create(name, option.val()));
}
} else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) {
// only add checkbox or radio if they have the checked attribute
if (el.hasAttr("checked")) {
final String val = el.val().length() > 0 ? el.val() : "on";
data.add(HttpConnection.KeyVal.create(name, val));
}
} else {
data.add(HttpConnection.KeyVal.create(name, el.val()));
}
}
return data;
}
|
src/main/java/org/jsoup/nodes/FormElement.java
|
<input type="image"> is not special cased in formData method
|
The following code:
import org.jsoup.Jsoup;
import org.jsoup.nodes.FormElement;
class Scratch {
public static void main(String[] args) {
System.out.println(((FormElement) Jsoup.parse("<form id=f><input type=image name=x></form>").getElementById("f")).formData());
}
}
Returns the following output:
[x=]
When either [] or [x.x=0, x.y=0] is expected (not sure which, but [x=] is definitely wrong).
| 78 | 113 |
JxPath-10
|
public final Object computeValue(EvalContext context) {
return compute(args[0].computeValue(context), args[1].computeValue(context))
? Boolean.TRUE : Boolean.FALSE;
}
|
public final Object computeValue(EvalContext context) {
return compute(args[0].compute(context), args[1].compute(context))
? Boolean.TRUE : Boolean.FALSE;
}
|
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationRelationalExpression.java
|
Binary operators behaviour involving node-sets is incorrect
|
According to XPath specification:
"If both objects to be compared are node-sets, then the comparison will be true if and only if there is a node in the first node-set and a node in the second node-set such that the result of performing the comparison on the string-values of the two nodes is true. If one object to be compared is a node-set and the other is a number, then the comparison will be true if and only if there is a node in the node-set such that the result of performing the comparison on the number to be compared and on the result of converting the string-value of that node to a number using the number function is true."
But following example illustrates, that this is not a JXPath behaviour:
JXPathContext pathContext = JXPathContext
.newContext(DocumentBuilderFactory.newInstance()
.newDocumentBuilder().parse(
new InputSource(new StringReader(
"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n"
+ "<doc/>"))));
Boolean result = (Boolean) pathContext.getValue("2.0 > child1",
Boolean.class);
assertFalse(result.booleanValue());
"child1" is not found - right operand node set is empty, but result is TRUE, instead of FALSE.
Please, check greaterThan(), lesserThan(), etc methods of org.apache.xpath.objects.XObject for possible solution
| 41 | 44 |
JxPath-12
|
public static boolean testNode(Node node, NodeTest test) {
if (test == null) {
return true;
}
if (test instanceof NodeNameTest) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NodeNameTest nodeNameTest = (NodeNameTest) test;
QName testName = nodeNameTest.getNodeName();
String namespaceURI = nodeNameTest.getNamespaceURI();
boolean wildcard = nodeNameTest.isWildcard();
String testPrefix = testName.getPrefix();
if (wildcard && testPrefix == null) {
return true;
}
if (wildcard
|| testName.getName()
.equals(DOMNodePointer.getLocalName(node))) {
String nodeNS = DOMNodePointer.getNamespaceURI(node);
return equalStrings(namespaceURI, nodeNS);
}
return false;
}
if (test instanceof NodeTypeTest) {
int nodeType = node.getNodeType();
switch (((NodeTypeTest) test).getNodeType()) {
case Compiler.NODE_TYPE_NODE :
return nodeType == Node.ELEMENT_NODE
|| nodeType == Node.DOCUMENT_NODE;
case Compiler.NODE_TYPE_TEXT :
return nodeType == Node.CDATA_SECTION_NODE
|| nodeType == Node.TEXT_NODE;
case Compiler.NODE_TYPE_COMMENT :
return nodeType == Node.COMMENT_NODE;
case Compiler.NODE_TYPE_PI :
return nodeType == Node.PROCESSING_INSTRUCTION_NODE;
}
return false;
}
if (test instanceof ProcessingInstructionTest) {
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
String testPI = ((ProcessingInstructionTest) test).getTarget();
String nodePI = ((ProcessingInstruction) node).getTarget();
return testPI.equals(nodePI);
}
}
return false;
}
|
public static boolean testNode(Node node, NodeTest test) {
if (test == null) {
return true;
}
if (test instanceof NodeNameTest) {
if (node.getNodeType() != Node.ELEMENT_NODE) {
return false;
}
NodeNameTest nodeNameTest = (NodeNameTest) test;
QName testName = nodeNameTest.getNodeName();
String namespaceURI = nodeNameTest.getNamespaceURI();
boolean wildcard = nodeNameTest.isWildcard();
String testPrefix = testName.getPrefix();
if (wildcard && testPrefix == null) {
return true;
}
if (wildcard
|| testName.getName()
.equals(DOMNodePointer.getLocalName(node))) {
String nodeNS = DOMNodePointer.getNamespaceURI(node);
return equalStrings(namespaceURI, nodeNS) || nodeNS == null
&& equalStrings(testPrefix, getPrefix(node));
}
return false;
}
if (test instanceof NodeTypeTest) {
int nodeType = node.getNodeType();
switch (((NodeTypeTest) test).getNodeType()) {
case Compiler.NODE_TYPE_NODE :
return nodeType == Node.ELEMENT_NODE
|| nodeType == Node.DOCUMENT_NODE;
case Compiler.NODE_TYPE_TEXT :
return nodeType == Node.CDATA_SECTION_NODE
|| nodeType == Node.TEXT_NODE;
case Compiler.NODE_TYPE_COMMENT :
return nodeType == Node.COMMENT_NODE;
case Compiler.NODE_TYPE_PI :
return nodeType == Node.PROCESSING_INSTRUCTION_NODE;
}
return false;
}
if (test instanceof ProcessingInstructionTest) {
if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) {
String testPI = ((ProcessingInstructionTest) test).getTarget();
String nodePI = ((ProcessingInstruction) node).getTarget();
return testPI.equals(nodePI);
}
}
return false;
}
|
src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java
|
Incomplete handling of undefined namespaces
|
Mcduffey, Joe <[email protected]>
Can someone tell me how to register namespaces so that attributes with namespaces does not cause the exception
org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
unknown namespace prefix: xsi
For example the following
<ElementA A:myAttr="Mytype">
<B:ElementB>MY VALUE</B:ElementB>
</ElementA>
Would result in the following exception:
org.apache.common.ri.model.dom.DOMNodePointer.createAttribute
unknown namespace prefix: A
FYI: In this example there was a namespace decaration in the file and I also manually called the
registerNamespace(A,"/http...");
registerNamespace(B,"/http...");
There was no problem encountered for elements. Only attributes. Can someone help? Thanks.
| 87 | 136 |
JxPath-15
|
public boolean setPosition(int position) {
if (!prepared) {
prepared = true;
BasicNodeSet nodeSet = (BasicNodeSet) getNodeSet();
ArrayList pointers = new ArrayList();
for (int i = 0; i < contexts.length; i++) {
EvalContext ctx = (EvalContext) contexts[i];
while (ctx.nextSet()) {
while (ctx.nextNode()) {
NodePointer ptr = ctx.getCurrentNodePointer();
if (!pointers.contains(ptr)) {
nodeSet.add(ptr);
pointers.add(ptr);
}
}
}
}
}
return super.setPosition(position);
}
|
public boolean setPosition(int position) {
if (!prepared) {
prepared = true;
BasicNodeSet nodeSet = (BasicNodeSet) getNodeSet();
ArrayList pointers = new ArrayList();
for (int i = 0; i < contexts.length; i++) {
EvalContext ctx = (EvalContext) contexts[i];
while (ctx.nextSet()) {
while (ctx.nextNode()) {
NodePointer ptr = ctx.getCurrentNodePointer();
if (!pointers.contains(ptr)) {
pointers.add(ptr);
}
}
}
}
sortPointers(pointers);
for (Iterator it = pointers.iterator(); it.hasNext();) {
nodeSet.add((Pointer) it.next());
}
}
return super.setPosition(position);
}
|
src/java/org/apache/commons/jxpath/ri/axes/UnionContext.java
|
Core union operation does not sort result nodes according to document order
|
Source document:
<MAIN><A>avalue</A><B>bvalue</B></MAIN>
According to string() function defintion:
"A node-set is converted to a string by returning the string-value of the node in the node-set that is first in document order. If the node-set is empty, an empty string is returned."
Following XPath calculated incorrectly:
string(/MAIN/B | /MAIN/A)
Expected result: "avalue"
Actual value: "bvalue"
Reason:
sorting of result nodes is missing from CoreOperationUnion
| 45 | 64 |
JxPath-18
|
public boolean nextNode() {
super.setPosition(getCurrentPosition() + 1);
if (!setStarted) {
setStarted = true;
if (!(nodeTest instanceof NodeNameTest)) {
return false;
}
QName name = ((NodeNameTest) nodeTest).getNodeName();
iterator =
parentContext.getCurrentNodePointer().attributeIterator(name);
}
if (iterator == null) {
return false;
}
if (!iterator.setPosition(iterator.getPosition() + 1)) {
return false;
}
currentNodePointer = iterator.getNodePointer();
return true;
}
|
public boolean nextNode() {
super.setPosition(getCurrentPosition() + 1);
if (!setStarted) {
setStarted = true;
NodeNameTest nodeNameTest = null;
if (nodeTest instanceof NodeTypeTest) {
if (((NodeTypeTest) nodeTest).getNodeType() == Compiler.NODE_TYPE_NODE) {
nodeNameTest = WILDCARD_TEST;
}
}
else if (nodeTest instanceof NodeNameTest) {
nodeNameTest = (NodeNameTest) nodeTest;
}
if (nodeNameTest == null) {
return false;
}
iterator = parentContext.getCurrentNodePointer().attributeIterator(
nodeNameTest.getNodeName());
}
if (iterator == null) {
return false;
}
if (!iterator.setPosition(iterator.getPosition() + 1)) {
return false;
}
currentNodePointer = iterator.getNodePointer();
return true;
}
|
src/java/org/apache/commons/jxpath/ri/axes/AttributeContext.java
|
Issue with attribute::
|
Checking test (Issue172_CountAttributeNode) I came with the following fix for the code in AttributeContext line 72
from
-----
if (!(nodeTest instanceof NodeNameTest)) {
return false;
}
QName name = ((NodeNameTest) nodeTest).getNodeName();
------
'
to
--- (outside method)
private static final QName WILDCARD = new QName("", "*");
--- (in method)
final QName name ;
if (nodeTest instanceof NodeTypeTest)
{
if (((NodeTypeTest) nodeTest).getNodeType() == Compiler.NODE_TYPE_NODE)
name = WILDCARD;
else return false;
}
else if (nodeTest instanceof NodeNameTest) {
name = ((NodeNameTest) nodeTest).getNodeName();
}
else
{
return false;
}
| 71 | 90 |
JxPath-20
|
private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
if (left instanceof Iterator && right instanceof Iterator) {
return findMatch((Iterator) left, (Iterator) right);
}
if (left instanceof Iterator) {
return containsMatch((Iterator) left, right);
}
if (right instanceof Iterator) {
return containsMatch((Iterator) right, left);
}
double ld = InfoSetUtil.doubleValue(left);
if (Double.isNaN(ld)) {
return false;
}
double rd = InfoSetUtil.doubleValue(right);
if (Double.isNaN(rd)) {
return false;
}
return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);
}
|
private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
if (left instanceof Iterator && right instanceof Iterator) {
return findMatch((Iterator) left, (Iterator) right);
}
if (left instanceof Iterator) {
return containsMatch((Iterator) left, right);
}
if (right instanceof Iterator) {
return containsMatch(left, (Iterator) right);
}
double ld = InfoSetUtil.doubleValue(left);
if (Double.isNaN(ld)) {
return false;
}
double rd = InfoSetUtil.doubleValue(right);
if (Double.isNaN(rd)) {
return false;
}
return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);
}
|
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationRelationalExpression.java
|
relational operations do not function properly when comparing a non-Iterator LHS to an Iterator RHS
|
I have a simple JXpathContext, with the following variables: var1=0, var2=0, var3=1. When I try to evaluate the following expression - "$var1 + $var2 <= $var3", it returns false.
| 71 | 99 |
JxPath-21
|
public int getLength() {
return ValueUtils.getLength(getBaseValue());
}
|
public int getLength() {
Object baseValue = getBaseValue();
return baseValue == null ? 1 : ValueUtils.getLength(baseValue);
}
|
src/java/org/apache/commons/jxpath/ri/model/beans/PropertyPointer.java
|
null handling is inconsistent
|
Comparing a vaule to null using unequals (!=) yields false!
Map<String, Integer> m = new HashMap<String, Integer>();
m.put("a", 1);
m.put("b", null);
m.put("c", 1);
JXPathContext c = JXPathContext.newContext(m);
System.out.println(c.getValue("a != b") + " should be true");
System.out.println(c.getValue("a != c") + " should be false");
System.out.println(c.getValue("a = b") + " should be false");
System.out.println(c.getValue("a = c") + " should be true");
System.out.println(c.getValue("not(a = b)") + " should be true");
System.out.println(c.getValue("not(a = c)") + " should be false");
Output using 1.3:
false should be true
false should be false
false should be false
true should be true
true should be true
false should be false
In 1.2 it works correctly!
| 151 | 153 |
JxPath-22
|
public static String getNamespaceURI(Node node) {
if (node instanceof Document) {
node = ((Document) node).getDocumentElement();
}
Element element = (Element) node;
String uri = element.getNamespaceURI();
if (uri == null) {
String prefix = getPrefix(node);
String qname = prefix == null ? "xmlns" : "xmlns:" + prefix;
Node aNode = node;
while (aNode != null) {
if (aNode.getNodeType() == Node.ELEMENT_NODE) {
Attr attr = ((Element) aNode).getAttributeNode(qname);
if (attr != null) {
return attr.getValue();
}
}
aNode = aNode.getParentNode();
}
return null;
}
return uri;
}
|
public static String getNamespaceURI(Node node) {
if (node instanceof Document) {
node = ((Document) node).getDocumentElement();
}
Element element = (Element) node;
String uri = element.getNamespaceURI();
if (uri == null) {
String prefix = getPrefix(node);
String qname = prefix == null ? "xmlns" : "xmlns:" + prefix;
Node aNode = node;
while (aNode != null) {
if (aNode.getNodeType() == Node.ELEMENT_NODE) {
Attr attr = ((Element) aNode).getAttributeNode(qname);
if (attr != null) {
uri = attr.getValue();
break;
}
}
aNode = aNode.getParentNode();
}
}
return "".equals(uri) ? null : uri;
}
|
src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java
|
Resetting the default namespace causes a serious endless loop when requesting .asPath() on a node.
|
sample smaller case:
<...>
<b:foo xmlns:b="bla" xmlns="test111"> <!-- No nodes are placed in the tree within ns "test111" but the attribute is still there.-->
<b:bar>a</b:bar> <!-- is in ns 'bla' -->
<test xmlns=""></test> <!-- does not have a namespace -->
</b:foo>
</...>
when requesting .asPath() on the 'test' node, it loops in org.apache.commons.jxpath.ri.NamespaceResolver.getPrefix(NodePointer, String),
and if it didn't loop it would create a wrong xpath '//b:fo/null:test' DOMNodePointer.asPath().
So I think that the fix should be in org.apache.commons.jxpath.ri.model.dom.DOMNodePointer.asPath()
....
String ln = DOMNodePointer.getLocalName(node);
String nsURI = getNamespaceURI();
if (nsURI == null) {
buffer.append(ln);
buffer.append('[');
buffer.append(getRelativePositionByName()).append(']');
}
else {
String prefix = getNamespaceResolver().getPrefix(nsURI);
if (prefix != null) {
...
should become
...
String ln = DOMNodePointer.getLocalName(node);
String nsURI = getNamespaceURI();
if (nsURI == null || nsURI.length() == 0) { // check for empty string which means that the node doesn't have a namespace.
buffer.append(ln);
buffer.append('[');
buffer.append(getRelativePositionByName()).append(']');
}
else {
String prefix = getNamespaceResolver().getPrefix(nsURI);
if (prefix != null) {
...
| 672 | 697 |
JxPath-5
|
private int compareNodePointers(
NodePointer p1,
int depth1,
NodePointer p2,
int depth2)
{
if (depth1 < depth2) {
int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);
return r == 0 ? -1 : r;
}
if (depth1 > depth2) {
int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2);
return r == 0 ? 1 : r;
}
if (p1 == null && p2 == null) {
return 0;
}
if (p1 != null && p1.equals(p2)) {
return 0;
}
if (depth1 == 1) {
throw new JXPathException(
"Cannot compare pointers that do not belong to the same tree: '"
+ p1 + "' and '" + p2 + "'");
}
int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1);
if (r != 0) {
return r;
}
return p1.parent.compareChildNodePointers(p1, p2);
}
|
private int compareNodePointers(
NodePointer p1,
int depth1,
NodePointer p2,
int depth2)
{
if (depth1 < depth2) {
int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1);
return r == 0 ? -1 : r;
}
if (depth1 > depth2) {
int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2);
return r == 0 ? 1 : r;
}
if (p1 == null && p2 == null) {
return 0;
}
if (p1 != null && p1.equals(p2)) {
return 0;
}
if (depth1 == 1) {
return 0;
}
int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1);
if (r != 0) {
return r;
}
return p1.parent.compareChildNodePointers(p1, p2);
}
|
src/java/org/apache/commons/jxpath/ri/model/NodePointer.java
|
Cannot compare pointers that do not belong to the same tree
|
For XPath "$var | /MAIN/A" exception is thrown:
org.apache.commons.jxpath.JXPathException: Cannot compare pointers that do not belong to the same tree: '$var' and ''
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:665)
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
at org.apache.commons.jxpath.ri.model.NodePointer.compareNodePointers(NodePointer.java:649)
at org.apache.commons.jxpath.ri.model.NodePointer.compareTo(NodePointer.java:639)
at java.util.Arrays.mergeSort(Arrays.java:1152)
at java.util.Arrays.sort(Arrays.java:1079)
at java.util.Collections.sort(Collections.java:113)
at org.apache.commons.jxpath.ri.EvalContext.constructIterator(EvalContext.java:176)
at org.apache.commons.jxpath.ri.EvalContext.hasNext(EvalContext.java:100)
at org.apache.commons.jxpath.JXPathContext.selectNodes(JXPathContext.java:648)
at org.apache.commons.jxpath.ri.model.VariablePointerTestCase.testUnionOfVariableAndNode(VariablePointerTestCase.java:76)
| 642 | 675 |
JxPath-6
|
protected boolean equal(
EvalContext context,
Expression left,
Expression right)
{
Object l = left.compute(context);
Object r = right.compute(context);
System.err.println("COMPARING: " +
(l == null ? "null" : l.getClass().getName()) + " " +
(r == null ? "null" : r.getClass().getName()));
if (l instanceof InitialContext || l instanceof SelfContext) {
l = ((EvalContext) l).getSingleNodePointer();
}
if (r instanceof InitialContext || r instanceof SelfContext) {
r = ((EvalContext) r).getSingleNodePointer();
}
if (l instanceof Collection) {
l = ((Collection) l).iterator();
}
if (r instanceof Collection) {
r = ((Collection) r).iterator();
}
if ((l instanceof Iterator) && !(r instanceof Iterator)) {
return contains((Iterator) l, r);
}
if (!(l instanceof Iterator) && (r instanceof Iterator)) {
return contains((Iterator) r, l);
}
if (l instanceof Iterator && r instanceof Iterator) {
return findMatch((Iterator) l, (Iterator) r);
}
return equal(l, r);
}
|
protected boolean equal(
EvalContext context,
Expression left,
Expression right)
{
Object l = left.compute(context);
Object r = right.compute(context);
System.err.println("COMPARING: " +
(l == null ? "null" : l.getClass().getName()) + " " +
(r == null ? "null" : r.getClass().getName()));
if (l instanceof InitialContext) {
((EvalContext) l).reset();
}
if (l instanceof SelfContext) {
l = ((EvalContext) l).getSingleNodePointer();
}
if (r instanceof InitialContext) {
((EvalContext) r).reset();
}
if (r instanceof SelfContext) {
r = ((EvalContext) r).getSingleNodePointer();
}
if (l instanceof Collection) {
l = ((Collection) l).iterator();
}
if (r instanceof Collection) {
r = ((Collection) r).iterator();
}
if ((l instanceof Iterator) && !(r instanceof Iterator)) {
return contains((Iterator) l, r);
}
if (!(l instanceof Iterator) && (r instanceof Iterator)) {
return contains((Iterator) r, l);
}
if (l instanceof Iterator && r instanceof Iterator) {
return findMatch((Iterator) l, (Iterator) r);
}
return equal(l, r);
}
|
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationCompare.java
|
equality test for multi-valued variables does not conform to spec
|
given e.g. variable d=
{"a", "b"}
, the spec implies that "$d = 'a'" and that "$d = 'b'". Instead of iterating the variable's components its immediate content (here, the String[]) is compared, causing the aforementioned assertions to fail.
| 45 | 83 |
JxPath-8
|
private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
if (left instanceof Iterator && right instanceof Iterator) {
return findMatch((Iterator) left, (Iterator) right);
}
if (left instanceof Iterator) {
return containsMatch((Iterator) left, right);
}
if (right instanceof Iterator) {
return containsMatch((Iterator) right, left);
}
double ld = InfoSetUtil.doubleValue(left);
double rd = InfoSetUtil.doubleValue(right);
return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);
}
|
private boolean compute(Object left, Object right) {
left = reduce(left);
right = reduce(right);
if (left instanceof InitialContext) {
((InitialContext) left).reset();
}
if (right instanceof InitialContext) {
((InitialContext) right).reset();
}
if (left instanceof Iterator && right instanceof Iterator) {
return findMatch((Iterator) left, (Iterator) right);
}
if (left instanceof Iterator) {
return containsMatch((Iterator) left, right);
}
if (right instanceof Iterator) {
return containsMatch((Iterator) right, left);
}
double ld = InfoSetUtil.doubleValue(left);
if (Double.isNaN(ld)) {
return false;
}
double rd = InfoSetUtil.doubleValue(right);
if (Double.isNaN(rd)) {
return false;
}
return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1);
}
|
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationRelationalExpression.java
|
Comparing with NaN is incorrect
|
'NaN' > 'NaN' is true, but should be FALSE
| 56 | 78 |
Lang-10
|
private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) {
boolean wasWhite= false;
for(int i= 0; i<value.length(); ++i) {
char c= value.charAt(i);
if(Character.isWhitespace(c)) {
if(!wasWhite) {
wasWhite= true;
regex.append("\\s*+");
}
continue;
}
wasWhite= false;
switch(c) {
case '\'':
if(unquote) {
if(++i==value.length()) {
return regex;
}
c= value.charAt(i);
}
break;
case '?':
case '[':
case ']':
case '(':
case ')':
case '{':
case '}':
case '\\':
case '|':
case '*':
case '+':
case '^':
case '$':
case '.':
regex.append('\\');
}
regex.append(c);
}
return regex;
}
|
private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) {
for(int i= 0; i<value.length(); ++i) {
char c= value.charAt(i);
switch(c) {
case '\'':
if(unquote) {
if(++i==value.length()) {
return regex;
}
c= value.charAt(i);
}
break;
case '?':
case '[':
case ']':
case '(':
case ')':
case '{':
case '}':
case '\\':
case '|':
case '*':
case '+':
case '^':
case '$':
case '.':
regex.append('\\');
}
regex.append(c);
}
return regex;
}
|
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
|
FastDateParser does not handle white-space properly
|
The SimpleDateFormat Javadoc does not treat white-space specially, however FastDateParser treats a single white-space as being any number of white-space characters.
This means that FDP will parse dates that fail when parsed by SDP.
| 303 | 343 |
Lang-11
|
public static String random(int count, int start, int end, boolean letters, boolean numbers,
char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
}
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch)
|| numbers && Character.isDigit(ch)
|| !letters && !numbers) {
if(ch >= 56320 && ch <= 57343) {
if(count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if(ch >= 55296 && ch <= 56191) {
if(count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if(ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
|
public static String random(int count, int start, int end, boolean letters, boolean numbers,
char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
} else {
if (end <= start) {
throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")");
}
}
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch)
|| numbers && Character.isDigit(ch)
|| !letters && !numbers) {
if(ch >= 56320 && ch <= 57343) {
if(count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if(ch >= 55296 && ch <= 56191) {
if(count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if(ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
|
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
|
RandomStringUtils throws confusing IAE when end <= start
|
RandomUtils invokes Random#nextInt where n = end - start.
If end <= start, then Random throws:
java.lang.IllegalArgumentException: n must be positive
This is confusing, and does not identify the source of the problem.
| 223 | 289 |
Lang-12
|
public static String random(int count, int start, int end, boolean letters, boolean numbers,
char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (start == 0 && end == 0) {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch)
|| numbers && Character.isDigit(ch)
|| !letters && !numbers) {
if(ch >= 56320 && ch <= 57343) {
if(count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if(ch >= 55296 && ch <= 56191) {
if(count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if(ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
|
public static String random(int count, int start, int end, boolean letters, boolean numbers,
char[] chars, Random random) {
if (count == 0) {
return "";
} else if (count < 0) {
throw new IllegalArgumentException("Requested random string length " + count + " is less than 0.");
}
if (chars != null && chars.length == 0) {
throw new IllegalArgumentException("The chars array must not be empty");
}
if (start == 0 && end == 0) {
if (chars != null) {
end = chars.length;
} else {
if (!letters && !numbers) {
end = Integer.MAX_VALUE;
} else {
end = 'z' + 1;
start = ' ';
}
}
}
char[] buffer = new char[count];
int gap = end - start;
while (count-- != 0) {
char ch;
if (chars == null) {
ch = (char) (random.nextInt(gap) + start);
} else {
ch = chars[random.nextInt(gap) + start];
}
if (letters && Character.isLetter(ch)
|| numbers && Character.isDigit(ch)
|| !letters && !numbers) {
if(ch >= 56320 && ch <= 57343) {
if(count == 0) {
count++;
} else {
// low surrogate, insert high surrogate after putting it in
buffer[count] = ch;
count--;
buffer[count] = (char) (55296 + random.nextInt(128));
}
} else if(ch >= 55296 && ch <= 56191) {
if(count == 0) {
count++;
} else {
// high surrogate, insert low surrogate before putting it in
buffer[count] = (char) (56320 + random.nextInt(128));
count--;
buffer[count] = ch;
}
} else if(ch >= 56192 && ch <= 56319) {
// private high surrogate, no effing clue, so skip it
count++;
} else {
buffer[count] = ch;
}
} else {
count++;
}
}
return new String(buffer);
}
|
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
|
RandomStringUtils.random(count, 0, 0, false, false, universe, random) always throws java.lang.ArrayIndexOutOfBoundsException
|
In commons-lang 2.6 line 250 :
ch = chars[random.nextInt(gap) + start];
This line of code takes a random int to fetch a char in the chars array regardless of its size.
(Besides start is useless here)
Fixed version would be :
//ch = chars[random.nextInt(gap)%chars.length];
When user pass 0 as end or when the array is not null but empty this line ends up with an exception
| 223 | 282 |
Lang-14
|
public static boolean equals(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
return cs1.equals(cs2);
}
|
public static boolean equals(CharSequence cs1, CharSequence cs2) {
if (cs1 == cs2) {
return true;
}
if (cs1 == null || cs2 == null) {
return false;
}
if (cs1 instanceof String && cs2 instanceof String) {
return cs1.equals(cs2);
}
return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length()));
}
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
StringUtils equals() relies on undefined behavior
|
Since the java.lang.CharSequence class was first introduced in 1.4, the JavaDoc block has contained the following note:
This interface does not refine the general contracts of the equals and hashCode methods. The result of comparing two objects that implement CharSequence is therefore, in general, undefined. Each object may be implemented by a different class, and there is no guarantee that each class will be capable of testing its instances for equality with those of the other.
When the signature of the StringUtils equals() method was changed from equals(String, String) to equals(CharSequence, CharSequence) in R920543, the implementation still relied on calling CharSequence#equals(Object) even though, in general, the result is undefined.
One example where equals(Object) returns false even though, as CharSequences, two objects represent equal sequences is when one object is an instance of javax.lang.model.element.Name and the other object is a String.
| 781 | 789 |
Lang-17
|
public final void translate(CharSequence input, Writer out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (input == null) {
return;
}
int pos = 0;
int len = Character.codePointCount(input, 0, input.length());
while (pos < len) {
int consumed = translate(input, pos, out);
if (consumed == 0) {
char[] c = Character.toChars(Character.codePointAt(input, pos));
out.write(c);
}
else {
// contract with translators is that they have to understand codepoints
// and they just took care of a surrogate pair
for (int pt = 0; pt < consumed; pt++) {
if (pos < len - 2) {
pos += Character.charCount(Character.codePointAt(input, pos));
} else {
pos++;
}
}
pos--;
}
pos++;
}
}
|
public final void translate(CharSequence input, Writer out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (input == null) {
return;
}
int pos = 0;
int len = input.length();
while (pos < len) {
int consumed = translate(input, pos, out);
if (consumed == 0) {
char[] c = Character.toChars(Character.codePointAt(input, pos));
out.write(c);
pos+= c.length;
continue;
}
// contract with translators is that they have to understand codepoints
// and they just took care of a surrogate pair
for (int pt = 0; pt < consumed; pt++) {
pos += Character.charCount(Character.codePointAt(input, pos));
}
}
}
|
src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java
|
StringEscapeUtils.escapeXml(input) outputs wrong results when an input contains characters in Supplementary Planes.
|
Hello.
I use StringEscapeUtils.escapeXml(input) to escape special characters for XML.
This method outputs wrong results when input contains characters in Supplementary Planes.
String str1 = "\uD842\uDFB7" + "A";
String str2 = StringEscapeUtils.escapeXml(str1);
// The value of str2 must be equal to the one of str1,
// because str1 does not contain characters to be escaped.
// However, str2 is diffrent from str1.
System.out.println(URLEncoder.encode(str1, "UTF-16BE")); //%D8%42%DF%B7A
System.out.println(URLEncoder.encode(str2, "UTF-16BE")); //%D8%42%DF%B7%FF%FD
The cause of this problem is that the loop to translate input character by character is wrong.
In CharSequenceTranslator.translate(CharSequence input, Writer out),
loop counter "i" moves from 0 to Character.codePointCount(input, 0, input.length()),
but it should move from 0 to input.length().
| 75 | 104 |
Lang-19
|
public int translate(CharSequence input, int index, Writer out) throws IOException {
int seqEnd = input.length();
// Uses -2 to ensure there is something after the &#
if(input.charAt(index) == '&' && index < seqEnd - 1 && input.charAt(index + 1) == '#') {
int start = index + 2;
boolean isHex = false;
char firstChar = input.charAt(start);
if(firstChar == 'x' || firstChar == 'X') {
start++;
isHex = true;
// Check there's more than just an x after the &#
}
int end = start;
// Note that this supports character codes without a ; on the end
while(input.charAt(end) != ';')
{
end++;
}
int entityValue;
try {
if(isHex) {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
} else {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
}
} catch(NumberFormatException nfe) {
System.err.println("FAIL: " + input.subSequence(start, end) + "[" + start +"]["+ end +"]");
return 0;
}
if(entityValue > 0xFFFF) {
char[] chrs = Character.toChars(entityValue);
out.write(chrs[0]);
out.write(chrs[1]);
} else {
out.write(entityValue);
}
return 2 + (end - start) + (isHex ? 1 : 0) + 1;
}
return 0;
}
|
public int translate(CharSequence input, int index, Writer out) throws IOException {
int seqEnd = input.length();
// Uses -2 to ensure there is something after the &#
if(input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') {
int start = index + 2;
boolean isHex = false;
char firstChar = input.charAt(start);
if(firstChar == 'x' || firstChar == 'X') {
start++;
isHex = true;
// Check there's more than just an x after the &#
if(start == seqEnd) {
return 0;
}
}
int end = start;
// Note that this supports character codes without a ; on the end
while(end < seqEnd && ( (input.charAt(end) >= '0' && input.charAt(end) <= '9') ||
(input.charAt(end) >= 'a' && input.charAt(end) <= 'f') ||
(input.charAt(end) >= 'A' && input.charAt(end) <= 'F') ) )
{
end++;
}
int entityValue;
try {
if(isHex) {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
} else {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
}
} catch(NumberFormatException nfe) {
System.err.println("FAIL: " + input.subSequence(start, end) + "[" + start +"]["+ end +"]");
return 0;
}
if(entityValue > 0xFFFF) {
char[] chrs = Character.toChars(entityValue);
out.write(chrs[0]);
out.write(chrs[1]);
} else {
out.write(entityValue);
}
boolean semiNext = (end != seqEnd) && (input.charAt(end) == ';');
return 2 + (end - start) + (isHex ? 1 : 0) + (semiNext ? 1 : 0);
}
return 0;
}
|
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java
|
StringIndexOutOfBoundsException when calling unescapeHtml4("")
|
When calling unescapeHtml4() on the String "" (or any String that contains these characters) an Exception is thrown:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 4
at java.lang.String.charAt(String.java:686)
at org.apache.commons.lang3.text.translate.NumericEntityUnescaper.translate(NumericEntityUnescaper.java:49)
at org.apache.commons.lang3.text.translate.AggregateTranslator.translate(AggregateTranslator.java:53)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:88)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:60)
at org.apache.commons.lang3.StringEscapeUtils.unescapeHtml4(StringEscapeUtils.java:351)
| 37 | 83 |
Lang-21
|
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.getClass() == cal2.getClass());
}
|
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) {
if (cal1 == null || cal2 == null) {
throw new IllegalArgumentException("The date must not be null");
}
return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) &&
cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) &&
cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) &&
cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) &&
cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) &&
cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) &&
cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) &&
cal1.getClass() == cal2.getClass());
}
|
src/main/java/org/apache/commons/lang3/time/DateUtils.java
|
DateUtils.isSameLocalTime does not work correct
|
Hi, I think I found a bug in the DateUtils class in the method isSameLocalTime.
Example:
Calendar a = Calendar.getInstance();
a.setTimeInMillis(1297364400000L);
Calendar b = Calendar.getInstance();
b.setTimeInMillis(1297321200000L);
Assert.assertFalse(DateUtils.isSameLocalTime(a, b));
This is because the method compares
cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR)
but I think it has to be
cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY)
| 258 | 270 |
Lang-22
|
private static int greatestCommonDivisor(int u, int v) {
// From Commons Math:
//if either operand is abs 1, return 1:
if (Math.abs(u) <= 1 || Math.abs(v) <= 1) {
return 1;
}
// keep u and v negative, as negative integers range down to
// -2^31, while positive numbers can only be as large as 2^31-1
// (i.e. we can't necessarily negate a negative number without
// overflow)
if (u>0) { u=-u; } // make u negative
if (v>0) { v=-v; } // make v negative
// B1. [Find power of 2]
int k=0;
while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even...
u/=2; v/=2; k++; // cast out twos.
}
if (k==31) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
// B2. Initialize: u and v have been divided by 2^k and at least
// one is odd.
int t = ((u&1)==1) ? v : -(u/2)/*B3*/;
// t negative: u was odd, v may be even (t replaces v)
// t positive: u was even, v is odd (t replaces u)
do {
/* assert u<0 && v<0; */
// B4/B3: cast out twos from t.
while ((t&1)==0) { // while t is even..
t/=2; // cast out twos
}
// B5 [reset max(u,v)]
if (t>0) {
u = -t;
} else {
v = t;
}
// B6/B3. at this point both u and v should be odd.
t = (v - u)/2;
// |u| larger: t positive (replace u)
// |v| larger: t negative (replace v)
} while (t!=0);
return -u*(1<<k); // gcd is u*2^k
}
|
private static int greatestCommonDivisor(int u, int v) {
// From Commons Math:
if ((u == 0) || (v == 0)) {
if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
return Math.abs(u) + Math.abs(v);
}
//if either operand is abs 1, return 1:
if (Math.abs(u) == 1 || Math.abs(v) == 1) {
return 1;
}
// keep u and v negative, as negative integers range down to
// -2^31, while positive numbers can only be as large as 2^31-1
// (i.e. we can't necessarily negate a negative number without
// overflow)
if (u>0) { u=-u; } // make u negative
if (v>0) { v=-v; } // make v negative
// B1. [Find power of 2]
int k=0;
while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even...
u/=2; v/=2; k++; // cast out twos.
}
if (k==31) {
throw new ArithmeticException("overflow: gcd is 2^31");
}
// B2. Initialize: u and v have been divided by 2^k and at least
// one is odd.
int t = ((u&1)==1) ? v : -(u/2)/*B3*/;
// t negative: u was odd, v may be even (t replaces v)
// t positive: u was even, v is odd (t replaces u)
do {
/* assert u<0 && v<0; */
// B4/B3: cast out twos from t.
while ((t&1)==0) { // while t is even..
t/=2; // cast out twos
}
// B5 [reset max(u,v)]
if (t>0) {
u = -t;
} else {
v = t;
}
// B6/B3. at this point both u and v should be odd.
t = (v - u)/2;
// |u| larger: t positive (replace u)
// |v| larger: t negative (replace v)
} while (t!=0);
return -u*(1<<k); // gcd is u*2^k
}
|
src/main/java/org/apache/commons/lang3/math/Fraction.java
|
org.apache.commons.lang3.math.Fraction does not reduce (Integer.MIN_VALUE, 2^k)
|
The greatestCommonDivisor method in class Fraction does not find the gcd of Integer.MIN_VALUE and 2^k, and this case can be triggered by taking Integer.MIN_VALUE as the numerator. Note that the case of taking Integer.MIN_VALUE as the denominator is handled explicitly in the getReducedFraction factory method.
FractionTest.java
// additional test cases
public void testReducedFactory_int_int() {
// ...
f = Fraction.getReducedFraction(Integer.MIN_VALUE, 2);
assertEquals(Integer.MIN_VALUE / 2, f.getNumerator());
assertEquals(1, f.getDenominator());
public void testReduce() {
// ...
f = Fraction.getFraction(Integer.MIN_VALUE, 2);
result = f.reduce();
assertEquals(Integer.MIN_VALUE / 2, result.getNumerator());
assertEquals(1, result.getDenominator());
| 581 | 624 |
Lang-26
|
public String format(Date date) {
Calendar c = new GregorianCalendar(mTimeZone);
c.setTime(date);
return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
}
|
public String format(Date date) {
Calendar c = new GregorianCalendar(mTimeZone, mLocale);
c.setTime(date);
return applyRules(c, new StringBuffer(mMaxLengthEstimate)).toString();
}
|
src/main/java/org/apache/commons/lang3/time/FastDateFormat.java
|
FastDateFormat.format() outputs incorrect week of year because locale isn't respected
|
FastDateFormat apparently doesn't respect the locale it was sent on creation when outputting week in year (e.g. "ww") in format(). It seems to use the settings of the system locale for firstDayOfWeek and minimalDaysInFirstWeek, which (depending on the year) may result in the incorrect week number being output.
Here is a simple test program to demonstrate the problem by comparing with SimpleDateFormat, which gets the week number right:
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.text.SimpleDateFormat;
import org.apache.commons.lang.time.FastDateFormat;
public class FastDateFormatWeekBugDemo {
public static void main(String[] args) {
Locale.setDefault(new Locale("en", "US"));
Locale locale = new Locale("sv", "SE");
Calendar cal = Calendar.getInstance(); // setting locale here doesn't change outcome
cal.set(2010, 0, 1, 12, 0, 0);
Date d = cal.getTime();
System.out.println("Target date: " + d);
FastDateFormat fdf = FastDateFormat.getInstance("EEEE', week 'ww", locale);
SimpleDateFormat sdf = new SimpleDateFormat("EEEE', week 'ww", locale);
System.out.println("FastDateFormat: " + fdf.format(d)); // will output "FastDateFormat: fredag, week 01"
System.out.println("SimpleDateFormat: " + sdf.format(d)); // will output "SimpleDateFormat: fredag, week 53"
}
}
If sv/SE is passed to Locale.setDefault() instead of en/US, both FastDateFormat and SimpleDateFormat output the correct week number.
| 819 | 823 |
Lang-28
|
public int translate(CharSequence input, int index, Writer out) throws IOException {
// TODO: Protect from ArrayIndexOutOfBounds
if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') {
int start = index + 2;
boolean isHex = false;
char firstChar = input.charAt(start);
if(firstChar == 'x' || firstChar == 'X') {
start++;
isHex = true;
}
int end = start;
while(input.charAt(end) != ';') {
end++;
}
int entityValue;
try {
if(isHex) {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
} else {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
}
} catch(NumberFormatException nfe) {
return 0;
}
out.write(entityValue);
return 2 + (end - start) + (isHex ? 1 : 0) + 1;
}
return 0;
}
|
public int translate(CharSequence input, int index, Writer out) throws IOException {
// TODO: Protect from ArrayIndexOutOfBounds
if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') {
int start = index + 2;
boolean isHex = false;
char firstChar = input.charAt(start);
if(firstChar == 'x' || firstChar == 'X') {
start++;
isHex = true;
}
int end = start;
while(input.charAt(end) != ';') {
end++;
}
int entityValue;
try {
if(isHex) {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16);
} else {
entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10);
}
} catch(NumberFormatException nfe) {
return 0;
}
if(entityValue > 0xFFFF) {
char[] chrs = Character.toChars(entityValue);
out.write(chrs[0]);
out.write(chrs[1]);
} else {
out.write(entityValue);
}
return 2 + (end - start) + (isHex ? 1 : 0) + 1;
}
return 0;
}
|
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java
|
StringEscapeUtils.escapeXML() can't process UTF-16 supplementary characters
|
Supplementary characters in UTF-16 are those whose code points are above 0xffff, that is, require more than 1 Java char to be encoded, as explained here: http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
Currently, StringEscapeUtils.escapeXML() isn't aware of this coding scheme and treats each char as one character, which is not always right.
A possible solution in class Entities would be:
public void escape(Writer writer, String str) throws IOException {
int len = str.length();
for (int i = 0; i < len; i++) {
int code = str.codePointAt;
String entityName = this.entityName(code);
if (entityName != null)
{
writer.write('&');
writer.write(entityName);
writer.write(';');
}
else if (code > 0x7F)
{
writer.write("&#");
writer.write(code);
writer.write(';');
}
else
{
writer.write((char) code);
}
if (code > 0xffff)
{
i++;
}
}
}
Besides fixing escapeXML(), this will also affect HTML escaping functions. I guess that's a good thing, but please remember I have only tested escapeXML().
| 35 | 67 |
Lang-29
|
static float toJavaVersionInt(String version) {
return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));
}
|
static int toJavaVersionInt(String version) {
return toVersionInt(toJavaVersionIntArray(version, JAVA_VERSION_TRIM_SIZE));
}
|
src/main/java/org/apache/commons/lang3/SystemUtils.java
|
SystemUtils.getJavaVersionAsFloat throws StringIndexOutOfBoundsException on Android runtime/Dalvik VM
|
Can be replicated in the Android emulator quite easily.
Stack trace:
at org.apache.commons.lang.builder.ToStringBuilder.<clinit>(ToStringBuilder.java:98)
E/AndroidRuntime( 1681): ... 17 more
E/AndroidRuntime( 1681): Caused by: java.lang.ExceptionInInitializerError
E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle$MultiLineToStringStyle.<init>(ToStringStyle.java:2276)
E/AndroidRuntime( 1681): at org.apache.commons.lang.builder.ToStringStyle.<clinit>(ToStringStyle.java:94)
E/AndroidRuntime( 1681): ... 18 more
E/AndroidRuntime( 1681): Caused by: java.lang.StringIndexOutOfBoundsException
E/AndroidRuntime( 1681): at java.lang.String.substring(String.java:1571)
E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.getJavaVersionAsFloat(SystemUtils.java:1153)
E/AndroidRuntime( 1681): at org.apache.commons.lang.SystemUtils.<clinit>(SystemUtils.java:818)
| 1,672 | 1,674 |
Lang-31
|
public static boolean containsAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
// ch is a supplementary character
// ch is in the Basic Multilingual Plane
return true;
}
}
}
return false;
}
|
public static boolean containsAny(CharSequence cs, char[] searchChars) {
if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) {
return false;
}
int csLength = cs.length();
int searchLength = searchChars.length;
int csLastIndex = csLength - 1;
int searchLastIndex = searchLength - 1;
for (int i = 0; i < csLength; i++) {
char ch = cs.charAt(i);
for (int j = 0; j < searchLength; j++) {
if (searchChars[j] == ch) {
if (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) {
// ch is a supplementary character
if (searchChars[j + 1] == cs.charAt(i + 1)) {
return true;
}
} else {
// ch is in the Basic Multilingual Plane
return true;
}
}
}
}
return false;
}
|
src/main/java/org/apache/commons/lang3/StringUtils.java
|
StringUtils methods do not handle Unicode 2.0+ supplementary characters correctly.
|
StringUtils.containsAny methods incorrectly matches Unicode 2.0+ supplementary characters.
For example, define a test fixture to be the Unicode character U+20000 where U+20000 is written in Java source as "\uD840\uDC00"
private static final String CharU20000 = "\uD840\uDC00";
private static final String CharU20001 = "\uD840\uDC01";
You can see Unicode supplementary characters correctly implemented in the JRE call:
assertEquals(-1, CharU20000.indexOf(CharU20001));
But this is broken:
assertEquals(false, StringUtils.containsAny(CharU20000, CharU20001));
assertEquals(false, StringUtils.containsAny(CharU20001, CharU20000));
This is fine:
assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20000));
assertEquals(true, StringUtils.contains(CharU20000 + CharU20001, CharU20001));
assertEquals(true, StringUtils.contains(CharU20000, CharU20000));
assertEquals(false, StringUtils.contains(CharU20000, CharU20001));
because the method calls the JRE to perform the match.
More than you want to know:
http://java.sun.com/developer/technicalArticles/Intl/Supplementary/
| 1,440 | 1,457 |
Lang-33
|
public static Class<?>[] toClass(Object[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return ArrayUtils.EMPTY_CLASS_ARRAY;
}
Class<?>[] classes = new Class[array.length];
for (int i = 0; i < array.length; i++) {
classes[i] = array[i].getClass();
}
return classes;
}
|
public static Class<?>[] toClass(Object[] array) {
if (array == null) {
return null;
} else if (array.length == 0) {
return ArrayUtils.EMPTY_CLASS_ARRAY;
}
Class<?>[] classes = new Class[array.length];
for (int i = 0; i < array.length; i++) {
classes[i] = array[i] == null ? null : array[i].getClass();
}
return classes;
}
|
src/main/java/org/apache/commons/lang3/ClassUtils.java
|
ClassUtils.toClass(Object[]) throws NPE on null array element
|
see summary
| 902 | 913 |
Lang-37
|
public static <T> T[] addAll(T[] array1, T... array2) {
if (array1 == null) {
return clone(array2);
} else if (array2 == null) {
return clone(array1);
}
final Class<?> type1 = array1.getClass().getComponentType();
T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
// Check if problem is incompatible types
return joinedArray;
}
|
public static <T> T[] addAll(T[] array1, T... array2) {
if (array1 == null) {
return clone(array2);
} else if (array2 == null) {
return clone(array1);
}
final Class<?> type1 = array1.getClass().getComponentType();
T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length);
System.arraycopy(array1, 0, joinedArray, 0, array1.length);
try {
System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
} catch (ArrayStoreException ase) {
// Check if problem is incompatible types
final Class<?> type2 = array2.getClass().getComponentType();
if (!type1.isAssignableFrom(type2)){
throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName());
}
throw ase; // No, so rethrow original
}
return joinedArray;
}
|
src/java/org/apache/commons/lang3/ArrayUtils.java
|
ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed types very well
|
ArrayUtils.addAll(T[] array1, T... array2) does not handle mixed array types very well.
The stack trace for
Number[] st = ArrayUtils.addAll(new Integer[]
{1}
, new Long[]
{2L}
);
starts:
java.lang.ArrayStoreException
at java.lang.System.arraycopy(Native Method)
at org.apache.commons.lang3.ArrayUtils.addAll(ArrayUtils.java:2962)
which is not all that obvious.
It would be a lot clearer if the method threw an IlegalArgumentException or similar.
| 2,953 | 2,965 |
Lang-38
|
public StringBuffer format(Calendar calendar, StringBuffer buf) {
if (mTimeZoneForced) {
calendar = (Calendar) calendar.clone();
calendar.setTimeZone(mTimeZone);
}
return applyRules(calendar, buf);
}
|
public StringBuffer format(Calendar calendar, StringBuffer buf) {
if (mTimeZoneForced) {
calendar.getTime(); /// LANG-538
calendar = (Calendar) calendar.clone();
calendar.setTimeZone(mTimeZone);
}
return applyRules(calendar, buf);
}
|
src/java/org/apache/commons/lang3/time/FastDateFormat.java
|
DateFormatUtils.format does not correctly change Calendar TimeZone in certain situations
|
If a Calendar object is constructed in certain ways a call to Calendar.setTimeZone does not correctly change the Calendars fields. Calling Calenar.getTime() seems to fix this problem. While this is probably a bug in the JDK, it would be nice if DateFormatUtils was smart enough to detect/resolve this problem.
For example, the following unit test fails:
public void testFormat_CalendarIsoMsZulu() {
final String dateTime = "2009-10-16T16:42:16.000Z";
// more commonly constructed with: cal = new GregorianCalendar(2009, 9, 16, 8, 42, 16)
// for the unit test to work in any time zone, constructing with GMT-8 rather than default locale time zone
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
cal.clear();
cal.set(2009, 9, 16, 8, 42, 16);
FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
assertEquals("dateTime", dateTime, format.format(cal));
}
However, this unit test passes:
public void testFormat_CalendarIsoMsZulu() {
final String dateTime = "2009-10-16T16:42:16.000Z";
GregorianCalendar cal = new GregorianCalendar(TimeZone.getTimeZone("GMT-8"));
cal.clear();
cal.set(2009, 9, 16, 8, 42, 16);
cal.getTime();
FastDateFormat format = FastDateFormat.getInstance("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", TimeZone.getTimeZone("GMT"));
assertEquals("dateTime", dateTime, format.format(cal));
}
| 870 | 876 |
Lang-40
|
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
return contains(str.toUpperCase(), searchStr.toUpperCase());
}
|
public static boolean containsIgnoreCase(String str, String searchStr) {
if (str == null || searchStr == null) {
return false;
}
int len = searchStr.length();
int max = str.length() - len;
for (int i = 0; i <= max; i++) {
if (str.regionMatches(true, i, searchStr, 0, len)) {
return true;
}
}
return false;
}
|
src/java/org/apache/commons/lang/StringUtils.java
|
Fix case-insensitive string handling
|
String.to*Case() is locale-sensitive, this is usually not intended for case-insensitive comparisions. Please see Common Bug #3 for details.
| 1,044 | 1,049 |
Lang-42
|
public void escape(Writer writer, String str) throws IOException {
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
String entityName = this.entityName(c);
if (entityName == null) {
if (c > 0x7F) {
writer.write("&#");
writer.write(Integer.toString(c, 10));
writer.write(';');
} else {
writer.write(c);
}
} else {
writer.write('&');
writer.write(entityName);
writer.write(';');
}
}
}
|
public void escape(Writer writer, String str) throws IOException {
int len = str.length();
for (int i = 0; i < len; i++) {
int c = Character.codePointAt(str, i);
String entityName = this.entityName(c);
if (entityName == null) {
if (c >= 0x010000 && i < len - 1) {
writer.write("&#");
writer.write(Integer.toString(c, 10));
writer.write(';');
i++;
} else if (c > 0x7F) {
writer.write("&#");
writer.write(Integer.toString(c, 10));
writer.write(';');
} else {
writer.write(c);
}
} else {
writer.write('&');
writer.write(entityName);
writer.write(';');
}
}
}
|
src/java/org/apache/commons/lang/Entities.java
|
StringEscapeUtils.escapeHtml incorrectly converts unicode characters above U+00FFFF into 2 characters
|
Characters that are represented as a 2 characters internaly by java are incorrectly converted by the function. The following test displays the problem quite nicely:
import org.apache.commons.lang.*;
public class J2 {
public static void main(String[] args) throws Exception {
// this is the utf8 representation of the character:
// COUNTING ROD UNIT DIGIT THREE
// in unicode
// codepoint: U+1D362
byte[] data = new byte[]
{ (byte)0xF0, (byte)0x9D, (byte)0x8D, (byte)0xA2 }
;
//output is: ��
// should be: 𝍢
System.out.println("'" + StringEscapeUtils.escapeHtml(new String(data, "UTF8")) + "'");
}
}
Should be very quick to fix, feel free to drop me an email if you want a patch.
| 825 | 844 |
Lang-43
|
private StringBuffer appendQuotedString(String pattern, ParsePosition pos,
StringBuffer appendTo, boolean escapingOn) {
int start = pos.getIndex();
char[] c = pattern.toCharArray();
if (escapingOn && c[start] == QUOTE) {
return appendTo == null ? null : appendTo.append(QUOTE);
}
int lastHold = start;
for (int i = pos.getIndex(); i < pattern.length(); i++) {
if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) {
appendTo.append(c, lastHold, pos.getIndex() - lastHold).append(
QUOTE);
pos.setIndex(i + ESCAPED_QUOTE.length());
lastHold = pos.getIndex();
continue;
}
switch (c[pos.getIndex()]) {
case QUOTE:
next(pos);
return appendTo == null ? null : appendTo.append(c, lastHold,
pos.getIndex() - lastHold);
default:
next(pos);
}
}
throw new IllegalArgumentException(
"Unterminated quoted string at position " + start);
}
|
private StringBuffer appendQuotedString(String pattern, ParsePosition pos,
StringBuffer appendTo, boolean escapingOn) {
int start = pos.getIndex();
char[] c = pattern.toCharArray();
if (escapingOn && c[start] == QUOTE) {
next(pos);
return appendTo == null ? null : appendTo.append(QUOTE);
}
int lastHold = start;
for (int i = pos.getIndex(); i < pattern.length(); i++) {
if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) {
appendTo.append(c, lastHold, pos.getIndex() - lastHold).append(
QUOTE);
pos.setIndex(i + ESCAPED_QUOTE.length());
lastHold = pos.getIndex();
continue;
}
switch (c[pos.getIndex()]) {
case QUOTE:
next(pos);
return appendTo == null ? null : appendTo.append(c, lastHold,
pos.getIndex() - lastHold);
default:
next(pos);
}
}
throw new IllegalArgumentException(
"Unterminated quoted string at position " + start);
}
|
src/java/org/apache/commons/lang/text/ExtendedMessageFormat.java
|
ExtendedMessageFormat: OutOfMemory with custom format registry and a pattern containing single quotes
|
When using ExtendedMessageFormat with a custom format registry and a pattern conatining single quotes, an OutOfMemoryError will occur.
Example that will cause error:
ExtendedMessageFormatTest.java
private static Map<String, Object> formatRegistry = new HashMap<String, Object>();
static {
formatRegistry.put(DummyFormatFactory.DUMMY_FORMAT, new DummyFormatFactory());
}
public static void main(String[] args) {
ExtendedMessageFormat mf = new ExtendedMessageFormat("it''s a {dummy} 'test'!", formatRegistry);
String formattedPattern = mf.format(new String[] {"great"});
System.out.println(formattedPattern);
}
}
The following change starting at line 421 on the 2.4 release seems to fix the problem:
ExtendedMessageFormat.java
CURRENT (Broken):
if (escapingOn && c[start] == QUOTE) {
return appendTo == null ? null : appendTo.append(QUOTE);
}
WORKING:
if (escapingOn && c[start] == QUOTE) {
next(pos);
return appendTo == null ? null : appendTo.append(QUOTE);
}
| 417 | 444 |
Lang-45
|
public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
// initial parameter checks
if (str == null) {
return null;
}
if (str.length() == 0) {
return StringUtils.EMPTY;
}
// if the lower value is greater than the length of the string,
// set to the length of the string
// if the upper value is -1 (i.e. no limit) or is greater
// than the length of the string, set to the length of the string
if (upper == -1 || upper > str.length()) {
upper = str.length();
}
// if upper is less than lower, raise it to lower
if (upper < lower) {
upper = lower;
}
StringBuffer result = new StringBuffer();
int index = StringUtils.indexOf(str, " ", lower);
if (index == -1) {
result.append(str.substring(0, upper));
// only if abbreviation has occured do we append the appendToEnd value
if (upper != str.length()) {
result.append(StringUtils.defaultString(appendToEnd));
}
} else if (index > upper) {
result.append(str.substring(0, upper));
result.append(StringUtils.defaultString(appendToEnd));
} else {
result.append(str.substring(0, index));
result.append(StringUtils.defaultString(appendToEnd));
}
return result.toString();
}
|
public static String abbreviate(String str, int lower, int upper, String appendToEnd) {
// initial parameter checks
if (str == null) {
return null;
}
if (str.length() == 0) {
return StringUtils.EMPTY;
}
// if the lower value is greater than the length of the string,
// set to the length of the string
if (lower > str.length()) {
lower = str.length();
}
// if the upper value is -1 (i.e. no limit) or is greater
// than the length of the string, set to the length of the string
if (upper == -1 || upper > str.length()) {
upper = str.length();
}
// if upper is less than lower, raise it to lower
if (upper < lower) {
upper = lower;
}
StringBuffer result = new StringBuffer();
int index = StringUtils.indexOf(str, " ", lower);
if (index == -1) {
result.append(str.substring(0, upper));
// only if abbreviation has occured do we append the appendToEnd value
if (upper != str.length()) {
result.append(StringUtils.defaultString(appendToEnd));
}
} else if (index > upper) {
result.append(str.substring(0, upper));
result.append(StringUtils.defaultString(appendToEnd));
} else {
result.append(str.substring(0, index));
result.append(StringUtils.defaultString(appendToEnd));
}
return result.toString();
}
|
src/java/org/apache/commons/lang/WordUtils.java
|
WordUtils.abbreviate bug when lower is greater than str.length
|
In WordUtils.abbreviate, upper is adjusted to the length of the string, then to lower.
But lower is never adjusted to the length of the string, so if lower is greater than str.lengt(), upper will be too...
Then, str.substring(0, upper) throw a StringIndexOutOfBoundsException
The fix is to adjust lower to the length of the string
| 605 | 642 |
Lang-49
|
public Fraction reduce() {
int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
if (gcd == 1) {
return this;
}
return Fraction.getFraction(numerator / gcd, denominator / gcd);
}
|
public Fraction reduce() {
if (numerator == 0) {
return equals(ZERO) ? this : ZERO;
}
int gcd = greatestCommonDivisor(Math.abs(numerator), denominator);
if (gcd == 1) {
return this;
}
return Fraction.getFraction(numerator / gcd, denominator / gcd);
}
|
src/java/org/apache/commons/lang/math/Fraction.java
|
infinite loop in Fraction.reduce when numerator == 0
|
Summary pretty much says it all.
| 465 | 471 |
Lang-5
|
public static Locale toLocale(final String str) {
if (str == null) {
return null;
}
final int len = str.length();
if (len < 2) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch0 = str.charAt(0);
final char ch1 = str.charAt(1);
if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str);
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch3 = str.charAt(3);
if (ch3 == '_') {
return new Locale(str.substring(0, 2), "", str.substring(4));
}
final char ch4 = str.charAt(4);
if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
}
if (len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
|
public static Locale toLocale(final String str) {
if (str == null) {
return null;
}
final int len = str.length();
if (len < 2) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch0 = str.charAt(0);
if (ch0 == '_') {
if (len < 3) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch1 = str.charAt(1);
final char ch2 = str.charAt(2);
if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 3) {
return new Locale("", str.substring(1, 3));
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(3) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale("", str.substring(1, 3), str.substring(4));
} else {
final char ch1 = str.charAt(1);
if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str);
}
if (len < 5) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
final char ch3 = str.charAt(3);
if (ch3 == '_') {
return new Locale(str.substring(0, 2), "", str.substring(4));
}
final char ch4 = str.charAt(4);
if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
}
if (len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
}
|
src/main/java/org/apache/commons/lang3/LocaleUtils.java
|
LocaleUtils.toLocale does not parse strings starting with an underscore
|
Hi,
Javadocs of Locale.toString() states that "If the language is missing, the string will begin with an underbar.". This is not handled in the LocaleUtils.toLocale method if it is meant to be the inversion method of Locale.toString().
The fix for the ticket 328 does not handle well the case "fr__P", which I found out during fixing the first bug.
I am attaching the patch for both problems.
| 88 | 128 |
Lang-51
|
public static boolean toBoolean(String str) {
// Previously used equalsIgnoreCase, which was fast for interned 'true'.
// Non interned 'true' matched 15 times slower.
//
// Optimisation provides same performance as before for interned 'true'.
// Similar performance for null, 'false', and other strings not length 2/3/4.
// 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.
if (str == "true") {
return true;
}
if (str == null) {
return false;
}
switch (str.length()) {
case 2: {
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
return
(ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N');
}
case 3: {
char ch = str.charAt(0);
if (ch == 'y') {
return
(str.charAt(1) == 'e' || str.charAt(1) == 'E') &&
(str.charAt(2) == 's' || str.charAt(2) == 'S');
}
if (ch == 'Y') {
return
(str.charAt(1) == 'E' || str.charAt(1) == 'e') &&
(str.charAt(2) == 'S' || str.charAt(2) == 's');
}
}
case 4: {
char ch = str.charAt(0);
if (ch == 't') {
return
(str.charAt(1) == 'r' || str.charAt(1) == 'R') &&
(str.charAt(2) == 'u' || str.charAt(2) == 'U') &&
(str.charAt(3) == 'e' || str.charAt(3) == 'E');
}
if (ch == 'T') {
return
(str.charAt(1) == 'R' || str.charAt(1) == 'r') &&
(str.charAt(2) == 'U' || str.charAt(2) == 'u') &&
(str.charAt(3) == 'E' || str.charAt(3) == 'e');
}
}
}
return false;
}
|
public static boolean toBoolean(String str) {
// Previously used equalsIgnoreCase, which was fast for interned 'true'.
// Non interned 'true' matched 15 times slower.
//
// Optimisation provides same performance as before for interned 'true'.
// Similar performance for null, 'false', and other strings not length 2/3/4.
// 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower.
if (str == "true") {
return true;
}
if (str == null) {
return false;
}
switch (str.length()) {
case 2: {
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
return
(ch0 == 'o' || ch0 == 'O') &&
(ch1 == 'n' || ch1 == 'N');
}
case 3: {
char ch = str.charAt(0);
if (ch == 'y') {
return
(str.charAt(1) == 'e' || str.charAt(1) == 'E') &&
(str.charAt(2) == 's' || str.charAt(2) == 'S');
}
if (ch == 'Y') {
return
(str.charAt(1) == 'E' || str.charAt(1) == 'e') &&
(str.charAt(2) == 'S' || str.charAt(2) == 's');
}
return false;
}
case 4: {
char ch = str.charAt(0);
if (ch == 't') {
return
(str.charAt(1) == 'r' || str.charAt(1) == 'R') &&
(str.charAt(2) == 'u' || str.charAt(2) == 'U') &&
(str.charAt(3) == 'e' || str.charAt(3) == 'E');
}
if (ch == 'T') {
return
(str.charAt(1) == 'R' || str.charAt(1) == 'r') &&
(str.charAt(2) == 'U' || str.charAt(2) == 'u') &&
(str.charAt(3) == 'E' || str.charAt(3) == 'e');
}
}
}
return false;
}
|
src/java/org/apache/commons/lang/BooleanUtils.java
|
BooleanUtils.toBoolean() - invalid drop-thru in case statement causes StringIndexOutOfBoundsException
|
The method BooleanUtils.toBoolean() has a case statement; case 3 drops through to case 4; this can cause StringIndexOutOfBoundsException, for example with the test:
assertEquals(false, BooleanUtils.toBoolean("tru"));
The end of case 3 should return false.
Patch to follow for source and unit test.
| 649 | 700 |
Lang-52
|
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (str == null) {
return;
}
int sz;
sz = str.length();
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
// handle unicode
if (ch > 0xfff) {
out.write("\\u" + hex(ch));
} else if (ch > 0xff) {
out.write("\\u0" + hex(ch));
} else if (ch > 0x7f) {
out.write("\\u00" + hex(ch));
} else if (ch < 32) {
switch (ch) {
case '\b':
out.write('\\');
out.write('b');
break;
case '\n':
out.write('\\');
out.write('n');
break;
case '\t':
out.write('\\');
out.write('t');
break;
case '\f':
out.write('\\');
out.write('f');
break;
case '\r':
out.write('\\');
out.write('r');
break;
default :
if (ch > 0xf) {
out.write("\\u00" + hex(ch));
} else {
out.write("\\u000" + hex(ch));
}
break;
}
} else {
switch (ch) {
case '\'':
if (escapeSingleQuote) {
out.write('\\');
}
out.write('\'');
break;
case '"':
out.write('\\');
out.write('"');
break;
case '\\':
out.write('\\');
out.write('\\');
break;
default :
out.write(ch);
break;
}
}
}
}
|
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (str == null) {
return;
}
int sz;
sz = str.length();
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
// handle unicode
if (ch > 0xfff) {
out.write("\\u" + hex(ch));
} else if (ch > 0xff) {
out.write("\\u0" + hex(ch));
} else if (ch > 0x7f) {
out.write("\\u00" + hex(ch));
} else if (ch < 32) {
switch (ch) {
case '\b':
out.write('\\');
out.write('b');
break;
case '\n':
out.write('\\');
out.write('n');
break;
case '\t':
out.write('\\');
out.write('t');
break;
case '\f':
out.write('\\');
out.write('f');
break;
case '\r':
out.write('\\');
out.write('r');
break;
default :
if (ch > 0xf) {
out.write("\\u00" + hex(ch));
} else {
out.write("\\u000" + hex(ch));
}
break;
}
} else {
switch (ch) {
case '\'':
if (escapeSingleQuote) {
out.write('\\');
}
out.write('\'');
break;
case '"':
out.write('\\');
out.write('"');
break;
case '\\':
out.write('\\');
out.write('\\');
break;
case '/':
out.write('\\');
out.write('/');
break;
default :
out.write(ch);
break;
}
}
}
}
|
src/java/org/apache/commons/lang/StringEscapeUtils.java
|
StringEscapeUtils.escapeJavaScript() method did not escape '/' into '\/', it will make IE render page uncorrectly
|
If Javascripts including'/', IE will parse the scripts uncorrectly, actually '/' should be escaped to '\/'.
For example, document.getElementById("test").value = '<script>alert(\'aaa\');</script>';this expression will make IE render page uncorrect, it should be document.getElementById("test").value = '<script>alert(\'aaa\');<\/script>';
Btw, Spring's JavascriptEscape behavor is correct.
Try to run below codes, you will find the difference:
String s = "<script>alert('aaa');</script>";
String str = org.springframework.web.util.JavaScriptUtils.javaScriptEscape(s);
System.out.println("Spring JS Escape : "+str);
str = org.apache.commons.lang.StringEscapeUtils.escapeJavaScript(s);
System.out.println("Apache Common Lang JS Escape : "+ str);
| 171 | 242 |
Lang-54
|
public static Locale toLocale(String str) {
if (str == null) {
return null;
}
int len = str.length();
if (len != 2 && len != 5 && len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str, "");
} else {
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch3 = str.charAt(3);
char ch4 = str.charAt(4);
if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
} else {
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
}
}
|
public static Locale toLocale(String str) {
if (str == null) {
return null;
}
int len = str.length();
if (len != 2 && len != 5 && len < 7) {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch0 = str.charAt(0);
char ch1 = str.charAt(1);
if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 2) {
return new Locale(str, "");
} else {
if (str.charAt(2) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
char ch3 = str.charAt(3);
if (ch3 == '_') {
return new Locale(str.substring(0, 2), "", str.substring(4));
}
char ch4 = str.charAt(4);
if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
if (len == 5) {
return new Locale(str.substring(0, 2), str.substring(3, 5));
} else {
if (str.charAt(5) != '_') {
throw new IllegalArgumentException("Invalid locale format: " + str);
}
return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6));
}
}
}
|
src/java/org/apache/commons/lang/LocaleUtils.java
|
LocaleUtils.toLocale() rejects strings with only language+variant
|
LocaleUtils.toLocale() throws an exception on strings containing a language and a variant but no country code. For example : fr__POSIX
This string can be produced with the JDK by instanciating a Locale with an empty string for the country : new Locale("fr", "", "POSIX").toString(). According to the javadoc for the Locale class a variant is allowed with just a language code or just a country code.
Commons Configuration handles this case in its PropertyConverter.toLocale() method. I'd like to replace our implementation by the one provided by LocaleUtils, but our tests fail due to this case.
| 94 | 127 |
Lang-55
|
public void stop() {
if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
throw new IllegalStateException("Stopwatch is not running. ");
}
stopTime = System.currentTimeMillis();
this.runningState = STATE_STOPPED;
}
|
public void stop() {
if(this.runningState != STATE_RUNNING && this.runningState != STATE_SUSPENDED) {
throw new IllegalStateException("Stopwatch is not running. ");
}
if(this.runningState == STATE_RUNNING) {
stopTime = System.currentTimeMillis();
}
this.runningState = STATE_STOPPED;
}
|
src/java/org/apache/commons/lang/time/StopWatch.java
|
StopWatch: suspend() acts as split(), if followed by stop()
|
In my opinion, it is a bug that suspend() acts as split(), if followed by stop(); see below:
StopWatch sw = new StopWatch();
sw.start();
Thread.sleep(1000);
sw.suspend();
// Time 1 (ok)
System.out.println(sw.getTime());
Thread.sleep(2000);
// Time 1 (again, ok)
System.out.println(sw.getTime());
sw.resume();
Thread.sleep(3000);
sw.suspend();
// Time 2 (ok)
System.out.println(sw.getTime());
Thread.sleep(4000);
// Time 2 (again, ok)
System.out.println(sw.getTime());
Thread.sleep(5000);
sw.stop();
// Time 2 (should be, but is Time 3 => NOT ok)
System.out.println(sw.getTime());
suspend/resume is like a pause, where time counter doesn't continue. So a following stop()-call shouldn't increase the time counter, should it?
| 114 | 120 |
Lang-57
|
public static boolean isAvailableLocale(Locale locale) {
return cAvailableLocaleSet.contains(locale);
}
|
public static boolean isAvailableLocale(Locale locale) {
return availableLocaleList().contains(locale);
}
|
src/java/org/apache/commons/lang/LocaleUtils.java
|
NullPointerException in isAvailableLocale(Locale)
|
FindBugs pointed out:
UwF: Field not initialized in constructor: org.apache.commons.lang.LocaleUtils.cAvailableLocaleSet
cAvailableSet is used directly once in the source - and if availableLocaleSet() hasn't been called it will cause a NullPointerException.
| 222 | 224 |
Lang-59
|
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
int strLen = str.length();
if (strLen >= width) {
str.getChars(0, strLen, buffer, size);
} else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++) {
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
|
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
int strLen = str.length();
if (strLen >= width) {
str.getChars(0, width, buffer, size);
} else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++) {
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
|
src/java/org/apache/commons/lang/text/StrBuilder.java
|
Bug in method appendFixedWidthPadRight of class StrBuilder causes an ArrayIndexOutOfBoundsException
|
There's a bug in method appendFixedWidthPadRight of class StrBuilder:
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) {
if (width > 0) {
ensureCapacity(size + width);
String str = (obj == null ? getNullText() : obj.toString());
int strLen = str.length();
if (strLen >= width)
{
==> str.getChars(0, strLen, buffer, size); <==== BUG: it should be str.getChars(0, width, buffer, size);
}
else {
int padLen = width - strLen;
str.getChars(0, strLen, buffer, size);
for (int i = 0; i < padLen; i++)
{
buffer[size + strLen + i] = padChar;
}
}
size += width;
}
return this;
}
This is causing an ArrayIndexOutOfBoundsException, so this method is unusable when strLen > width.
It's counterpart method appendFixedWidthPadLeft seems to be ok.
| 878 | 895 |
Lang-6
|
public final void translate(CharSequence input, Writer out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (input == null) {
return;
}
int pos = 0;
int len = input.length();
while (pos < len) {
int consumed = translate(input, pos, out);
if (consumed == 0) {
char[] c = Character.toChars(Character.codePointAt(input, pos));
out.write(c);
pos+= c.length;
continue;
}
// contract with translators is that they have to understand codepoints
// and they just took care of a surrogate pair
for (int pt = 0; pt < consumed; pt++) {
pos += Character.charCount(Character.codePointAt(input, pos));
}
}
}
|
public final void translate(CharSequence input, Writer out) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (input == null) {
return;
}
int pos = 0;
int len = input.length();
while (pos < len) {
int consumed = translate(input, pos, out);
if (consumed == 0) {
char[] c = Character.toChars(Character.codePointAt(input, pos));
out.write(c);
pos+= c.length;
continue;
}
// contract with translators is that they have to understand codepoints
// and they just took care of a surrogate pair
for (int pt = 0; pt < consumed; pt++) {
pos += Character.charCount(Character.codePointAt(input, pt));
}
}
}
|
src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java
|
StringIndexOutOfBoundsException in CharSequenceTranslator
|
I found that there is bad surrogate pair handling in the CharSequenceTranslator
This is a simple test case for this problem.
\uD83D\uDE30 is a surrogate pair.
@Test
public void testEscapeSurrogatePairs() throws Exception {
assertEquals("\uD83D\uDE30", StringEscapeUtils.escapeCsv("\uD83D\uDE30"));
}
You'll get the exception as shown below.
java.lang.StringIndexOutOfBoundsException: String index out of range: 2
at java.lang.String.charAt(String.java:658)
at java.lang.Character.codePointAt(Character.java:4668)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:95)
at org.apache.commons.lang3.text.translate.CharSequenceTranslator.translate(CharSequenceTranslator.java:59)
at org.apache.commons.lang3.StringEscapeUtils.escapeCsv(StringEscapeUtils.java:556)
Patch attached, the method affected:
public final void translate(CharSequence input, Writer out) throws IOException
| 75 | 98 |
Lang-9
|
private void init() {
thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);
nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();
StringBuilder regex= new StringBuilder();
List<Strategy> collector = new ArrayList<Strategy>();
Matcher patternMatcher= formatPattern.matcher(pattern);
if(!patternMatcher.lookingAt()) {
throw new IllegalArgumentException("Invalid pattern");
}
currentFormatField= patternMatcher.group();
Strategy currentStrategy= getStrategy(currentFormatField);
for(;;) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if(!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
String nextFormatField= patternMatcher.group();
nextStrategy = getStrategy(nextFormatField);
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= nextFormatField;
currentStrategy= nextStrategy;
}
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= null;
strategies= collector.toArray(new Strategy[collector.size()]);
parsePattern= Pattern.compile(regex.toString());
}
|
private void init() {
thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR);
nameValues= new ConcurrentHashMap<Integer, KeyValue[]>();
StringBuilder regex= new StringBuilder();
List<Strategy> collector = new ArrayList<Strategy>();
Matcher patternMatcher= formatPattern.matcher(pattern);
if(!patternMatcher.lookingAt()) {
throw new IllegalArgumentException("Invalid pattern");
}
currentFormatField= patternMatcher.group();
Strategy currentStrategy= getStrategy(currentFormatField);
for(;;) {
patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd());
if(!patternMatcher.lookingAt()) {
nextStrategy = null;
break;
}
String nextFormatField= patternMatcher.group();
nextStrategy = getStrategy(nextFormatField);
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= nextFormatField;
currentStrategy= nextStrategy;
}
if (patternMatcher.regionStart() != patternMatcher.regionEnd()) {
throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart());
}
if(currentStrategy.addRegex(this, regex)) {
collector.add(currentStrategy);
}
currentFormatField= null;
strategies= collector.toArray(new Strategy[collector.size()]);
parsePattern= Pattern.compile(regex.toString());
}
|
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
|
FastDateParser does not handle unterminated quotes correctly
|
FDP does not handled unterminated quotes the same way as SimpleDateFormat
For example:
Format: 'd'd'
Date: d3
This should fail to parse the format and date but it actually works.
The format is parsed as:
Pattern: d(\p
{IsNd}
++)
| 115 | 150 |
Math-10
|
public void atan2(final double[] y, final int yOffset,
final double[] x, final int xOffset,
final double[] result, final int resultOffset) {
// compute r = sqrt(x^2+y^2)
double[] tmp1 = new double[getSize()];
multiply(x, xOffset, x, xOffset, tmp1, 0); // x^2
double[] tmp2 = new double[getSize()];
multiply(y, yOffset, y, yOffset, tmp2, 0); // y^2
add(tmp1, 0, tmp2, 0, tmp2, 0); // x^2 + y^2
rootN(tmp2, 0, 2, tmp1, 0); // r = sqrt(x^2 + y^2)
if (x[xOffset] >= 0) {
// compute atan2(y, x) = 2 atan(y / (r + x))
add(tmp1, 0, x, xOffset, tmp2, 0); // r + x
divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r + x)
atan(tmp1, 0, tmp2, 0); // atan(y / (r + x))
for (int i = 0; i < tmp2.length; ++i) {
result[resultOffset + i] = 2 * tmp2[i]; // 2 * atan(y / (r + x))
}
} else {
// compute atan2(y, x) = +/- pi - 2 atan(y / (r - x))
subtract(tmp1, 0, x, xOffset, tmp2, 0); // r - x
divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r - x)
atan(tmp1, 0, tmp2, 0); // atan(y / (r - x))
result[resultOffset] =
((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x))
for (int i = 1; i < tmp2.length; ++i) {
result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x))
}
}
// fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly
}
|
public void atan2(final double[] y, final int yOffset,
final double[] x, final int xOffset,
final double[] result, final int resultOffset) {
// compute r = sqrt(x^2+y^2)
double[] tmp1 = new double[getSize()];
multiply(x, xOffset, x, xOffset, tmp1, 0); // x^2
double[] tmp2 = new double[getSize()];
multiply(y, yOffset, y, yOffset, tmp2, 0); // y^2
add(tmp1, 0, tmp2, 0, tmp2, 0); // x^2 + y^2
rootN(tmp2, 0, 2, tmp1, 0); // r = sqrt(x^2 + y^2)
if (x[xOffset] >= 0) {
// compute atan2(y, x) = 2 atan(y / (r + x))
add(tmp1, 0, x, xOffset, tmp2, 0); // r + x
divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r + x)
atan(tmp1, 0, tmp2, 0); // atan(y / (r + x))
for (int i = 0; i < tmp2.length; ++i) {
result[resultOffset + i] = 2 * tmp2[i]; // 2 * atan(y / (r + x))
}
} else {
// compute atan2(y, x) = +/- pi - 2 atan(y / (r - x))
subtract(tmp1, 0, x, xOffset, tmp2, 0); // r - x
divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r - x)
atan(tmp1, 0, tmp2, 0); // atan(y / (r - x))
result[resultOffset] =
((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x))
for (int i = 1; i < tmp2.length; ++i) {
result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x))
}
}
// fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly
result[resultOffset] = FastMath.atan2(y[yOffset], x[xOffset]);
}
|
src/main/java/org/apache/commons/math3/analysis/differentiation/DSCompiler.java
|
DerivativeStructure.atan2(y,x) does not handle special cases properly
|
The four special cases +/-0 for both x and y should give the same values as Math.atan2 and FastMath.atan2. However, they give NaN for the value in all cases.
| 1,382 | 1,420 |
Math-101
|
public Complex parse(String source, ParsePosition pos) {
int initialIndex = pos.getIndex();
// parse whitespace
parseAndIgnoreWhitespace(source, pos);
// parse real
Number re = parseNumber(source, getRealFormat(), pos);
if (re == null) {
// invalid real number
// set index back to initial, error index should already be set
// character examined.
pos.setIndex(initialIndex);
return null;
}
// parse sign
int startIndex = pos.getIndex();
char c = parseNextCharacter(source, pos);
int sign = 0;
switch (c) {
case 0 :
// no sign
// return real only complex number
return new Complex(re.doubleValue(), 0.0);
case '-' :
sign = -1;
break;
case '+' :
sign = 1;
break;
default :
// invalid sign
// set index back to initial, error index should be the last
// character examined.
pos.setIndex(initialIndex);
pos.setErrorIndex(startIndex);
return null;
}
// parse whitespace
parseAndIgnoreWhitespace(source, pos);
// parse imaginary
Number im = parseNumber(source, getRealFormat(), pos);
if (im == null) {
// invalid imaginary number
// set index back to initial, error index should already be set
// character examined.
pos.setIndex(initialIndex);
return null;
}
// parse imaginary character
int n = getImaginaryCharacter().length();
startIndex = pos.getIndex();
int endIndex = startIndex + n;
if (
source.substring(startIndex, endIndex).compareTo(
getImaginaryCharacter()) != 0) {
// set index back to initial, error index should be the start index
// character examined.
pos.setIndex(initialIndex);
pos.setErrorIndex(startIndex);
return null;
}
pos.setIndex(endIndex);
return new Complex(re.doubleValue(), im.doubleValue() * sign);
}
|
public Complex parse(String source, ParsePosition pos) {
int initialIndex = pos.getIndex();
// parse whitespace
parseAndIgnoreWhitespace(source, pos);
// parse real
Number re = parseNumber(source, getRealFormat(), pos);
if (re == null) {
// invalid real number
// set index back to initial, error index should already be set
// character examined.
pos.setIndex(initialIndex);
return null;
}
// parse sign
int startIndex = pos.getIndex();
char c = parseNextCharacter(source, pos);
int sign = 0;
switch (c) {
case 0 :
// no sign
// return real only complex number
return new Complex(re.doubleValue(), 0.0);
case '-' :
sign = -1;
break;
case '+' :
sign = 1;
break;
default :
// invalid sign
// set index back to initial, error index should be the last
// character examined.
pos.setIndex(initialIndex);
pos.setErrorIndex(startIndex);
return null;
}
// parse whitespace
parseAndIgnoreWhitespace(source, pos);
// parse imaginary
Number im = parseNumber(source, getRealFormat(), pos);
if (im == null) {
// invalid imaginary number
// set index back to initial, error index should already be set
// character examined.
pos.setIndex(initialIndex);
return null;
}
// parse imaginary character
int n = getImaginaryCharacter().length();
startIndex = pos.getIndex();
int endIndex = startIndex + n;
if ((startIndex >= source.length()) ||
(endIndex > source.length()) ||
source.substring(startIndex, endIndex).compareTo(
getImaginaryCharacter()) != 0) {
// set index back to initial, error index should be the start index
// character examined.
pos.setIndex(initialIndex);
pos.setErrorIndex(startIndex);
return null;
}
pos.setIndex(endIndex);
return new Complex(re.doubleValue(), im.doubleValue() * sign);
}
|
src/java/org/apache/commons/math/complex/ComplexFormat.java
|
java.lang.StringIndexOutOfBoundsException in ComplexFormat.parse(String source, ParsePosition pos)
|
The parse(String source, ParsePosition pos) method in the ComplexFormat class does not check whether the imaginary character is set or not which produces StringIndexOutOfBoundsException in the substring method :
(line 375 of ComplexFormat)
...
// parse imaginary character
int n = getImaginaryCharacter().length();
startIndex = pos.getIndex();
int endIndex = startIndex + n;
if (source.substring(startIndex, endIndex).compareTo(
getImaginaryCharacter()) != 0) {
...
I encoutered this exception typing in a JTextFied with ComplexFormat set to look up an AbstractFormatter.
If only the user types the imaginary part of the complex number first, he gets this exception.
Solution: Before setting to n length of the imaginary character, check if the source contains it. My proposal:
...
int n = 0;
if (source.contains(getImaginaryCharacter()))
n = getImaginaryCharacter().length();
...
F.S.
| 320 | 389 |
Math-102
|
public double chiSquare(double[] expected, long[] observed)
throws IllegalArgumentException {
if ((expected.length < 2) || (expected.length != observed.length)) {
throw new IllegalArgumentException(
"observed, expected array lengths incorrect");
}
if (!isPositive(expected) || !isNonNegative(observed)) {
throw new IllegalArgumentException(
"observed counts must be non-negative and expected counts must be postive");
}
double sumSq = 0.0d;
double dev = 0.0d;
for (int i = 0; i < observed.length; i++) {
dev = ((double) observed[i] - expected[i]);
sumSq += dev * dev / expected[i];
}
return sumSq;
}
|
public double chiSquare(double[] expected, long[] observed)
throws IllegalArgumentException {
if ((expected.length < 2) || (expected.length != observed.length)) {
throw new IllegalArgumentException(
"observed, expected array lengths incorrect");
}
if (!isPositive(expected) || !isNonNegative(observed)) {
throw new IllegalArgumentException(
"observed counts must be non-negative and expected counts must be postive");
}
double sumExpected = 0d;
double sumObserved = 0d;
for (int i = 0; i < observed.length; i++) {
sumExpected += expected[i];
sumObserved += observed[i];
}
double ratio = 1.0d;
boolean rescale = false;
if (Math.abs(sumExpected - sumObserved) > 10E-6) {
ratio = sumObserved / sumExpected;
rescale = true;
}
double sumSq = 0.0d;
double dev = 0.0d;
for (int i = 0; i < observed.length; i++) {
if (rescale) {
dev = ((double) observed[i] - ratio * expected[i]);
sumSq += dev * dev / (ratio * expected[i]);
} else {
dev = ((double) observed[i] - expected[i]);
sumSq += dev * dev / expected[i];
}
}
return sumSq;
}
|
src/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java
|
chiSquare(double[] expected, long[] observed) is returning incorrect test statistic
|
ChiSquareTestImpl is returning incorrect chi-squared value. An implicit assumption of public double chiSquare(double[] expected, long[] observed) is that the sum of expected and observed are equal. That is, in the code:
for (int i = 0; i < observed.length; i++)
{
dev = ((double) observed[i] - expected[i]);
sumSq += dev * dev / expected[i];
}
this calculation is only correct if sum(observed)==sum(expected). When they are not equal then one must rescale the expected value by sum(observed) / sum(expected) so that they are.
Ironically, it is an example in the unit test ChiSquareTestTest that highlights the error:
long[] observed1 =
{ 500, 623, 72, 70, 31 }
;
double[] expected1 =
{ 485, 541, 82, 61, 37 }
;
assertEquals( "chi-square test statistic", 16.4131070362, testStatistic.chiSquare(expected1, observed1), 1E-10);
assertEquals("chi-square p-value", 0.002512096, testStatistic.chiSquareTest(expected1, observed1), 1E-9);
16.413 is not correct because the expected values do not make sense, they should be: 521.19403 581.37313 88.11940 65.55224 39.76119 so that the sum of expected equals 1296 which is the sum of observed.
Here is some R code (r-project.org) which proves it:
> o1
[1] 500 623 72 70 31
> e1
[1] 485 541 82 61 37
> chisq.test(o1,p=e1,rescale.p=TRUE)
Chi-squared test for given probabilities
data: o1
X-squared = 9.0233, df = 4, p-value = 0.06052
> chisq.test(o1,p=e1,rescale.p=TRUE)$observed
[1] 500 623 72 70 31
> chisq.test(o1,p=e1,rescale.p=TRUE)$expected
[1] 521.19403 581.37313 88.11940 65.55224 39.76119
| 64 | 81 |
Math-103
|
public double cumulativeProbability(double x) throws MathException {
return 0.5 * (1.0 + Erf.erf((x - mean) /
(standardDeviation * Math.sqrt(2.0))));
}
|
public double cumulativeProbability(double x) throws MathException {
try {
return 0.5 * (1.0 + Erf.erf((x - mean) /
(standardDeviation * Math.sqrt(2.0))));
} catch (MaxIterationsExceededException ex) {
if (x < (mean - 20 * standardDeviation)) { // JDK 1.5 blows at 38
return 0.0d;
} else if (x > (mean + 20 * standardDeviation)) {
return 1.0d;
} else {
throw ex;
}
}
}
|
src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java
|
ConvergenceException in normal CDF
|
NormalDistributionImpl::cumulativeProbability(double x) throws ConvergenceException
if x deviates too much from the mean. For example, when x=+/-100, mean=0, sd=1.
Of course the value of the CDF is hard to evaluate in these cases,
but effectively it should be either zero or one.
| 108 | 111 |
Math-11
|
public double density(final double[] vals) throws DimensionMismatchException {
final int dim = getDimension();
if (vals.length != dim) {
throw new DimensionMismatchException(vals.length, dim);
}
return FastMath.pow(2 * FastMath.PI, -dim / 2) *
FastMath.pow(covarianceMatrixDeterminant, -0.5) *
getExponentTerm(vals);
}
|
public double density(final double[] vals) throws DimensionMismatchException {
final int dim = getDimension();
if (vals.length != dim) {
throw new DimensionMismatchException(vals.length, dim);
}
return FastMath.pow(2 * FastMath.PI, -0.5 * dim) *
FastMath.pow(covarianceMatrixDeterminant, -0.5) *
getExponentTerm(vals);
}
|
src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java
|
MultivariateNormalDistribution.density(double[]) returns wrong value when the dimension is odd
|
To reproduce:
Assert.assertEquals(0.398942280401433, new MultivariateNormalDistribution(new double[]{0}, new double[][]{{1}}).density(new double[]{0}), 1e-15);
| 177 | 186 |
Math-13
|
private RealMatrix squareRoot(RealMatrix m) {
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
}
|
private RealMatrix squareRoot(RealMatrix m) {
if (m instanceof DiagonalMatrix) {
final int dim = m.getRowDimension();
final RealMatrix sqrtM = new DiagonalMatrix(dim);
for (int i = 0; i < dim; i++) {
sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i)));
}
return sqrtM;
} else {
final EigenDecomposition dec = new EigenDecomposition(m);
return dec.getSquareRoot();
}
}
|
src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java
|
new multivariate vector optimizers cannot be used with large number of weights
|
When using the Weigth class to pass a large number of weights to multivariate vector optimizers, an nxn full matrix is created (and copied) when a n elements vector is used. This exhausts memory when n is large.
This happens for example when using curve fitters (even simple curve fitters like polynomial ones for low degree) with large number of points. I encountered this with curve fitting on 41200 points, which created a matrix with 1.7 billion elements.
| 561 | 564 |
Math-17
|
public Dfp multiply(final int x) {
return multiplyFast(x);
}
|
public Dfp multiply(final int x) {
if (x >= 0 && x < RADIX) {
return multiplyFast(x);
} else {
return multiply(newInstance(x));
}
}
|
src/main/java/org/apache/commons/math3/dfp/Dfp.java
|
Dfp Dfp.multiply(int x) does not comply with the general contract FieldElement.multiply(int n)
|
In class org.apache.commons.math3.Dfp, the method multiply(int n) is limited to 0 <= n <= 9999. This is not consistent with the general contract of FieldElement.multiply(int n), where there should be no limitation on the values of n.
| 1,602 | 1,604 |
Math-19
|
private void checkParameters() {
final double[] init = getStartPoint();
final double[] lB = getLowerBound();
final double[] uB = getUpperBound();
// Checks whether there is at least one finite bound value.
boolean hasFiniteBounds = false;
for (int i = 0; i < lB.length; i++) {
if (!Double.isInfinite(lB[i]) ||
!Double.isInfinite(uB[i])) {
hasFiniteBounds = true;
break;
}
}
// Checks whether there is at least one infinite bound value.
boolean hasInfiniteBounds = false;
if (hasFiniteBounds) {
for (int i = 0; i < lB.length; i++) {
if (Double.isInfinite(lB[i]) ||
Double.isInfinite(uB[i])) {
hasInfiniteBounds = true;
break;
}
}
if (hasInfiniteBounds) {
// If there is at least one finite bound, none can be infinite,
// because mixed cases are not supported by the current code.
throw new MathUnsupportedOperationException();
} else {
// Convert API to internal handling of boundaries.
boundaries = new double[2][];
boundaries[0] = lB;
boundaries[1] = uB;
// Abort early if the normalization will overflow (cf. "encode" method).
}
} else {
// Convert API to internal handling of boundaries.
boundaries = null;
}
if (inputSigma != null) {
if (inputSigma.length != init.length) {
throw new DimensionMismatchException(inputSigma.length, init.length);
}
for (int i = 0; i < init.length; i++) {
if (inputSigma[i] < 0) {
throw new NotPositiveException(inputSigma[i]);
}
if (boundaries != null) {
if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) {
throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]);
}
}
}
}
}
|
private void checkParameters() {
final double[] init = getStartPoint();
final double[] lB = getLowerBound();
final double[] uB = getUpperBound();
// Checks whether there is at least one finite bound value.
boolean hasFiniteBounds = false;
for (int i = 0; i < lB.length; i++) {
if (!Double.isInfinite(lB[i]) ||
!Double.isInfinite(uB[i])) {
hasFiniteBounds = true;
break;
}
}
// Checks whether there is at least one infinite bound value.
boolean hasInfiniteBounds = false;
if (hasFiniteBounds) {
for (int i = 0; i < lB.length; i++) {
if (Double.isInfinite(lB[i]) ||
Double.isInfinite(uB[i])) {
hasInfiniteBounds = true;
break;
}
}
if (hasInfiniteBounds) {
// If there is at least one finite bound, none can be infinite,
// because mixed cases are not supported by the current code.
throw new MathUnsupportedOperationException();
} else {
// Convert API to internal handling of boundaries.
boundaries = new double[2][];
boundaries[0] = lB;
boundaries[1] = uB;
// Abort early if the normalization will overflow (cf. "encode" method).
for (int i = 0; i < lB.length; i++) {
if (Double.isInfinite(boundaries[1][i] - boundaries[0][i])) {
final double max = Double.MAX_VALUE + boundaries[0][i];
final NumberIsTooLargeException e
= new NumberIsTooLargeException(boundaries[1][i],
max,
true);
e.getContext().addMessage(LocalizedFormats.OVERFLOW);
e.getContext().addMessage(LocalizedFormats.INDEX, i);
throw e;
}
}
}
} else {
// Convert API to internal handling of boundaries.
boundaries = null;
}
if (inputSigma != null) {
if (inputSigma.length != init.length) {
throw new DimensionMismatchException(inputSigma.length, init.length);
}
for (int i = 0; i < init.length; i++) {
if (inputSigma[i] < 0) {
throw new NotPositiveException(inputSigma[i]);
}
if (boundaries != null) {
if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) {
throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]);
}
}
}
}
}
|
src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java
|
Wide bounds to CMAESOptimizer result in NaN parameters passed to fitness function
|
If you give large values as lower/upper bounds (for example -Double.MAX_VALUE as a lower bound), the optimizer can call the fitness function with parameters set to NaN. My guess is this is due to FitnessFunction.encode/decode generating NaN when normalizing/denormalizing parameters. For example, if the difference between the lower and upper bound is greater than Double.MAX_VALUE, encode could divide infinity by infinity.
| 504 | 561 |
Math-2
|
public double getNumericalMean() {
return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize();
}
|
public double getNumericalMean() {
return getSampleSize() * (getNumberOfSuccesses() / (double) getPopulationSize());
}
|
src/main/java/org/apache/commons/math3/distribution/HypergeometricDistribution.java
|
HypergeometricDistribution.sample suffers from integer overflow
|
Hi, I have an application which broke when ported from commons math 2.2 to 3.2. It looks like the HypergeometricDistribution.sample() method doesn't work as well as it used to with large integer values – the example code below should return a sample between 0 and 50, but usually returns -50.
import org.apache.commons.math3.distribution.HypergeometricDistribution;
public class Foo {
public static void main(String[] args) {
HypergeometricDistribution a = new HypergeometricDistribution(
43130568, 42976365, 50);
System.out.printf("%d %d%n", a.getSupportLowerBound(), a.getSupportUpperBound()); // Prints "0 50"
System.out.printf("%d%n",a.sample()); // Prints "-50"
}
}
In the debugger, I traced it as far as an integer overflow in HypergeometricDistribution.getNumericalMean() – instead of doing
return (double) (getSampleSize() * getNumberOfSuccesses()) / (double) getPopulationSize();
it could do:
return getSampleSize() * ((double) getNumberOfSuccesses() / (double) getPopulationSize());
This seemed to fix it, based on a quick test.
| 267 | 269 |
Math-20
|
public double[] repairAndDecode(final double[] x) {
return
decode(x);
}
|
public double[] repairAndDecode(final double[] x) {
return boundaries != null && isRepairMode ?
decode(repair(x)) :
decode(x);
}
|
src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java
|
CMAESOptimizer does not enforce bounds
|
The CMAESOptimizer can exceed the bounds passed to optimize. Looking at the generationLoop in doOptimize(), it does a bounds check by calling isFeasible() but if checkFeasableCount is zero (the default) then isFeasible() is never even called. Also, even with non-zero checkFeasableCount it may give up before finding an in-bounds offspring and go forward with an out-of-bounds offspring. This is against svn revision 1387637. I can provide an example program where the optimizer ends up with a fit outside the prescribed bounds if that would help.
| 920 | 923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.