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(); ...
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(); ...
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()...
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()...
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: [databi...
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: [databi...
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 ...
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) { _l...
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) { _l...
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\">...
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.serial...
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 inst...
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-x...
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 ...
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...
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...
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); ...
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); ...
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:/...
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.ha...
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) ...
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) val...
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 san...
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("&lt;"); parseTextNode(); return; } Attributes attributes = new Att...
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("&lt;"); parseTextNode(); return; } Attributes attributes = new Att...
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 ho...
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...
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...
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()) { ...
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()...
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>...
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.b...
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 copySafeNode...
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 nul...
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(Loc...
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 ...
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 class...
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 Toke...
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(To...
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 inc...
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[...
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[...
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....
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...
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...
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...
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, ...
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 foll...
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 elementSiblingInd...
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)) { ...
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)) { ...
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.equalsIgn...
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.equalsIgn...
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...
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 ...
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.matchCh...
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.matchCh...
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 StringIndexOutOfBoundsEx...
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...
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] ...
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 b...
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">&#9312;&#35373;&#35336; &#38283;&#22987;&#20104;&#23450...
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 ...
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('"') &...
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.getValu...
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_...
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 star...
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); ...
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); ...
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 iterato...
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 = pendingAttrib...
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 = pendingAttrib...
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,...
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....
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....
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.Pa...
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...
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)) {...
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...
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> &lt;/head&gt; &lt;body&gt; &lt...
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...
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; ...
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; ...
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()) ...
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.o...
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 < ...
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 of...
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); // ...
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); // ...
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\"...
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; } ...
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; ...
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 publ...
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 p...
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 p...
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...
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 = update...
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 = update...
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 ...
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(...
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 XmlDeclaratio...
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(Stri...
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 Attrib...
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...
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 ...
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 ...
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.help...
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 ...
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 ...
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=] ...
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 co...
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 testNam...
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 testNam...
src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java
Incomplete handling of undefined namespaces
Mcduffey, Joe <jdmcduf@nsa.gov> 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:Ele...
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) conte...
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) conte...
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 incorrec...
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(); iter...
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_N...
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 ...
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(); } ...
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(); } ...
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"...
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 = pr...
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 = pr...
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> ...
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, d...
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, d...
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.compareNod...
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.getClas...
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.getClas...
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 &...
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 &...
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; rege...
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; ...
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 th...
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 th...
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 th...
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 th...
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 i...
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...
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 obje...
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()); w...
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 consu...
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, // b...
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...
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...
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java
StringIndexOutOfBoundsException when calling unescapeHtml4("&#03")
When calling unescapeHtml4() on the String "&#03" (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.NumericEnti...
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(C...
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(C...
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 compar...
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 larg...
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 ei...
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. FractionTe...
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 ...
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); ...
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); ...
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...
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....
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++)...
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;...
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 = ...
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();...
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 ? n...
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 + array...
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 + array...
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(ArrayUtil...
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 exam...
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)) { ...
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("&#"); ...
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) { ...
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 representatio...
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 ...
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(QUO...
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...
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 t...
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 t...
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 ...
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); ...
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) { ...
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 ...
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 stri...
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 stri...
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 ...
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 ...
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(\'aa...
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 ...
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 ...
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 Loca...
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...
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, ...
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, s...
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...
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 consu...
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 consu...
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...
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(patter...
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(patter...
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 dou...
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 dou...
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...
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...
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()...
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) || !is...
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) || !is...
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]);...
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 ...
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, -...
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,...
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 s...
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 de...
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 (!Doubl...
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 (!Doubl...
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 bet...
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....
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 a...
920
923