id
stringlengths
5
19
content
stringlengths
94
57.5k
max_stars_repo_path
stringlengths
36
95
Jsoup-47
static void escape(StringBuilder accum, String string, Document.OutputSettings out, boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) { boolean lastWasWhite = false; boolean reachedNonWhite = false; final EscapeMode escapeMode = out.escapeMode(); final CharsetEncoder encoder = out.encoder(); final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name()); final Map<Character, String> map = escapeMode.getMap(); final int length = string.length(); int codePoint; for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) { codePoint = string.codePointAt(offset); if (normaliseWhite) { if (StringUtil.isWhitespace(codePoint)) { if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) continue; accum.append(' '); lastWasWhite = true; continue; } else { lastWasWhite = false; reachedNonWhite = true; } } // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]): if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) { final char c = (char) codePoint; // html specific and required escapes: switch (c) { case '&': accum.append("&amp;"); break; case 0xA0: if (escapeMode != EscapeMode.xhtml) accum.append("&nbsp;"); else accum.append("&#xa0;"); break; case '<': // escape when in character data or when in a xml attribue val; not needed in html attr val if (!inAttribute) accum.append("&lt;"); else accum.append(c); break; case '>': if (!inAttribute) accum.append("&gt;"); else accum.append(c); break; case '"': if (inAttribute) accum.append("&quot;"); else accum.append(c); break; default: if (canEncode(coreCharset, c, encoder)) accum.append(c); else if (map.containsKey(c)) accum.append('&').append(map.get(c)).append(';'); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } else { final String c = new String(Character.toChars(codePoint)); if (encoder.canEncode(c)) // uses fallback encoder for simplicity accum.append(c); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } } static void escape(StringBuilder accum, String string, Document.OutputSettings out, boolean inAttribute, boolean normaliseWhite, boolean stripLeadingWhite) { boolean lastWasWhite = false; boolean reachedNonWhite = false; final EscapeMode escapeMode = out.escapeMode(); final CharsetEncoder encoder = out.encoder(); final CoreCharset coreCharset = CoreCharset.byName(encoder.charset().name()); final Map<Character, String> map = escapeMode.getMap(); final int length = string.length(); int codePoint; for (int offset = 0; offset < length; offset += Character.charCount(codePoint)) { codePoint = string.codePointAt(offset); if (normaliseWhite) { if (StringUtil.isWhitespace(codePoint)) { if ((stripLeadingWhite && !reachedNonWhite) || lastWasWhite) continue; accum.append(' '); lastWasWhite = true; continue; } else { lastWasWhite = false; reachedNonWhite = true; } } // surrogate pairs, split implementation for efficiency on single char common case (saves creating strings, char[]): if (codePoint < Character.MIN_SUPPLEMENTARY_CODE_POINT) { final char c = (char) codePoint; // html specific and required escapes: switch (c) { case '&': accum.append("&amp;"); break; case 0xA0: if (escapeMode != EscapeMode.xhtml) accum.append("&nbsp;"); else accum.append("&#xa0;"); break; case '<': // escape when in character data or when in a xml attribue val; not needed in html attr val if (!inAttribute || escapeMode == EscapeMode.xhtml) accum.append("&lt;"); else accum.append(c); break; case '>': if (!inAttribute) accum.append("&gt;"); else accum.append(c); break; case '"': if (inAttribute) accum.append("&quot;"); else accum.append(c); break; default: if (canEncode(coreCharset, c, encoder)) accum.append(c); else if (map.containsKey(c)) accum.append('&').append(map.get(c)).append(';'); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } else { final String c = new String(Character.toChars(codePoint)); if (encoder.canEncode(c)) // uses fallback encoder for simplicity accum.append(c); else accum.append("&#x").append(Integer.toHexString(codePoint)).append(';'); } } }
src/main/java/org/jsoup/nodes/Entities.java
Jsoup-48
void processResponseHeaders(Map<String, List<String>> resHeaders) { for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; // http/1.1 line List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); // ignores path, date, domain, validateTLSCertificates et al. req'd? // name not blank, value not null if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { // combine same header names with comma: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 if (!values.isEmpty()) header(name, values.get(0)); } } } void processResponseHeaders(Map<String, List<String>> resHeaders) { for (Map.Entry<String, List<String>> entry : resHeaders.entrySet()) { String name = entry.getKey(); if (name == null) continue; // http/1.1 line List<String> values = entry.getValue(); if (name.equalsIgnoreCase("Set-Cookie")) { for (String value : values) { if (value == null) continue; TokenQueue cd = new TokenQueue(value); String cookieName = cd.chompTo("=").trim(); String cookieVal = cd.consumeTo(";").trim(); // ignores path, date, domain, validateTLSCertificates et al. req'd? // name not blank, value not null if (cookieName.length() > 0) cookie(cookieName, cookieVal); } } else { // combine same header names with comma: http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2 if (values.size() == 1) header(name, values.get(0)); else if (values.size() > 1) { StringBuilder accum = new StringBuilder(); for (int i = 0; i < values.size(); i++) { final String val = values.get(i); if (i != 0) accum.append(", "); accum.append(val); } header(name, accum.toString()); } } } }
src/main/java/org/jsoup/helper/HttpConnection.java
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
Jsoup-5
private Attribute parseAttribute() { tq.consumeWhitespace(); String key = tq.consumeAttributeKey(); String value = ""; tq.consumeWhitespace(); if (tq.matchChomp("=")) { tq.consumeWhitespace(); if (tq.matchChomp(SQ)) { value = tq.chompTo(SQ); } else if (tq.matchChomp(DQ)) { value = tq.chompTo(DQ); } else { StringBuilder valueAccum = new StringBuilder(); // no ' or " to look for, so scan to end tag or space (or end of stream) while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) { valueAccum.append(tq.consume()); } value = valueAccum.toString(); } tq.consumeWhitespace(); } if (key.length() != 0) return Attribute.createFromEncoded(key, value); else { tq.consume(); return null; } } private Attribute parseAttribute() { tq.consumeWhitespace(); String key = tq.consumeAttributeKey(); String value = ""; tq.consumeWhitespace(); if (tq.matchChomp("=")) { tq.consumeWhitespace(); if (tq.matchChomp(SQ)) { value = tq.chompTo(SQ); } else if (tq.matchChomp(DQ)) { value = tq.chompTo(DQ); } else { StringBuilder valueAccum = new StringBuilder(); // no ' or " to look for, so scan to end tag or space (or end of stream) while (!tq.matchesAny("<", "/>", ">") && !tq.matchesWhitespace() && !tq.isEmpty()) { valueAccum.append(tq.consume()); } value = valueAccum.toString(); } tq.consumeWhitespace(); } if (key.length() != 0) return Attribute.createFromEncoded(key, value); else { if (value.length() == 0) // no key, no val; unknown char, keep popping so not get stuck tq.advance(); return null; } }
src/main/java/org/jsoup/parser/Parser.java
Jsoup-50
static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; // look for BOM - overrides any other header or input if (charsetName == null) { // determine from meta. safe parse as UTF-8 // look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312"> docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { // if not found, will keep utf-8 as best attempt String foundCharset = null; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); } if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { // specified by content type header (or by user on file load) Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (docData.length() > 0 && docData.charAt(0) == UNICODE_BOM) { byteData.rewind(); docData = Charset.forName(defaultCharset).decode(byteData).toString(); docData = docData.substring(1); charsetName = defaultCharset; doc = null; } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; } static Document parseByteData(ByteBuffer byteData, String charsetName, String baseUri, Parser parser) { String docData; Document doc = null; // look for BOM - overrides any other header or input byteData.mark(); byte[] bom = new byte[4]; byteData.get(bom); byteData.rewind(); if (bom[0] == 0x00 && bom[1] == 0x00 && bom[2] == (byte) 0xFE && bom[3] == (byte) 0xFF || // BE bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE && bom[2] == 0x00 && bom[3] == 0x00) { // LE charsetName = "UTF-32"; // and I hope it's on your system } else if (bom[0] == (byte) 0xFE && bom[1] == (byte) 0xFF || // BE bom[0] == (byte) 0xFF && bom[1] == (byte) 0xFE) { charsetName = "UTF-16"; // in all Javas } else if (bom[0] == (byte) 0xEF && bom[1] == (byte) 0xBB && bom[2] == (byte) 0xBF) { charsetName = "UTF-8"; // in all Javas byteData.position(3); // 16 and 32 decoders consume the BOM to determine be/le; utf-8 should be consumed } if (charsetName == null) { // determine from meta. safe parse as UTF-8 // look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312"> docData = Charset.forName(defaultCharset).decode(byteData).toString(); doc = parser.parseInput(docData, baseUri); Element meta = doc.select("meta[http-equiv=content-type], meta[charset]").first(); if (meta != null) { // if not found, will keep utf-8 as best attempt String foundCharset = null; if (meta.hasAttr("http-equiv")) { foundCharset = getCharsetFromContentType(meta.attr("content")); } if (foundCharset == null && meta.hasAttr("charset")) { try { if (Charset.isSupported(meta.attr("charset"))) { foundCharset = meta.attr("charset"); } } catch (IllegalCharsetNameException e) { foundCharset = null; } } if (foundCharset != null && foundCharset.length() != 0 && !foundCharset.equals(defaultCharset)) { // need to re-decode foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; byteData.rewind(); docData = Charset.forName(foundCharset).decode(byteData).toString(); doc = null; } } } else { // specified by content type header (or by user on file load) Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); docData = Charset.forName(charsetName).decode(byteData).toString(); } if (doc == null) { doc = parser.parseInput(docData, baseUri); doc.outputSettings().charset(charsetName); } return doc; }
src/main/java/org/jsoup/helper/DataUtil.java
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
Jsoup-53
public String chompBalanced(char open, char close) { int start = -1; int end = -1; int depth = 0; char last = 0; do { if (isEmpty()) break; Character c = consume(); if (last == 0 || last != ESC) { if (c.equals(open)) { depth++; if (start == -1) start = pos; } else if (c.equals(close)) depth--; } if (depth > 0 && last != 0) end = pos; // don't include the outer match pair in the return last = c; } while (depth > 0); return (end >= 0) ? queue.substring(start, end) : ""; } public String chompBalanced(char open, char close) { int start = -1; int end = -1; int depth = 0; char last = 0; boolean inQuote = false; do { if (isEmpty()) break; Character c = consume(); if (last == 0 || last != ESC) { if (c.equals('\'') || c.equals('"') && c != open) inQuote = !inQuote; if (inQuote) continue; if (c.equals(open)) { depth++; if (start == -1) start = pos; } else if (c.equals(close)) depth--; } if (depth > 0 && last != 0) end = pos; // don't include the outer match pair in the return last = c; } while (depth > 0); return (end >= 0) ? queue.substring(start, end) : ""; }
src/main/java/org/jsoup/parser/TokenQueue.java
Jsoup-54
private void copyAttributes(org.jsoup.nodes.Node source, Element el) { for (Attribute attribute : source.attributes()) { // valid xml attribute names are: ^[a-zA-Z_:][-a-zA-Z0-9_:.] String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", ""); el.setAttribute(key, attribute.getValue()); } } private void copyAttributes(org.jsoup.nodes.Node source, Element el) { for (Attribute attribute : source.attributes()) { // valid xml attribute names are: ^[a-zA-Z_:][-a-zA-Z0-9_:.] String key = attribute.getKey().replaceAll("[^-a-zA-Z0-9_:.]", ""); if (key.matches("[a-zA-Z_:]{1}[-a-zA-Z0-9_:.]*")) el.setAttribute(key, attribute.getValue()); } }
src/main/java/org/jsoup/helper/W3CDom.java
Jsoup-55
void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.tagPending.selfClosing = true; t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); t.transition(BeforeAttributeName); } } void read(Tokeniser t, CharacterReader r) { char c = r.consume(); switch (c) { case '>': t.tagPending.selfClosing = true; t.emitTagPending(); t.transition(Data); break; case eof: t.eofError(this); t.transition(Data); break; default: t.error(this); r.unconsume(); t.transition(BeforeAttributeName); } }
src/main/java/org/jsoup/parser/TokeniserState.java
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
Jsoup-59
final void newAttribute() { if (attributes == null) attributes = new Attributes(); if (pendingAttributeName != null) { // the tokeniser has skipped whitespace control chars, but trimming could collapse to empty for other control codes, so verify here pendingAttributeName = pendingAttributeName.trim(); Attribute attribute; if (hasPendingAttributeValue) attribute = new Attribute(pendingAttributeName, pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS); else if (hasEmptyAttributeValue) attribute = new Attribute(pendingAttributeName, ""); else attribute = new BooleanAttribute(pendingAttributeName); attributes.put(attribute); } pendingAttributeName = null; hasEmptyAttributeValue = false; hasPendingAttributeValue = false; reset(pendingAttributeValue); pendingAttributeValueS = null; } final void newAttribute() { if (attributes == null) attributes = new Attributes(); if (pendingAttributeName != null) { // the tokeniser has skipped whitespace control chars, but trimming could collapse to empty for other control codes, so verify here pendingAttributeName = pendingAttributeName.trim(); if (pendingAttributeName.length() > 0) { Attribute attribute; if (hasPendingAttributeValue) attribute = new Attribute(pendingAttributeName, pendingAttributeValue.length() > 0 ? pendingAttributeValue.toString() : pendingAttributeValueS); else if (hasEmptyAttributeValue) attribute = new Attribute(pendingAttributeName, ""); else attribute = new BooleanAttribute(pendingAttributeName); attributes.put(attribute); } } pendingAttributeName = null; hasEmptyAttributeValue = false; hasPendingAttributeValue = false; reset(pendingAttributeValue); pendingAttributeValueS = null; }
src/main/java/org/jsoup/parser/Token.java
Jsoup-6
static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs // todo: replace m.appendReplacement with own impl, so StringBuilder and quoteReplacement not required while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, c); } else { m.appendReplacement(accum, m.group(0)); } } m.appendTail(accum); return accum.toString(); } static String unescape(String string) { if (!string.contains("&")) return string; Matcher m = unescapePattern.matcher(string); // &(#(x|X)?([0-9a-fA-F]+)|[a-zA-Z]+);? StringBuffer accum = new StringBuffer(string.length()); // pity matcher can't use stringbuilder, avoid syncs // todo: replace m.appendReplacement with own impl, so StringBuilder and quoteReplacement not required while (m.find()) { int charval = -1; String num = m.group(3); if (num != null) { try { int base = m.group(2) != null ? 16 : 10; // 2 is hex indicator charval = Integer.valueOf(num, base); } catch (NumberFormatException e) { } // skip } else { String name = m.group(1); if (full.containsKey(name)) charval = full.get(name); } if (charval != -1 || charval > 0xFFFF) { // out of range String c = Character.toString((char) charval); m.appendReplacement(accum, Matcher.quoteReplacement(c)); } else { m.appendReplacement(accum, Matcher.quoteReplacement(m.group(0))); // replace with original string } } m.appendTail(accum); return accum.toString(); }
src/main/java/org/jsoup/nodes/Entities.java
Jsoup-61
public boolean hasClass(String className) { final String classAttr = attributes.get("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } // if both lengths are equal, only need compare the className with the attribute if (len == wantLen) { return className.equalsIgnoreCase(classAttr); } // otherwise, scan for whitespace and compare regions (with no string or arraylist allocations) boolean inClass = false; int start = 0; for (int i = 0; i < len; i++) { if (Character.isWhitespace(classAttr.charAt(i))) { if (inClass) { // white space ends a class name, compare it with the requested one, ignore case if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) { return true; } inClass = false; } } else { if (!inClass) { // we're in a class name : keep the start of the substring inClass = true; start = i; } } } // check the last entry if (inClass && len - start == wantLen) { return classAttr.regionMatches(true, start, className, 0, wantLen); } return false; } public boolean hasClass(String className) { final String classAttr = attributes.getIgnoreCase("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } // if both lengths are equal, only need compare the className with the attribute if (len == wantLen) { return className.equalsIgnoreCase(classAttr); } // otherwise, scan for whitespace and compare regions (with no string or arraylist allocations) boolean inClass = false; int start = 0; for (int i = 0; i < len; i++) { if (Character.isWhitespace(classAttr.charAt(i))) { if (inClass) { // white space ends a class name, compare it with the requested one, ignore case if (i - start == wantLen && classAttr.regionMatches(true, start, className, 0, wantLen)) { return true; } inClass = false; } } else { if (!inClass) { // we're in a class name : keep the start of the substring inClass = true; start = i; } } } // check the last entry if (inClass && len - start == wantLen) { return classAttr.regionMatches(true, start, className, 0, wantLen); } return false; }
src/main/java/org/jsoup/nodes/Element.java
Jsoup-62
boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) { String name = t.asEndTag().normalName(); ArrayList<Element> stack = tb.getStack(); for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; } boolean anyOtherEndTag(Token t, HtmlTreeBuilder tb) { String name = t.asEndTag().name(); // matches with case sensitivity if enabled ArrayList<Element> stack = tb.getStack(); for (int pos = stack.size() -1; pos >= 0; pos--) { Element node = stack.get(pos); if (node.nodeName().equals(name)) { tb.generateImpliedEndTags(name); if (!name.equals(tb.currentElement().nodeName())) tb.error(this); tb.popStackToClose(name); break; } else { if (tb.isSpecial(node)) { tb.error(this); return false; } } } return true; }
src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java
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
Jsoup-68
private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) { // https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope int bottom = stack.size() -1; if (bottom > MaxScopeSearchDepth) { bottom = MaxScopeSearchDepth; } final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0; // don't walk too far up the tree for (int pos = bottom; pos >= top; pos--) { final String elName = stack.get(pos).nodeName(); if (inSorted(elName, targetNames)) return true; if (inSorted(elName, baseTypes)) return false; if (extraTypes != null && inSorted(elName, extraTypes)) return false; } //Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes) return false; } private boolean inSpecificScope(String[] targetNames, String[] baseTypes, String[] extraTypes) { // https://html.spec.whatwg.org/multipage/parsing.html#has-an-element-in-the-specific-scope final int bottom = stack.size() -1; final int top = bottom > MaxScopeSearchDepth ? bottom - MaxScopeSearchDepth : 0; // don't walk too far up the tree for (int pos = bottom; pos >= top; pos--) { final String elName = stack.get(pos).nodeName(); if (inSorted(elName, targetNames)) return true; if (inSorted(elName, baseTypes)) return false; if (extraTypes != null && inSorted(elName, extraTypes)) return false; } //Validate.fail("Should not be reachable"); // would end up false because hitting 'html' at root (basetypes) return false; }
src/main/java/org/jsoup/parser/HtmlTreeBuilder.java
Jsoup-70
static boolean preserveWhitespace(Node node) { // looks only at this element and five levels up, to prevent recursion & needless stack searches if (node != null && node instanceof Element) { Element el = (Element) node; if (el.tag.preserveWhitespace()) return true; else return el.parent() != null && el.parent().tag.preserveWhitespace(); } return false; } static boolean preserveWhitespace(Node node) { // looks only at this element and five levels up, to prevent recursion & needless stack searches if (node != null && node instanceof Element) { Element el = (Element) node; int i = 0; do { if (el.tag.preserveWhitespace()) return true; el = el.parent(); i++; } while (i < 6 && el != null); } return false; }
src/main/java/org/jsoup/nodes/Element.java
Jsoup-72
private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) { // limit (no cache): if (count > maxStringCacheLen) return new String(charBuf, start, count); // calculate hash: int hash = 0; int offset = start; for (int i = 0; i < count; i++) { hash = 31 * hash + charBuf[offset++]; } // get from cache final int index = hash & stringCache.length - 1; String cached = stringCache[index]; if (cached == null) { // miss, add cached = new String(charBuf, start, count); stringCache[index] = cached; } else { // hashcode hit, check equality if (rangeEquals(charBuf, start, count, cached)) { // hit return cached; } else { // hashcode conflict cached = new String(charBuf, start, count); stringCache[index] = cached; // update the cache, as recently used strings are more likely to show up again } } return cached; } private static String cacheString(final char[] charBuf, final String[] stringCache, final int start, final int count) { // limit (no cache): if (count > maxStringCacheLen) return new String(charBuf, start, count); if (count < 1) return ""; // calculate hash: int hash = 0; int offset = start; for (int i = 0; i < count; i++) { hash = 31 * hash + charBuf[offset++]; } // get from cache final int index = hash & stringCache.length - 1; String cached = stringCache[index]; if (cached == null) { // miss, add cached = new String(charBuf, start, count); stringCache[index] = cached; } else { // hashcode hit, check equality if (rangeEquals(charBuf, start, count, cached)) { // hit return cached; } else { // hashcode conflict cached = new String(charBuf, start, count); stringCache[index] = cached; // update the cache, as recently used strings are more likely to show up again } } return cached; }
src/main/java/org/jsoup/parser/CharacterReader.java
Jsoup-75
final void html(final Appendable accum, final Document.OutputSettings out) throws IOException { final int sz = size; for (int i = 0; i < sz; i++) { // inlined from Attribute.html() final String key = keys[i]; final String val = vals[i]; accum.append(' ').append(key); // collapse checked=null, checked="", checked=checked; write out others if (!(out.syntax() == Document.OutputSettings.Syntax.html && (val == null || val.equals(key) && Attribute.isBooleanAttribute(key)))) { accum.append("=\""); Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false); accum.append('"'); } } } final void html(final Appendable accum, final Document.OutputSettings out) throws IOException { final int sz = size; for (int i = 0; i < sz; i++) { // inlined from Attribute.html() final String key = keys[i]; final String val = vals[i]; accum.append(' ').append(key); // collapse checked=null, checked="", checked=checked; write out others if (!Attribute.shouldCollapseAttribute(key, val, out)) { accum.append("=\""); Entities.escape(accum, val == null ? EmptyString : val, out, true, false, false); accum.append('"'); } } }
src/main/java/org/jsoup/nodes/Attributes.java
Jsoup-76
boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { // todo confirm that check tb.error(this); return false; } else if (tb.framesetOk() && isWhitespace(c)) { // don't check if whitespace if frames already closed tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); // todo - refactor to a switch statement String name = startTag.normalName(); if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.processEndTag("a"); // still on stack? Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.inSorted(name, Constants.InBodyStartEmptyFormatters)) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("span")) { // same as final else, but short circuits lots of checks tb.reconstructFormattingElements(); tb.insert(startTag); } else if (name.equals("li")) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.processEndTag("li"); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("html")) { tb.error(this); // merge attributes onto real html Element html = tb.getStack().get(0); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); ArrayList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); ArrayList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else if (!tb.framesetOk()) { return false; // ignore frameset } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); // pop up to html element while (stack.size() > 1) stack.remove(stack.size()-1); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertForm(startTag, true); } else if (StringUtil.inSorted(name, Constants.DdDt)) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) { tb.processEndTag(el.nodeName()); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out } else if (name.equals("button")) { if (tb.inButtonScope("button")) { // close and reprocess tb.error(this); tb.processEndTag("button"); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (StringUtil.inSorted(name, Constants.Formatters)) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.processEndTag("nobr"); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { if (tb.getFromStack("svg") == null) return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg else tb.insert(startTag); } else if (name.equals("isindex")) { // how much do we care about the early 90s? tb.error(this); if (tb.getFormElement() != null) return false; tb.processStartTag("form"); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.processStartTag("hr"); tb.processStartTag("label"); // hope you like english. String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character().data(prompt)); // input Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs)) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.processStartTag("input", inputAttribs); tb.processEndTag("label"); tb.processStartTag("hr"); tb.processEndTag("form"); } else if (name.equals("textarea")) { tb.insert(startTag); // todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.) tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { // also handle noscript if script enabled handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); HtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.inSorted(name, Constants.InBodyStartOptions)) { if (tb.currentElement().nodeName().equals("option")) tb.processEndTag("option"); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); // i.e. close up to but not include name } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml) tb.insert(startTag); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "svg" (xlink, svg) tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.normalName(); if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) { // Adoption Agency Algorithm. for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; ArrayList<Element> stack = tb.getStack(); // the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents // run-aways final int stackSize = stack.size(); for (int si = 0; si < stackSize && si < 64; si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } // todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list. // does that mean: int pos of format el in list? Element node = furthestBlock; Element lastNode = furthestBlock; for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check tb.removeFromStack(node); continue; } else if (node == formatEl) break; Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri()); // case will follow the original node (so honours ParseSettings) tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { // todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements. // not getting how this bookmark both straddles the element above, but is inbetween here... } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(formatEl.tag(), tb.getBaseUri()); adopter.attributes().addAll(formatEl.attributes()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod. } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); // todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark. tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.inSorted(name, Constants.InBodyEndClosers)) { if (!tb.inScope(name)) { // nothing to close tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("span")) { // same as final fall through, but saves short circuit return anyOtherEndTag(t, tb); } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { // todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.processEndTag("body"); if (notIgnored) return tb.process(endTag); } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); // remove currentForm from stack. will shift anything under up. tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.processStartTag(name); // if no p to close, creates an empty <p></p> return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.DdDt)) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (!tb.inScope(Constants.Headings)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(Constants.Headings); } } else if (name.equals("sarcasm")) { // *sigh* return anyOtherEndTag(t, tb); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.processStartTag("br"); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: // todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html // stop parsing break; } return true; } boolean process(Token t, HtmlTreeBuilder tb) { switch (t.type) { case Character: { Token.Character c = t.asCharacter(); if (c.getData().equals(nullString)) { // todo confirm that check tb.error(this); return false; } else if (tb.framesetOk() && isWhitespace(c)) { // don't check if whitespace if frames already closed tb.reconstructFormattingElements(); tb.insert(c); } else { tb.reconstructFormattingElements(); tb.insert(c); tb.framesetOk(false); } break; } case Comment: { tb.insert(t.asComment()); break; } case Doctype: { tb.error(this); return false; } case StartTag: Token.StartTag startTag = t.asStartTag(); // todo - refactor to a switch statement String name = startTag.normalName(); if (name.equals("a")) { if (tb.getActiveFormattingElement("a") != null) { tb.error(this); tb.processEndTag("a"); // still on stack? Element remainingA = tb.getFromStack("a"); if (remainingA != null) { tb.removeFromActiveFormattingElements(remainingA); tb.removeFromStack(remainingA); } } tb.reconstructFormattingElements(); Element a = tb.insert(startTag); tb.pushActiveFormattingElements(a); } else if (StringUtil.inSorted(name, Constants.InBodyStartEmptyFormatters)) { tb.reconstructFormattingElements(); tb.insertEmpty(startTag); tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartPClosers)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("span")) { // same as final else, but short circuits lots of checks tb.reconstructFormattingElements(); tb.insert(startTag); } else if (name.equals("li")) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (el.nodeName().equals("li")) { tb.processEndTag("li"); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("html")) { tb.error(this); // merge attributes onto real html Element html = tb.getStack().get(0); for (Attribute attribute : startTag.getAttributes()) { if (!html.hasAttr(attribute.getKey())) html.attributes().put(attribute); } } else if (StringUtil.inSorted(name, Constants.InBodyStartToHead)) { return tb.process(t, InHead); } else if (name.equals("body")) { tb.error(this); ArrayList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else { tb.framesetOk(false); Element body = stack.get(1); for (Attribute attribute : startTag.getAttributes()) { if (!body.hasAttr(attribute.getKey())) body.attributes().put(attribute); } } } else if (name.equals("frameset")) { tb.error(this); ArrayList<Element> stack = tb.getStack(); if (stack.size() == 1 || (stack.size() > 2 && !stack.get(1).nodeName().equals("body"))) { // only in fragment case return false; // ignore } else if (!tb.framesetOk()) { return false; // ignore frameset } else { Element second = stack.get(1); if (second.parent() != null) second.remove(); // pop up to html element while (stack.size() > 1) stack.remove(stack.size()-1); tb.insert(startTag); tb.transition(InFrameset); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } if (StringUtil.inSorted(tb.currentElement().nodeName(), Constants.Headings)) { tb.error(this); tb.pop(); } tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartPreListing)) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.reader.matchConsume("\n"); // ignore LF if next token tb.framesetOk(false); } else if (name.equals("form")) { if (tb.getFormElement() != null) { tb.error(this); return false; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertForm(startTag, true); } else if (StringUtil.inSorted(name, Constants.DdDt)) { tb.framesetOk(false); ArrayList<Element> stack = tb.getStack(); for (int i = stack.size() - 1; i > 0; i--) { Element el = stack.get(i); if (StringUtil.inSorted(el.nodeName(), Constants.DdDt)) { tb.processEndTag(el.nodeName()); break; } if (tb.isSpecial(el) && !StringUtil.inSorted(el.nodeName(), Constants.InBodyStartLiBreakers)) break; } if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); } else if (name.equals("plaintext")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.tokeniser.transition(TokeniserState.PLAINTEXT); // once in, never gets out } else if (name.equals("button")) { if (tb.inButtonScope("button")) { // close and reprocess tb.error(this); tb.processEndTag("button"); tb.process(startTag); } else { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); } } else if (StringUtil.inSorted(name, Constants.Formatters)) { tb.reconstructFormattingElements(); Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (name.equals("nobr")) { tb.reconstructFormattingElements(); if (tb.inScope("nobr")) { tb.error(this); tb.processEndTag("nobr"); tb.reconstructFormattingElements(); } Element el = tb.insert(startTag); tb.pushActiveFormattingElements(el); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.insertMarkerToFormattingElements(); tb.framesetOk(false); } else if (name.equals("table")) { if (tb.getDocument().quirksMode() != Document.QuirksMode.quirks && tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insert(startTag); tb.framesetOk(false); tb.transition(InTable); } else if (name.equals("input")) { tb.reconstructFormattingElements(); Element el = tb.insertEmpty(startTag); if (!el.attr("type").equalsIgnoreCase("hidden")) tb.framesetOk(false); } else if (StringUtil.inSorted(name, Constants.InBodyStartMedia)) { tb.insertEmpty(startTag); } else if (name.equals("hr")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.insertEmpty(startTag); tb.framesetOk(false); } else if (name.equals("image")) { if (tb.getFromStack("svg") == null) return tb.process(startTag.name("img")); // change <image> to <img>, unless in svg else tb.insert(startTag); } else if (name.equals("isindex")) { // how much do we care about the early 90s? tb.error(this); if (tb.getFormElement() != null) return false; tb.processStartTag("form"); if (startTag.attributes.hasKey("action")) { Element form = tb.getFormElement(); form.attr("action", startTag.attributes.get("action")); } tb.processStartTag("hr"); tb.processStartTag("label"); // hope you like english. String prompt = startTag.attributes.hasKey("prompt") ? startTag.attributes.get("prompt") : "This is a searchable index. Enter search keywords: "; tb.process(new Token.Character().data(prompt)); // input Attributes inputAttribs = new Attributes(); for (Attribute attr : startTag.attributes) { if (!StringUtil.inSorted(attr.getKey(), Constants.InBodyStartInputAttribs)) inputAttribs.put(attr); } inputAttribs.put("name", "isindex"); tb.processStartTag("input", inputAttribs); tb.processEndTag("label"); tb.processStartTag("hr"); tb.processEndTag("form"); } else if (name.equals("textarea")) { tb.insert(startTag); // todo: If the next token is a U+000A LINE FEED (LF) character token, then ignore that token and move on to the next one. (Newlines at the start of textarea elements are ignored as an authoring convenience.) tb.tokeniser.transition(TokeniserState.Rcdata); tb.markInsertionMode(); tb.framesetOk(false); tb.transition(Text); } else if (name.equals("xmp")) { if (tb.inButtonScope("p")) { tb.processEndTag("p"); } tb.reconstructFormattingElements(); tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("iframe")) { tb.framesetOk(false); handleRawtext(startTag, tb); } else if (name.equals("noembed")) { // also handle noscript if script enabled handleRawtext(startTag, tb); } else if (name.equals("select")) { tb.reconstructFormattingElements(); tb.insert(startTag); tb.framesetOk(false); HtmlTreeBuilderState state = tb.state(); if (state.equals(InTable) || state.equals(InCaption) || state.equals(InTableBody) || state.equals(InRow) || state.equals(InCell)) tb.transition(InSelectInTable); else tb.transition(InSelect); } else if (StringUtil.inSorted(name, Constants.InBodyStartOptions)) { if (tb.currentElement().nodeName().equals("option")) tb.processEndTag("option"); tb.reconstructFormattingElements(); tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartRuby)) { if (tb.inScope("ruby")) { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals("ruby")) { tb.error(this); tb.popStackToBefore("ruby"); // i.e. close up to but not include name } tb.insert(startTag); } } else if (name.equals("math")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "math" (i.e. foreign, mathml) tb.insert(startTag); } else if (name.equals("svg")) { tb.reconstructFormattingElements(); // todo: handle A start tag whose tag name is "svg" (xlink, svg) tb.insert(startTag); } else if (StringUtil.inSorted(name, Constants.InBodyStartDrop)) { tb.error(this); return false; } else { tb.reconstructFormattingElements(); tb.insert(startTag); } break; case EndTag: Token.EndTag endTag = t.asEndTag(); name = endTag.normalName(); if (StringUtil.inSorted(name, Constants.InBodyEndAdoptionFormatters)) { // Adoption Agency Algorithm. for (int i = 0; i < 8; i++) { Element formatEl = tb.getActiveFormattingElement(name); if (formatEl == null) return anyOtherEndTag(t, tb); else if (!tb.onStack(formatEl)) { tb.error(this); tb.removeFromActiveFormattingElements(formatEl); return true; } else if (!tb.inScope(formatEl.nodeName())) { tb.error(this); return false; } else if (tb.currentElement() != formatEl) tb.error(this); Element furthestBlock = null; Element commonAncestor = null; boolean seenFormattingElement = false; ArrayList<Element> stack = tb.getStack(); // the spec doesn't limit to < 64, but in degenerate cases (9000+ stack depth) this prevents // run-aways final int stackSize = stack.size(); for (int si = 0; si < stackSize && si < 64; si++) { Element el = stack.get(si); if (el == formatEl) { commonAncestor = stack.get(si - 1); seenFormattingElement = true; } else if (seenFormattingElement && tb.isSpecial(el)) { furthestBlock = el; break; } } if (furthestBlock == null) { tb.popStackToClose(formatEl.nodeName()); tb.removeFromActiveFormattingElements(formatEl); return true; } // todo: Let a bookmark note the position of the formatting element in the list of active formatting elements relative to the elements on either side of it in the list. // does that mean: int pos of format el in list? Element node = furthestBlock; Element lastNode = furthestBlock; for (int j = 0; j < 3; j++) { if (tb.onStack(node)) node = tb.aboveOnStack(node); if (!tb.isInActiveFormattingElements(node)) { // note no bookmark check tb.removeFromStack(node); continue; } else if (node == formatEl) break; Element replacement = new Element(Tag.valueOf(node.nodeName(), ParseSettings.preserveCase), tb.getBaseUri()); // case will follow the original node (so honours ParseSettings) tb.replaceActiveFormattingElement(node, replacement); tb.replaceOnStack(node, replacement); node = replacement; if (lastNode == furthestBlock) { // todo: move the aforementioned bookmark to be immediately after the new node in the list of active formatting elements. // not getting how this bookmark both straddles the element above, but is inbetween here... } if (lastNode.parent() != null) lastNode.remove(); node.appendChild(lastNode); lastNode = node; } if (StringUtil.inSorted(commonAncestor.nodeName(), Constants.InBodyEndTableFosters)) { if (lastNode.parent() != null) lastNode.remove(); tb.insertInFosterParent(lastNode); } else { if (lastNode.parent() != null) lastNode.remove(); commonAncestor.appendChild(lastNode); } Element adopter = new Element(formatEl.tag(), tb.getBaseUri()); adopter.attributes().addAll(formatEl.attributes()); Node[] childNodes = furthestBlock.childNodes().toArray(new Node[furthestBlock.childNodeSize()]); for (Node childNode : childNodes) { adopter.appendChild(childNode); // append will reparent. thus the clone to avoid concurrent mod. } furthestBlock.appendChild(adopter); tb.removeFromActiveFormattingElements(formatEl); // todo: insert the new element into the list of active formatting elements at the position of the aforementioned bookmark. tb.removeFromStack(formatEl); tb.insertOnStackAfter(furthestBlock, adopter); } } else if (StringUtil.inSorted(name, Constants.InBodyEndClosers)) { if (!tb.inScope(name)) { // nothing to close tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("span")) { // same as final fall through, but saves short circuit return anyOtherEndTag(t, tb); } else if (name.equals("li")) { if (!tb.inListItemScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (name.equals("body")) { if (!tb.inScope("body")) { tb.error(this); return false; } else { // todo: error if stack contains something not dd, dt, li, optgroup, option, p, rp, rt, tbody, td, tfoot, th, thead, tr, body, html tb.transition(AfterBody); } } else if (name.equals("html")) { boolean notIgnored = tb.processEndTag("body"); if (notIgnored) return tb.process(endTag); } else if (name.equals("form")) { Element currentForm = tb.getFormElement(); tb.setFormElement(null); if (currentForm == null || !tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); // remove currentForm from stack. will shift anything under up. tb.removeFromStack(currentForm); } } else if (name.equals("p")) { if (!tb.inButtonScope(name)) { tb.error(this); tb.processStartTag(name); // if no p to close, creates an empty <p></p> return tb.process(endTag); } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.DdDt)) { if (!tb.inScope(name)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); } } else if (StringUtil.inSorted(name, Constants.Headings)) { if (!tb.inScope(Constants.Headings)) { tb.error(this); return false; } else { tb.generateImpliedEndTags(name); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(Constants.Headings); } } else if (name.equals("sarcasm")) { // *sigh* return anyOtherEndTag(t, tb); } else if (StringUtil.inSorted(name, Constants.InBodyStartApplets)) { if (!tb.inScope("name")) { if (!tb.inScope(name)) { tb.error(this); return false; } tb.generateImpliedEndTags(); if (!tb.currentElement().nodeName().equals(name)) tb.error(this); tb.popStackToClose(name); tb.clearFormattingElementsToLastMarker(); } } else if (name.equals("br")) { tb.error(this); tb.processStartTag("br"); return false; } else { return anyOtherEndTag(t, tb); } break; case EOF: // todo: error if stack contains something not dd, dt, li, p, tbody, td, tfoot, th, thead, tr, body, html // stop parsing break; } return true; }
src/main/java/org/jsoup/parser/HtmlTreeBuilderState.java
Jsoup-77
private void popStackToClose(Token.EndTag endTag) { String elName = endTag.name(); Element firstFound = null; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (next.nodeName().equals(elName)) { firstFound = next; break; } } if (firstFound == null) return; // not found, skip for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); stack.remove(pos); if (next == firstFound) break; } } private void popStackToClose(Token.EndTag endTag) { String elName = endTag.normalName(); Element firstFound = null; for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); if (next.nodeName().equals(elName)) { firstFound = next; break; } } if (firstFound == null) return; // not found, skip for (int pos = stack.size() -1; pos >= 0; pos--) { Element next = stack.get(pos); stack.remove(pos); if (next == firstFound) break; } }
src/main/java/org/jsoup/parser/XmlTreeBuilder.java
Jsoup-80
void insert(Token.Comment commentToken) { Comment comment = new Comment(commentToken.getData()); Node insert = comment; if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml) // so we do a bit of a hack and parse the data as an element to pull the attributes out String data = comment.getData(); if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) { Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser()); Element el = doc.child(0); insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!")); insert.attributes().addAll(el.attributes()); } } insertNode(insert); } void insert(Token.Comment commentToken) { Comment comment = new Comment(commentToken.getData()); Node insert = comment; if (commentToken.bogus) { // xml declarations are emitted as bogus comments (which is right for html, but not xml) // so we do a bit of a hack and parse the data as an element to pull the attributes out String data = comment.getData(); if (data.length() > 1 && (data.startsWith("!") || data.startsWith("?"))) { Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri, Parser.xmlParser()); if (doc.childNodeSize() > 0) { Element el = doc.child(0); insert = new XmlDeclaration(settings.normalizeTag(el.tagName()), data.startsWith("!")); insert.attributes().addAll(el.attributes()); } // else, we couldn't parse it as a decl, so leave as a comment } } insertNode(insert); }
src/main/java/org/jsoup/parser/XmlTreeBuilder.java
Jsoup-82
static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException { if (input == null) // empty body return new Document(baseUri); input = ConstrainableInputStream.wrap(input, bufferSize, 0); Document doc = null; boolean fullyRead = false; // read the start of the stream and look for a BOM or meta charset input.mark(bufferSize); ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); // -1 because we read one more to see if completed. First read is < buffer size, so can't be invalid. fullyRead = input.read() == -1; input.reset(); // look for BOM - overrides any other header or input BomCharset bomCharset = detectCharsetFromBom(firstBytes); if (bomCharset != null) charsetName = bomCharset.charset; if (charsetName == null) { // determine from meta. safe first parse as UTF-8 String docData = Charset.forName(defaultCharset).decode(firstBytes).toString(); doc = parser.parseInput(docData, baseUri); // look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312"> Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]"); String foundCharset = null; // if not found, will keep utf-8 as best attempt for (Element meta : metaElements) { if (meta.hasAttr("http-equiv")) foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) foundCharset = meta.attr("charset"); if (foundCharset != null) break; } // look for <?xml encoding='ISO-8859-1'?> if (foundCharset == null && doc.childNodeSize() > 0) { Node first = doc.childNode(0); XmlDeclaration decl = null; if (first instanceof XmlDeclaration) decl = (XmlDeclaration) first; else if (first instanceof Comment) { Comment comment = (Comment) first; if (comment.isXmlDeclaration()) decl = comment.asXmlDeclaration(); } if (decl != null) { if (decl.name().equalsIgnoreCase("xml")) foundCharset = decl.attr("encoding"); } } foundCharset = validateCharset(foundCharset); if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { // need to re-decode. (case insensitive check here to match how validate works) foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; doc = null; } else if (!fullyRead) { doc = null; } } else { // specified by content type header (or by user on file load) Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); } if (doc == null) { if (charsetName == null) charsetName = defaultCharset; BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); if (bomCharset != null && bomCharset.offset) // creating the buffered reader ignores the input pos, so must skip here reader.skip(1); try { doc = parser.parseInput(reader, baseUri); } catch (UncheckedIOException e) { // io exception when parsing (not seen before because reading the stream as we go) throw e.ioException(); } Charset charset = Charset.forName(charsetName); doc.outputSettings().charset(charset); // some charsets can read but not encode; switch to an encodable charset and update the meta el } input.close(); return doc; } static Document parseInputStream(InputStream input, String charsetName, String baseUri, Parser parser) throws IOException { if (input == null) // empty body return new Document(baseUri); input = ConstrainableInputStream.wrap(input, bufferSize, 0); Document doc = null; boolean fullyRead = false; // read the start of the stream and look for a BOM or meta charset input.mark(bufferSize); ByteBuffer firstBytes = readToByteBuffer(input, firstReadBufferSize - 1); // -1 because we read one more to see if completed. First read is < buffer size, so can't be invalid. fullyRead = input.read() == -1; input.reset(); // look for BOM - overrides any other header or input BomCharset bomCharset = detectCharsetFromBom(firstBytes); if (bomCharset != null) charsetName = bomCharset.charset; if (charsetName == null) { // determine from meta. safe first parse as UTF-8 String docData = Charset.forName(defaultCharset).decode(firstBytes).toString(); doc = parser.parseInput(docData, baseUri); // look for <meta http-equiv="Content-Type" content="text/html;charset=gb2312"> or HTML5 <meta charset="gb2312"> Elements metaElements = doc.select("meta[http-equiv=content-type], meta[charset]"); String foundCharset = null; // if not found, will keep utf-8 as best attempt for (Element meta : metaElements) { if (meta.hasAttr("http-equiv")) foundCharset = getCharsetFromContentType(meta.attr("content")); if (foundCharset == null && meta.hasAttr("charset")) foundCharset = meta.attr("charset"); if (foundCharset != null) break; } // look for <?xml encoding='ISO-8859-1'?> if (foundCharset == null && doc.childNodeSize() > 0) { Node first = doc.childNode(0); XmlDeclaration decl = null; if (first instanceof XmlDeclaration) decl = (XmlDeclaration) first; else if (first instanceof Comment) { Comment comment = (Comment) first; if (comment.isXmlDeclaration()) decl = comment.asXmlDeclaration(); } if (decl != null) { if (decl.name().equalsIgnoreCase("xml")) foundCharset = decl.attr("encoding"); } } foundCharset = validateCharset(foundCharset); if (foundCharset != null && !foundCharset.equalsIgnoreCase(defaultCharset)) { // need to re-decode. (case insensitive check here to match how validate works) foundCharset = foundCharset.trim().replaceAll("[\"']", ""); charsetName = foundCharset; doc = null; } else if (!fullyRead) { doc = null; } } else { // specified by content type header (or by user on file load) Validate.notEmpty(charsetName, "Must set charset arg to character set of file to parse. Set to null to attempt to detect from HTML"); } if (doc == null) { if (charsetName == null) charsetName = defaultCharset; BufferedReader reader = new BufferedReader(new InputStreamReader(input, charsetName), bufferSize); if (bomCharset != null && bomCharset.offset) // creating the buffered reader ignores the input pos, so must skip here reader.skip(1); try { doc = parser.parseInput(reader, baseUri); } catch (UncheckedIOException e) { // io exception when parsing (not seen before because reading the stream as we go) throw e.ioException(); } Charset charset = Charset.forName(charsetName); doc.outputSettings().charset(charset); if (!charset.canEncode()) { // some charsets can read but not encode; switch to an encodable charset and update the meta el doc.charset(Charset.forName(defaultCharset)); } } input.close(); return doc; }
src/main/java/org/jsoup/helper/DataUtil.java
Jsoup-84
public void head(org.jsoup.nodes.Node source, int depth) { namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack if (source instanceof org.jsoup.nodes.Element) { org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source; String prefix = updateNamespaces(sourceEl); String namespace = namespacesStack.peek().get(prefix); String tagName = sourceEl.tagName(); Element el = doc.createElementNS(namespace, tagName); copyAttributes(sourceEl, el); if (dest == null) { // sets up the root doc.appendChild(el); } else { dest.appendChild(el); } dest = el; // descend } else if (source instanceof org.jsoup.nodes.TextNode) { org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source; Text text = doc.createTextNode(sourceText.getWholeText()); dest.appendChild(text); } else if (source instanceof org.jsoup.nodes.Comment) { org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source; Comment comment = doc.createComment(sourceComment.getData()); dest.appendChild(comment); } else if (source instanceof org.jsoup.nodes.DataNode) { org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source; Text node = doc.createTextNode(sourceData.getWholeData()); dest.appendChild(node); } else { // unhandled } } public void head(org.jsoup.nodes.Node source, int depth) { namespacesStack.push(new HashMap<>(namespacesStack.peek())); // inherit from above on the stack if (source instanceof org.jsoup.nodes.Element) { org.jsoup.nodes.Element sourceEl = (org.jsoup.nodes.Element) source; String prefix = updateNamespaces(sourceEl); String namespace = namespacesStack.peek().get(prefix); String tagName = sourceEl.tagName(); Element el = namespace == null && tagName.contains(":") ? doc.createElementNS("", tagName) : // doesn't have a real namespace defined doc.createElementNS(namespace, tagName); copyAttributes(sourceEl, el); if (dest == null) { // sets up the root doc.appendChild(el); } else { dest.appendChild(el); } dest = el; // descend } else if (source instanceof org.jsoup.nodes.TextNode) { org.jsoup.nodes.TextNode sourceText = (org.jsoup.nodes.TextNode) source; Text text = doc.createTextNode(sourceText.getWholeText()); dest.appendChild(text); } else if (source instanceof org.jsoup.nodes.Comment) { org.jsoup.nodes.Comment sourceComment = (org.jsoup.nodes.Comment) source; Comment comment = doc.createComment(sourceComment.getData()); dest.appendChild(comment); } else if (source instanceof org.jsoup.nodes.DataNode) { org.jsoup.nodes.DataNode sourceData = (org.jsoup.nodes.DataNode) source; Text node = doc.createTextNode(sourceData.getWholeData()); dest.appendChild(node); } else { // unhandled } }
src/main/java/org/jsoup/helper/W3CDom.java
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
Jsoup-86
public XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.childNodeSize() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; } public XmlDeclaration asXmlDeclaration() { String data = getData(); Document doc = Jsoup.parse("<" + data.substring(1, data.length() -1) + ">", baseUri(), Parser.xmlParser()); XmlDeclaration decl = null; if (doc.children().size() > 0) { Element el = doc.child(0); decl = new XmlDeclaration(NodeUtils.parser(doc).settings().normalizeTag(el.tagName()), data.startsWith("!")); decl.attributes().addAll(el.attributes()); } return decl; }
src/main/java/org/jsoup/nodes/Comment.java
Jsoup-88
public String getValue() { return val; } public String getValue() { return Attributes.checkNotNull(val); }
src/main/java/org/jsoup/nodes/Attribute.java
Jsoup-89
public String setValue(String val) { String oldVal = parent.get(this.key); if (parent != null) { int i = parent.indexOfKey(this.key); if (i != Attributes.NotFound) parent.vals[i] = val; } this.val = val; return Attributes.checkNotNull(oldVal); } public String setValue(String val) { String oldVal = this.val; if (parent != null) { oldVal = parent.get(this.key); // trust the container more int i = parent.indexOfKey(this.key); if (i != Attributes.NotFound) parent.vals[i] = val; } this.val = val; return Attributes.checkNotNull(oldVal); }
src/main/java/org/jsoup/nodes/Attribute.java
Jsoup-90
private static boolean looksLikeUtf8(byte[] input) { int i = 0; // BOM: if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int end; for (int j = input.length; i < j; ++i) { int o = input[i]; if ((o & 0x80) == 0) { continue; // ASCII } // UTF-8 leading: if ((o & 0xE0) == 0xC0) { end = i + 1; } else if ((o & 0xF0) == 0xE0) { end = i + 2; } else if ((o & 0xF8) == 0xF0) { end = i + 3; } else { return false; } while (i < end) { i++; o = input[i]; if ((o & 0xC0) != 0x80) { return false; } } } return true; } private static boolean looksLikeUtf8(byte[] input) { int i = 0; // BOM: if (input.length >= 3 && (input[0] & 0xFF) == 0xEF && (input[1] & 0xFF) == 0xBB & (input[2] & 0xFF) == 0xBF) { i = 3; } int end; for (int j = input.length; i < j; ++i) { int o = input[i]; if ((o & 0x80) == 0) { continue; // ASCII } // UTF-8 leading: if ((o & 0xE0) == 0xC0) { end = i + 1; } else if ((o & 0xF0) == 0xE0) { end = i + 2; } else if ((o & 0xF8) == 0xF0) { end = i + 3; } else { return false; } if (end >= input.length) return false; while (i < end) { i++; o = input[i]; if ((o & 0xC0) != 0x80) { return false; } } } return true; }
src/main/java/org/jsoup/helper/HttpConnection.java
Jsoup-93
public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<>(); // iterate the form control elements and accumulate their values for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable if (el.hasAttr("disabled")) continue; // skip disabled form inputs String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if ("select".equals(el.normalName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option: options) { data.add(HttpConnection.KeyVal.create(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) data.add(HttpConnection.KeyVal.create(name, option.val())); } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { // only add checkbox or radio if they have the checked attribute if (el.hasAttr("checked")) { final String val = el.val().length() > 0 ? el.val() : "on"; data.add(HttpConnection.KeyVal.create(name, val)); } } else { data.add(HttpConnection.KeyVal.create(name, el.val())); } } return data; } public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<>(); // iterate the form control elements and accumulate their values for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; // contents are form listable, superset of submitable if (el.hasAttr("disabled")) continue; // skip disabled form inputs String name = el.attr("name"); if (name.length() == 0) continue; String type = el.attr("type"); if (type.equalsIgnoreCase("button")) continue; // browsers don't submit these if ("select".equals(el.normalName())) { Elements options = el.select("option[selected]"); boolean set = false; for (Element option: options) { data.add(HttpConnection.KeyVal.create(name, option.val())); set = true; } if (!set) { Element option = el.select("option").first(); if (option != null) data.add(HttpConnection.KeyVal.create(name, option.val())); } } else if ("checkbox".equalsIgnoreCase(type) || "radio".equalsIgnoreCase(type)) { // only add checkbox or radio if they have the checked attribute if (el.hasAttr("checked")) { final String val = el.val().length() > 0 ? el.val() : "on"; data.add(HttpConnection.KeyVal.create(name, val)); } } else { data.add(HttpConnection.KeyVal.create(name, el.val())); } } return data; }
src/main/java/org/jsoup/nodes/FormElement.java
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
JxPath-12
public static boolean testNode(Node node, NodeTest test) { if (test == null) { return true; } if (test instanceof NodeNameTest) { if (node.getNodeType() != Node.ELEMENT_NODE) { return false; } NodeNameTest nodeNameTest = (NodeNameTest) test; QName testName = nodeNameTest.getNodeName(); String namespaceURI = nodeNameTest.getNamespaceURI(); boolean wildcard = nodeNameTest.isWildcard(); String testPrefix = testName.getPrefix(); if (wildcard && testPrefix == null) { return true; } if (wildcard || testName.getName() .equals(DOMNodePointer.getLocalName(node))) { String nodeNS = DOMNodePointer.getNamespaceURI(node); return equalStrings(namespaceURI, nodeNS); } return false; } if (test instanceof NodeTypeTest) { int nodeType = node.getNodeType(); switch (((NodeTypeTest) test).getNodeType()) { case Compiler.NODE_TYPE_NODE : return nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE; case Compiler.NODE_TYPE_TEXT : return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE; case Compiler.NODE_TYPE_COMMENT : return nodeType == Node.COMMENT_NODE; case Compiler.NODE_TYPE_PI : return nodeType == Node.PROCESSING_INSTRUCTION_NODE; } return false; } if (test instanceof ProcessingInstructionTest) { if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { String testPI = ((ProcessingInstructionTest) test).getTarget(); String nodePI = ((ProcessingInstruction) node).getTarget(); return testPI.equals(nodePI); } } return false; } public static boolean testNode(Node node, NodeTest test) { if (test == null) { return true; } if (test instanceof NodeNameTest) { if (node.getNodeType() != Node.ELEMENT_NODE) { return false; } NodeNameTest nodeNameTest = (NodeNameTest) test; QName testName = nodeNameTest.getNodeName(); String namespaceURI = nodeNameTest.getNamespaceURI(); boolean wildcard = nodeNameTest.isWildcard(); String testPrefix = testName.getPrefix(); if (wildcard && testPrefix == null) { return true; } if (wildcard || testName.getName() .equals(DOMNodePointer.getLocalName(node))) { String nodeNS = DOMNodePointer.getNamespaceURI(node); return equalStrings(namespaceURI, nodeNS) || nodeNS == null && equalStrings(testPrefix, getPrefix(node)); } return false; } if (test instanceof NodeTypeTest) { int nodeType = node.getNodeType(); switch (((NodeTypeTest) test).getNodeType()) { case Compiler.NODE_TYPE_NODE : return nodeType == Node.ELEMENT_NODE || nodeType == Node.DOCUMENT_NODE; case Compiler.NODE_TYPE_TEXT : return nodeType == Node.CDATA_SECTION_NODE || nodeType == Node.TEXT_NODE; case Compiler.NODE_TYPE_COMMENT : return nodeType == Node.COMMENT_NODE; case Compiler.NODE_TYPE_PI : return nodeType == Node.PROCESSING_INSTRUCTION_NODE; } return false; } if (test instanceof ProcessingInstructionTest) { if (node.getNodeType() == Node.PROCESSING_INSTRUCTION_NODE) { String testPI = ((ProcessingInstructionTest) test).getTarget(); String nodePI = ((ProcessingInstruction) node).getTarget(); return testPI.equals(nodePI); } } return false; }
src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java
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
JxPath-22
public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { return attr.getValue(); } } aNode = aNode.getParentNode(); } return null; } return uri; } public static String getNamespaceURI(Node node) { if (node instanceof Document) { node = ((Document) node).getDocumentElement(); } Element element = (Element) node; String uri = element.getNamespaceURI(); if (uri == null) { String prefix = getPrefix(node); String qname = prefix == null ? "xmlns" : "xmlns:" + prefix; Node aNode = node; while (aNode != null) { if (aNode.getNodeType() == Node.ELEMENT_NODE) { Attr attr = ((Element) aNode).getAttributeNode(qname); if (attr != null) { uri = attr.getValue(); break; } } aNode = aNode.getParentNode(); } } return "".equals(uri) ? null : uri; }
src/java/org/apache/commons/jxpath/ri/model/dom/DOMNodePointer.java
JxPath-5
private int compareNodePointers( NodePointer p1, int depth1, NodePointer p2, int depth2) { if (depth1 < depth2) { int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1); return r == 0 ? -1 : r; } if (depth1 > depth2) { int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2); return r == 0 ? 1 : r; } if (p1 == null && p2 == null) { return 0; } if (p1 != null && p1.equals(p2)) { return 0; } if (depth1 == 1) { throw new JXPathException( "Cannot compare pointers that do not belong to the same tree: '" + p1 + "' and '" + p2 + "'"); } int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1); if (r != 0) { return r; } return p1.parent.compareChildNodePointers(p1, p2); } private int compareNodePointers( NodePointer p1, int depth1, NodePointer p2, int depth2) { if (depth1 < depth2) { int r = compareNodePointers(p1, depth1, p2.parent, depth2 - 1); return r == 0 ? -1 : r; } if (depth1 > depth2) { int r = compareNodePointers(p1.parent, depth1 - 1, p2, depth2); return r == 0 ? 1 : r; } if (p1 == null && p2 == null) { return 0; } if (p1 != null && p1.equals(p2)) { return 0; } if (depth1 == 1) { return 0; } int r = compareNodePointers(p1.parent, depth1 - 1, p2.parent, depth2 - 1); if (r != 0) { return r; } return p1.parent.compareChildNodePointers(p1, p2); }
src/java/org/apache/commons/jxpath/ri/model/NodePointer.java
JxPath-6
protected boolean equal( EvalContext context, Expression left, Expression right) { Object l = left.compute(context); Object r = right.compute(context); // System.err.println("COMPARING: " + // (l == null ? "null" : l.getClass().getName()) + " " + // (r == null ? "null" : r.getClass().getName())); if (l instanceof InitialContext || l instanceof SelfContext) { l = ((EvalContext) l).getSingleNodePointer(); } if (r instanceof InitialContext || r instanceof SelfContext) { r = ((EvalContext) r).getSingleNodePointer(); } if (l instanceof Collection) { l = ((Collection) l).iterator(); } if (r instanceof Collection) { r = ((Collection) r).iterator(); } if ((l instanceof Iterator) && !(r instanceof Iterator)) { return contains((Iterator) l, r); } if (!(l instanceof Iterator) && (r instanceof Iterator)) { return contains((Iterator) r, l); } if (l instanceof Iterator && r instanceof Iterator) { return findMatch((Iterator) l, (Iterator) r); } return equal(l, r); } protected boolean equal( EvalContext context, Expression left, Expression right) { Object l = left.compute(context); Object r = right.compute(context); // System.err.println("COMPARING: " + // (l == null ? "null" : l.getClass().getName()) + " " + // (r == null ? "null" : r.getClass().getName())); if (l instanceof InitialContext) { ((EvalContext) l).reset(); } if (l instanceof SelfContext) { l = ((EvalContext) l).getSingleNodePointer(); } if (r instanceof InitialContext) { ((EvalContext) r).reset(); } if (r instanceof SelfContext) { r = ((EvalContext) r).getSingleNodePointer(); } if (l instanceof Collection) { l = ((Collection) l).iterator(); } if (r instanceof Collection) { r = ((Collection) r).iterator(); } if ((l instanceof Iterator) && !(r instanceof Iterator)) { return contains((Iterator) l, r); } if (!(l instanceof Iterator) && (r instanceof Iterator)) { return contains((Iterator) r, l); } if (l instanceof Iterator && r instanceof Iterator) { return findMatch((Iterator) l, (Iterator) r); } return equal(l, r); }
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationCompare.java
JxPath-8
private boolean compute(Object left, Object right) { left = reduce(left); right = reduce(right); if (left instanceof InitialContext) { ((InitialContext) left).reset(); } if (right instanceof InitialContext) { ((InitialContext) right).reset(); } if (left instanceof Iterator && right instanceof Iterator) { return findMatch((Iterator) left, (Iterator) right); } if (left instanceof Iterator) { return containsMatch((Iterator) left, right); } if (right instanceof Iterator) { return containsMatch((Iterator) right, left); } double ld = InfoSetUtil.doubleValue(left); double rd = InfoSetUtil.doubleValue(right); return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1); } private boolean compute(Object left, Object right) { left = reduce(left); right = reduce(right); if (left instanceof InitialContext) { ((InitialContext) left).reset(); } if (right instanceof InitialContext) { ((InitialContext) right).reset(); } if (left instanceof Iterator && right instanceof Iterator) { return findMatch((Iterator) left, (Iterator) right); } if (left instanceof Iterator) { return containsMatch((Iterator) left, right); } if (right instanceof Iterator) { return containsMatch((Iterator) right, left); } double ld = InfoSetUtil.doubleValue(left); if (Double.isNaN(ld)) { return false; } double rd = InfoSetUtil.doubleValue(right); if (Double.isNaN(rd)) { return false; } return evaluateCompare(ld == rd ? 0 : ld < rd ? -1 : 1); }
src/java/org/apache/commons/jxpath/ri/compiler/CoreOperationRelationalExpression.java
Lang-1
public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } // Need to deal with all possible hex prefixes here final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { // we have a hex number final int hexDigits = str.length() - pfxLen; if (hexDigits > 16) { // too many for Long return createBigInteger(str); } if (hexDigits > 8) { // too many for an int return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) // and the parsing which will detect if e or E appear in a number due to using the wrong offset int numDecimals = 0; // Check required precision (LANG-693) if (decPos > -1) { // there is a decimal point if (expPos > -1) { // there is an exponent if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers. } else { if (expPos > -1) { if (expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { // no decimal point and no exponent //Must be an Integer, Long, Biginteger try { return createInteger(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } //Must be a Float, Double, BigDecimal final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { if(numDecimals <= 7){// If number has 7 or fewer digits past the decimal point then make it a float final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { if(numDecimals <= 16){// If number has between 8 and 16 digits past the decimal point then make it a double final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); } public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } // Need to deal with all possible hex prefixes here final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { // we have a hex number char firstSigDigit = 0; // strip leading zeroes for(int i = pfxLen; i < str.length(); i++) { firstSigDigit = str.charAt(i); if (firstSigDigit == '0') { // count leading zeroes pfxLen++; } else { break; } } final int hexDigits = str.length() - pfxLen; if (hexDigits > 16 || (hexDigits == 16 && firstSigDigit > '7')) { // too many for Long return createBigInteger(str); } if (hexDigits > 8 || (hexDigits == 8 && firstSigDigit > '7')) { // too many for an int return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) // and the parsing which will detect if e or E appear in a number due to using the wrong offset int numDecimals = 0; // Check required precision (LANG-693) if (decPos > -1) { // there is a decimal point if (expPos > -1) { // there is an exponent if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers. } else { if (expPos > -1) { if (expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { // no decimal point and no exponent //Must be an Integer, Long, Biginteger try { return createInteger(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } //Must be a Float, Double, BigDecimal final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { if(numDecimals <= 7){// If number has 7 or fewer digits past the decimal point then make it a float final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { if(numDecimals <= 16){// If number has between 8 and 16 digits past the decimal point then make it a double final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); }
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
Lang-10
private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) { boolean wasWhite= false; for(int i= 0; i<value.length(); ++i) { char c= value.charAt(i); if(Character.isWhitespace(c)) { if(!wasWhite) { wasWhite= true; regex.append("\\s*+"); } continue; } wasWhite= false; switch(c) { case '\'': if(unquote) { if(++i==value.length()) { return regex; } c= value.charAt(i); } break; case '?': case '[': case ']': case '(': case ')': case '{': case '}': case '\\': case '|': case '*': case '+': case '^': case '$': case '.': regex.append('\\'); } regex.append(c); } return regex; } private static StringBuilder escapeRegex(StringBuilder regex, String value, boolean unquote) { for(int i= 0; i<value.length(); ++i) { char c= value.charAt(i); switch(c) { case '\'': if(unquote) { if(++i==value.length()) { return regex; } c= value.charAt(i); } break; case '?': case '[': case ']': case '(': case ')': case '{': case '}': case '\\': case '|': case '*': case '+': case '^': case '$': case '.': regex.append('\\'); } regex.append(c); } return regex; }
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
Lang-11
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); } public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } } else { if (end <= start) { throw new IllegalArgumentException("Parameter end (" + end + ") must be greater than start (" + start + ")"); } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); }
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
Lang-12
public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (start == 0 && end == 0) { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); } public static String random(int count, int start, int end, boolean letters, boolean numbers, char[] chars, Random random) { if (count == 0) { return ""; } else if (count < 0) { throw new IllegalArgumentException("Requested random string length " + count + " is less than 0."); } if (chars != null && chars.length == 0) { throw new IllegalArgumentException("The chars array must not be empty"); } if (start == 0 && end == 0) { if (chars != null) { end = chars.length; } else { if (!letters && !numbers) { end = Integer.MAX_VALUE; } else { end = 'z' + 1; start = ' '; } } } char[] buffer = new char[count]; int gap = end - start; while (count-- != 0) { char ch; if (chars == null) { ch = (char) (random.nextInt(gap) + start); } else { ch = chars[random.nextInt(gap) + start]; } if (letters && Character.isLetter(ch) || numbers && Character.isDigit(ch) || !letters && !numbers) { if(ch >= 56320 && ch <= 57343) { if(count == 0) { count++; } else { // low surrogate, insert high surrogate after putting it in buffer[count] = ch; count--; buffer[count] = (char) (55296 + random.nextInt(128)); } } else if(ch >= 55296 && ch <= 56191) { if(count == 0) { count++; } else { // high surrogate, insert low surrogate before putting it in buffer[count] = (char) (56320 + random.nextInt(128)); count--; buffer[count] = ch; } } else if(ch >= 56192 && ch <= 56319) { // private high surrogate, no effing clue, so skip it count++; } else { buffer[count] = ch; } } else { count++; } } return new String(buffer); }
src/main/java/org/apache/commons/lang3/RandomStringUtils.java
Lang-14
public static boolean equals(CharSequence cs1, CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } return cs1.equals(cs2); } public static boolean equals(CharSequence cs1, CharSequence cs2) { if (cs1 == cs2) { return true; } if (cs1 == null || cs2 == null) { return false; } if (cs1 instanceof String && cs2 instanceof String) { return cs1.equals(cs2); } return CharSequenceUtils.regionMatches(cs1, false, 0, cs2, 0, Math.max(cs1.length(), cs2.length())); }
src/main/java/org/apache/commons/lang3/StringUtils.java
Lang-16
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); } } } public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x") || str.startsWith("0X") || str.startsWith("-0X")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); } } }
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
Lang-17
public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = Character.codePointCount(input, 0, input.length()); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); } else { // // contract with translators is that they have to understand codepoints // // and they just took care of a surrogate pair for (int pt = 0; pt < consumed; pt++) { if (pos < len - 2) { pos += Character.charCount(Character.codePointAt(input, pos)); } else { pos++; } } pos--; } pos++; } } public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = input.length(); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); pos+= c.length; continue; } // // contract with translators is that they have to understand codepoints // // and they just took care of a surrogate pair for (int pt = 0; pt < consumed; pt++) { pos += Character.charCount(Character.codePointAt(input, pos)); } } }
src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java
Lang-18
protected List<Rule> parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List<Rule> rules = new ArrayList<Rule>(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': // era designator (text) rule = new TextField(Calendar.ERA, ERAs); break; case 'y': // year (number) if (tokenLen >= 4) { rule = selectNumberRule(Calendar.YEAR, tokenLen); } else { rule = TwoDigitYearField.INSTANCE; } break; case 'M': // month in year (text and number) if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': // day in month (number) rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': // hour in am/pm (number, 1..12) rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': // hour in day (number, 0..23) rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': // minute in hour (number) rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': // second in minute (number) rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': // millisecond (number) rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': // day in week (text) rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': // day in year (number) rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': // day of week in month (number) rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': // week in year (number) rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': // week in month (number) rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': // am/pm marker (text) rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': // hour in day (1..24) rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': // hour in am/pm (0..11) rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': // time zone (text) if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); } break; case 'Z': // time zone (value) if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': // literal text String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; } protected List<Rule> parsePattern() { DateFormatSymbols symbols = new DateFormatSymbols(mLocale); List<Rule> rules = new ArrayList<Rule>(); String[] ERAs = symbols.getEras(); String[] months = symbols.getMonths(); String[] shortMonths = symbols.getShortMonths(); String[] weekdays = symbols.getWeekdays(); String[] shortWeekdays = symbols.getShortWeekdays(); String[] AmPmStrings = symbols.getAmPmStrings(); int length = mPattern.length(); int[] indexRef = new int[1]; for (int i = 0; i < length; i++) { indexRef[0] = i; String token = parseToken(mPattern, indexRef); i = indexRef[0]; int tokenLen = token.length(); if (tokenLen == 0) { break; } Rule rule; char c = token.charAt(0); switch (c) { case 'G': // era designator (text) rule = new TextField(Calendar.ERA, ERAs); break; case 'y': // year (number) if (tokenLen == 2) { rule = TwoDigitYearField.INSTANCE; } else { rule = selectNumberRule(Calendar.YEAR, tokenLen < 4 ? 4 : tokenLen); } break; case 'M': // month in year (text and number) if (tokenLen >= 4) { rule = new TextField(Calendar.MONTH, months); } else if (tokenLen == 3) { rule = new TextField(Calendar.MONTH, shortMonths); } else if (tokenLen == 2) { rule = TwoDigitMonthField.INSTANCE; } else { rule = UnpaddedMonthField.INSTANCE; } break; case 'd': // day in month (number) rule = selectNumberRule(Calendar.DAY_OF_MONTH, tokenLen); break; case 'h': // hour in am/pm (number, 1..12) rule = new TwelveHourField(selectNumberRule(Calendar.HOUR, tokenLen)); break; case 'H': // hour in day (number, 0..23) rule = selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen); break; case 'm': // minute in hour (number) rule = selectNumberRule(Calendar.MINUTE, tokenLen); break; case 's': // second in minute (number) rule = selectNumberRule(Calendar.SECOND, tokenLen); break; case 'S': // millisecond (number) rule = selectNumberRule(Calendar.MILLISECOND, tokenLen); break; case 'E': // day in week (text) rule = new TextField(Calendar.DAY_OF_WEEK, tokenLen < 4 ? shortWeekdays : weekdays); break; case 'D': // day in year (number) rule = selectNumberRule(Calendar.DAY_OF_YEAR, tokenLen); break; case 'F': // day of week in month (number) rule = selectNumberRule(Calendar.DAY_OF_WEEK_IN_MONTH, tokenLen); break; case 'w': // week in year (number) rule = selectNumberRule(Calendar.WEEK_OF_YEAR, tokenLen); break; case 'W': // week in month (number) rule = selectNumberRule(Calendar.WEEK_OF_MONTH, tokenLen); break; case 'a': // am/pm marker (text) rule = new TextField(Calendar.AM_PM, AmPmStrings); break; case 'k': // hour in day (1..24) rule = new TwentyFourHourField(selectNumberRule(Calendar.HOUR_OF_DAY, tokenLen)); break; case 'K': // hour in am/pm (0..11) rule = selectNumberRule(Calendar.HOUR, tokenLen); break; case 'z': // time zone (text) if (tokenLen >= 4) { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.LONG); } else { rule = new TimeZoneNameRule(mTimeZone, mLocale, TimeZone.SHORT); } break; case 'Z': // time zone (value) if (tokenLen == 1) { rule = TimeZoneNumberRule.INSTANCE_NO_COLON; } else { rule = TimeZoneNumberRule.INSTANCE_COLON; } break; case '\'': // literal text String sub = token.substring(1); if (sub.length() == 1) { rule = new CharacterLiteral(sub.charAt(0)); } else { rule = new StringLiteral(sub); } break; default: throw new IllegalArgumentException("Illegal pattern component: " + token); } rules.add(rule); } return rules; }
src/main/java/org/apache/commons/lang3/time/FastDateFormat.java
Lang-19
public int translate(CharSequence input, int index, Writer out) throws IOException { int seqEnd = input.length(); // Uses -2 to ensure there is something after the &# if(input.charAt(index) == '&' && index < seqEnd - 1 && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; // Check there's more than just an x after the &# } int end = start; // Note that this supports character codes without a ; on the end while(input.charAt(end) != ';') { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { System.err.println("FAIL: " + input.subSequence(start, end) + "[" + start +"]["+ end +"]"); return 0; } if(entityValue > 0xFFFF) { char[] chrs = Character.toChars(entityValue); out.write(chrs[0]); out.write(chrs[1]); } else { out.write(entityValue); } return 2 + (end - start) + (isHex ? 1 : 0) + 1; } return 0; } public int translate(CharSequence input, int index, Writer out) throws IOException { int seqEnd = input.length(); // Uses -2 to ensure there is something after the &# if(input.charAt(index) == '&' && index < seqEnd - 2 && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; // Check there's more than just an x after the &# if(start == seqEnd) { return 0; } } int end = start; // Note that this supports character codes without a ; on the end while(end < seqEnd && ( (input.charAt(end) >= '0' && input.charAt(end) <= '9') || (input.charAt(end) >= 'a' && input.charAt(end) <= 'f') || (input.charAt(end) >= 'A' && input.charAt(end) <= 'F') ) ) { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { System.err.println("FAIL: " + input.subSequence(start, end) + "[" + start +"]["+ end +"]"); return 0; } if(entityValue > 0xFFFF) { char[] chrs = Character.toChars(entityValue); out.write(chrs[0]); out.write(chrs[1]); } else { out.write(entityValue); } boolean semiNext = (end != seqEnd) && (input.charAt(end) == ';'); return 2 + (end - start) + (isHex ? 1 : 0) + (semiNext ? 1 : 0); } return 0; }
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java
Lang-21
public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR) == cal2.get(Calendar.HOUR) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass()); } public static boolean isSameLocalTime(Calendar cal1, Calendar cal2) { if (cal1 == null || cal2 == null) { throw new IllegalArgumentException("The date must not be null"); } return (cal1.get(Calendar.MILLISECOND) == cal2.get(Calendar.MILLISECOND) && cal1.get(Calendar.SECOND) == cal2.get(Calendar.SECOND) && cal1.get(Calendar.MINUTE) == cal2.get(Calendar.MINUTE) && cal1.get(Calendar.HOUR_OF_DAY) == cal2.get(Calendar.HOUR_OF_DAY) && cal1.get(Calendar.DAY_OF_YEAR) == cal2.get(Calendar.DAY_OF_YEAR) && cal1.get(Calendar.YEAR) == cal2.get(Calendar.YEAR) && cal1.get(Calendar.ERA) == cal2.get(Calendar.ERA) && cal1.getClass() == cal2.getClass()); }
src/main/java/org/apache/commons/lang3/time/DateUtils.java
Lang-22
private static int greatestCommonDivisor(int u, int v) { // From Commons Math: //if either operand is abs 1, return 1: if (Math.abs(u) <= 1 || Math.abs(v) <= 1) { return 1; } // keep u and v negative, as negative integers range down to // -2^31, while positive numbers can only be as large as 2^31-1 // (i.e. we can't necessarily negate a negative number without // overflow) if (u>0) { u=-u; } // make u negative if (v>0) { v=-v; } // make v negative // B1. [Find power of 2] int k=0; while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even... u/=2; v/=2; k++; // cast out twos. } if (k==31) { throw new ArithmeticException("overflow: gcd is 2^31"); } // B2. Initialize: u and v have been divided by 2^k and at least // one is odd. int t = ((u&1)==1) ? v : -(u/2)/*B3*/; // t negative: u was odd, v may be even (t replaces v) // t positive: u was even, v is odd (t replaces u) do { /* assert u<0 && v<0; */ // B4/B3: cast out twos from t. while ((t&1)==0) { // while t is even.. t/=2; // cast out twos } // B5 [reset max(u,v)] if (t>0) { u = -t; } else { v = t; } // B6/B3. at this point both u and v should be odd. t = (v - u)/2; // |u| larger: t positive (replace u) // |v| larger: t negative (replace v) } while (t!=0); return -u*(1<<k); // gcd is u*2^k } private static int greatestCommonDivisor(int u, int v) { // From Commons Math: if ((u == 0) || (v == 0)) { if ((u == Integer.MIN_VALUE) || (v == Integer.MIN_VALUE)) { throw new ArithmeticException("overflow: gcd is 2^31"); } return Math.abs(u) + Math.abs(v); } //if either operand is abs 1, return 1: if (Math.abs(u) == 1 || Math.abs(v) == 1) { return 1; } // keep u and v negative, as negative integers range down to // -2^31, while positive numbers can only be as large as 2^31-1 // (i.e. we can't necessarily negate a negative number without // overflow) if (u>0) { u=-u; } // make u negative if (v>0) { v=-v; } // make v negative // B1. [Find power of 2] int k=0; while ((u&1)==0 && (v&1)==0 && k<31) { // while u and v are both even... u/=2; v/=2; k++; // cast out twos. } if (k==31) { throw new ArithmeticException("overflow: gcd is 2^31"); } // B2. Initialize: u and v have been divided by 2^k and at least // one is odd. int t = ((u&1)==1) ? v : -(u/2)/*B3*/; // t negative: u was odd, v may be even (t replaces v) // t positive: u was even, v is odd (t replaces u) do { /* assert u<0 && v<0; */ // B4/B3: cast out twos from t. while ((t&1)==0) { // while t is even.. t/=2; // cast out twos } // B5 [reset max(u,v)] if (t>0) { u = -t; } else { v = t; } // B6/B3. at this point both u and v should be odd. t = (v - u)/2; // |u| larger: t positive (replace u) // |v| larger: t negative (replace v) } while (t!=0); return -u*(1<<k); // gcd is u*2^k }
src/main/java/org/apache/commons/lang3/math/Fraction.java
Lang-24
public static boolean isNumber(String str) { if (StringUtils.isEmpty(str)) { return false; } char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; // deal with any possible sign up front int start = (chars[0] == '-') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; // str == "0x" } // checking hex (it can't be anything else) for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; // don't want to loop to the last char, check it afterwords // for type qualifiers int i = start; // loop to the next to last char or to the last char if we need another digit to // make a valid number (e.g. chars[0..5] = "1234E") while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { // we've already taken care of hex. if (hasExp) { // two E's return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; // we need a digit after the E } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { // no type qualifier, OK return true; } if (chars[i] == 'e' || chars[i] == 'E') { // can't have an E at the last byte return false; } if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } // single trailing decimal point after non-exponent is ok return foundDigit; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent or decimal point return foundDigit && !hasExp; } // last character is illegal return false; } // allowSigns is true iff the val ends in 'E' // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass return !allowSigns && foundDigit; } public static boolean isNumber(String str) { if (StringUtils.isEmpty(str)) { return false; } char[] chars = str.toCharArray(); int sz = chars.length; boolean hasExp = false; boolean hasDecPoint = false; boolean allowSigns = false; boolean foundDigit = false; // deal with any possible sign up front int start = (chars[0] == '-') ? 1 : 0; if (sz > start + 1) { if (chars[start] == '0' && chars[start + 1] == 'x') { int i = start + 2; if (i == sz) { return false; // str == "0x" } // checking hex (it can't be anything else) for (; i < chars.length; i++) { if ((chars[i] < '0' || chars[i] > '9') && (chars[i] < 'a' || chars[i] > 'f') && (chars[i] < 'A' || chars[i] > 'F')) { return false; } } return true; } } sz--; // don't want to loop to the last char, check it afterwords // for type qualifiers int i = start; // loop to the next to last char or to the last char if we need another digit to // make a valid number (e.g. chars[0..5] = "1234E") while (i < sz || (i < sz + 1 && allowSigns && !foundDigit)) { if (chars[i] >= '0' && chars[i] <= '9') { foundDigit = true; allowSigns = false; } else if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } hasDecPoint = true; } else if (chars[i] == 'e' || chars[i] == 'E') { // we've already taken care of hex. if (hasExp) { // two E's return false; } if (!foundDigit) { return false; } hasExp = true; allowSigns = true; } else if (chars[i] == '+' || chars[i] == '-') { if (!allowSigns) { return false; } allowSigns = false; foundDigit = false; // we need a digit after the E } else { return false; } i++; } if (i < chars.length) { if (chars[i] >= '0' && chars[i] <= '9') { // no type qualifier, OK return true; } if (chars[i] == 'e' || chars[i] == 'E') { // can't have an E at the last byte return false; } if (chars[i] == '.') { if (hasDecPoint || hasExp) { // two decimal points or dec in exponent return false; } // single trailing decimal point after non-exponent is ok return foundDigit; } if (!allowSigns && (chars[i] == 'd' || chars[i] == 'D' || chars[i] == 'f' || chars[i] == 'F')) { return foundDigit; } if (chars[i] == 'l' || chars[i] == 'L') { // not allowing L with an exponent or decimal point return foundDigit && !hasExp && !hasDecPoint; } // last character is illegal return false; } // allowSigns is true iff the val ends in 'E' // found digit it to make sure weird stuff like '.' and '1E-' doesn't pass return !allowSigns && foundDigit; }
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
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
Lang-27
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } } public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos || expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { if (expPos > str.length()) { throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } }
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
Lang-28
public int translate(CharSequence input, int index, Writer out) throws IOException { // TODO: Protect from ArrayIndexOutOfBounds if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; } int end = start; while(input.charAt(end) != ';') { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { return 0; } out.write(entityValue); return 2 + (end - start) + (isHex ? 1 : 0) + 1; } return 0; } public int translate(CharSequence input, int index, Writer out) throws IOException { // TODO: Protect from ArrayIndexOutOfBounds if(input.charAt(index) == '&' && input.charAt(index + 1) == '#') { int start = index + 2; boolean isHex = false; char firstChar = input.charAt(start); if(firstChar == 'x' || firstChar == 'X') { start++; isHex = true; } int end = start; while(input.charAt(end) != ';') { end++; } int entityValue; try { if(isHex) { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 16); } else { entityValue = Integer.parseInt(input.subSequence(start, end).toString(), 10); } } catch(NumberFormatException nfe) { return 0; } if(entityValue > 0xFFFF) { char[] chrs = Character.toChars(entityValue); out.write(chrs[0]); out.write(chrs[1]); } else { out.write(entityValue); } return 2 + (end - start) + (isHex ? 1 : 0) + 1; } return 0; }
src/main/java/org/apache/commons/lang3/text/translate/NumericEntityUnescaper.java
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
Lang-3
public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } // Need to deal with all possible hex prefixes here final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { // we have a hex number final int hexDigits = str.length() - pfxLen; if (hexDigits > 16) { // too many for Long return createBigInteger(str); } if (hexDigits > 8) { // too many for an int return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) // and the parsing which will detect if e or E appear in a number due to using the wrong offset int numDecimals = 0; // Check required precision (LANG-693) if (decPos > -1) { // there is a decimal point if (expPos > -1) { // there is an exponent if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers. } else { if (expPos > -1) { if (expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { // no decimal point and no exponent //Must be an Integer, Long, Biginteger try { return createInteger(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } //Must be a Float, Double, BigDecimal final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); } public static Number createNumber(final String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } // Need to deal with all possible hex prefixes here final String[] hex_prefixes = {"0x", "0X", "-0x", "-0X", "#", "-#"}; int pfxLen = 0; for(final String pfx : hex_prefixes) { if (str.startsWith(pfx)) { pfxLen += pfx.length(); break; } } if (pfxLen > 0) { // we have a hex number final int hexDigits = str.length() - pfxLen; if (hexDigits > 16) { // too many for Long return createBigInteger(str); } if (hexDigits > 8) { // too many for an int return createLong(str); } return createInteger(str); } final char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; final int decPos = str.indexOf('.'); final int expPos = str.indexOf('e') + str.indexOf('E') + 1; // assumes both not present // if both e and E are present, this is caught by the checks on expPos (which prevent IOOBE) // and the parsing which will detect if e or E appear in a number due to using the wrong offset int numDecimals = 0; // Check required precision (LANG-693) if (decPos > -1) { // there is a decimal point if (expPos > -1) { // there is an exponent if (expPos < decPos || expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); numDecimals = dec.length(); // gets number of digits past the decimal to ensure no loss of precision for floating point numbers. } else { if (expPos > -1) { if (expPos > str.length()) { // prevents double exponent causing IOOBE throw new NumberFormatException(str + " is not a valid number."); } mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar) && lastChar != '.') { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. final String numeric = str.substring(0, str.length() - 1); final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (final NumberFormatException nfe) { // NOPMD // Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { final Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ case 'd' : case 'D' : try { final Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createBigDecimal(numeric); } catch (final NumberFormatException e) { // NOPMD // ignore the bad number } //$FALL-THROUGH$ default : throw new NumberFormatException(str + " is not a valid number."); } } //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { // no decimal point and no exponent //Must be an Integer, Long, Biginteger try { return createInteger(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { return createLong(str); } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigInteger(str); } //Must be a Float, Double, BigDecimal final boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { if(numDecimals <= 7){// If number has 7 or fewer digits past the decimal point then make it a float final Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } try { if(numDecimals <= 16){// If number has between 8 and 16 digits past the decimal point then make it a double final Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } } catch (final NumberFormatException nfe) { // NOPMD // ignore the bad number } return createBigDecimal(str); }
src/main/java/org/apache/commons/lang3/math/NumberUtils.java
Lang-31
public static boolean containsAny(CharSequence cs, char[] searchChars) { if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = cs.length(); int searchLength = searchChars.length; for (int i = 0; i < csLength; i++) { char ch = cs.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { // ch is a supplementary character // ch is in the Basic Multilingual Plane return true; } } } return false; } public static boolean containsAny(CharSequence cs, char[] searchChars) { if (isEmpty(cs) || ArrayUtils.isEmpty(searchChars)) { return false; } int csLength = cs.length(); int searchLength = searchChars.length; int csLastIndex = csLength - 1; int searchLastIndex = searchLength - 1; for (int i = 0; i < csLength; i++) { char ch = cs.charAt(i); for (int j = 0; j < searchLength; j++) { if (searchChars[j] == ch) { if (i < csLastIndex && j < searchLastIndex && ch >= Character.MIN_HIGH_SURROGATE && ch <= Character.MAX_HIGH_SURROGATE) { // ch is a supplementary character if (searchChars[j + 1] == cs.charAt(i + 1)) { return true; } } else { // ch is in the Basic Multilingual Plane return true; } } } } return false; }
src/main/java/org/apache/commons/lang3/StringUtils.java
Lang-33
public static Class<?>[] toClass(Object[] array) { if (array == null) { return null; } else if (array.length == 0) { return ArrayUtils.EMPTY_CLASS_ARRAY; } Class<?>[] classes = new Class[array.length]; for (int i = 0; i < array.length; i++) { classes[i] = array[i].getClass(); } return classes; } public static Class<?>[] toClass(Object[] array) { if (array == null) { return null; } else if (array.length == 0) { return ArrayUtils.EMPTY_CLASS_ARRAY; } Class<?>[] classes = new Class[array.length]; for (int i = 0; i < array.length; i++) { classes[i] = array[i] == null ? null : array[i].getClass(); } return classes; }
src/main/java/org/apache/commons/lang3/ClassUtils.java
Lang-37
public static <T> T[] addAll(T[] array1, T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); // Check if problem is incompatible types return joinedArray; } public static <T> T[] addAll(T[] array1, T... array2) { if (array1 == null) { return clone(array2); } else if (array2 == null) { return clone(array1); } final Class<?> type1 = array1.getClass().getComponentType(); T[] joinedArray = (T[]) Array.newInstance(type1, array1.length + array2.length); System.arraycopy(array1, 0, joinedArray, 0, array1.length); try { System.arraycopy(array2, 0, joinedArray, array1.length, array2.length); } catch (ArrayStoreException ase) { // Check if problem is incompatible types final Class<?> type2 = array2.getClass().getComponentType(); if (!type1.isAssignableFrom(type2)){ throw new IllegalArgumentException("Cannot store "+type2.getName()+" in an array of "+type1.getName()); } throw ase; // No, so rethrow original } return joinedArray; }
src/java/org/apache/commons/lang3/ArrayUtils.java
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
Lang-39
private static String replaceEach(String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { // mchyzer Performance note: This creates very few new objects (one major goal) // let me know if there are performance requests, we can create a harness to measure if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) { return text; } // if recursing, this shouldnt be less than 0 if (timeToLive < 0) { throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text); } int searchLength = searchList.length; int replacementLength = replacementList.length; // make sure lengths are ok, these need to be equal if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } // keep track of which still have matches boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; // index on index that the match was found int textIndex = -1; int replaceIndex = -1; int tempIndex = -1; // index of replace array that will replace the search string found // NOTE: logic duplicated below START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic mostly below END // no search strings found, we are done if (textIndex == -1) { return text; } int start = 0; // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit int increase = 0; // count the replacement text elements that are larger than their corresponding text being replaced for (int i = 0; i < searchList.length; i++) { int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; // assume 3 matches } } // have upper-bound at 20% increase, then let Java take over increase = Math.min(increase, text.length() / 5); StringBuilder buf = new StringBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; tempIndex = -1; // find the next earliest match // NOTE: logic mostly duplicated above START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic duplicated above END } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } String result = buf.toString(); if (!repeat) { return result; } return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); } private static String replaceEach(String text, String[] searchList, String[] replacementList, boolean repeat, int timeToLive) { // mchyzer Performance note: This creates very few new objects (one major goal) // let me know if there are performance requests, we can create a harness to measure if (text == null || text.length() == 0 || searchList == null || searchList.length == 0 || replacementList == null || replacementList.length == 0) { return text; } // if recursing, this shouldnt be less than 0 if (timeToLive < 0) { throw new IllegalStateException("TimeToLive of " + timeToLive + " is less than 0: " + text); } int searchLength = searchList.length; int replacementLength = replacementList.length; // make sure lengths are ok, these need to be equal if (searchLength != replacementLength) { throw new IllegalArgumentException("Search and Replace array lengths don't match: " + searchLength + " vs " + replacementLength); } // keep track of which still have matches boolean[] noMoreMatchesForReplIndex = new boolean[searchLength]; // index on index that the match was found int textIndex = -1; int replaceIndex = -1; int tempIndex = -1; // index of replace array that will replace the search string found // NOTE: logic duplicated below START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i]); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic mostly below END // no search strings found, we are done if (textIndex == -1) { return text; } int start = 0; // get a good guess on the size of the result buffer so it doesnt have to double if it goes over a bit int increase = 0; // count the replacement text elements that are larger than their corresponding text being replaced for (int i = 0; i < searchList.length; i++) { if (searchList[i] == null || replacementList[i] == null) { continue; } int greater = replacementList[i].length() - searchList[i].length(); if (greater > 0) { increase += 3 * greater; // assume 3 matches } } // have upper-bound at 20% increase, then let Java take over increase = Math.min(increase, text.length() / 5); StringBuilder buf = new StringBuilder(text.length() + increase); while (textIndex != -1) { for (int i = start; i < textIndex; i++) { buf.append(text.charAt(i)); } buf.append(replacementList[replaceIndex]); start = textIndex + searchList[replaceIndex].length(); textIndex = -1; replaceIndex = -1; tempIndex = -1; // find the next earliest match // NOTE: logic mostly duplicated above START for (int i = 0; i < searchLength; i++) { if (noMoreMatchesForReplIndex[i] || searchList[i] == null || searchList[i].length() == 0 || replacementList[i] == null) { continue; } tempIndex = text.indexOf(searchList[i], start); // see if we need to keep searching for this if (tempIndex == -1) { noMoreMatchesForReplIndex[i] = true; } else { if (textIndex == -1 || tempIndex < textIndex) { textIndex = tempIndex; replaceIndex = i; } } } // NOTE: logic duplicated above END } int textLength = text.length(); for (int i = start; i < textLength; i++) { buf.append(text.charAt(i)); } String result = buf.toString(); if (!repeat) { return result; } return replaceEach(result, searchList, replacementList, repeat, timeToLive - 1); }
src/java/org/apache/commons/lang3/StringUtils.java
Lang-40
public static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } return contains(str.toUpperCase(), searchStr.toUpperCase()); } public static boolean containsIgnoreCase(String str, String searchStr) { if (str == null || searchStr == null) { return false; } int len = searchStr.length(); int max = str.length() - len; for (int i = 0; i <= max; i++) { if (str.regionMatches(true, i, searchStr, 0, len)) { return true; } } return false; }
src/java/org/apache/commons/lang/StringUtils.java
Lang-42
public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { char c = str.charAt(i); String entityName = this.entityName(c); if (entityName == null) { if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } } public void escape(Writer writer, String str) throws IOException { int len = str.length(); for (int i = 0; i < len; i++) { int c = Character.codePointAt(str, i); String entityName = this.entityName(c); if (entityName == null) { if (c >= 0x010000 && i < len - 1) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); i++; } else if (c > 0x7F) { writer.write("&#"); writer.write(Integer.toString(c, 10)); writer.write(';'); } else { writer.write(c); } } else { writer.write('&'); writer.write(entityName); writer.write(';'); } } }
src/java/org/apache/commons/lang/Entities.java
Lang-43
private StringBuffer appendQuotedString(String pattern, ParsePosition pos, StringBuffer appendTo, boolean escapingOn) { int start = pos.getIndex(); char[] c = pattern.toCharArray(); if (escapingOn && c[start] == QUOTE) { return appendTo == null ? null : appendTo.append(QUOTE); } int lastHold = start; for (int i = pos.getIndex(); i < pattern.length(); i++) { if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) { appendTo.append(c, lastHold, pos.getIndex() - lastHold).append( QUOTE); pos.setIndex(i + ESCAPED_QUOTE.length()); lastHold = pos.getIndex(); continue; } switch (c[pos.getIndex()]) { case QUOTE: next(pos); return appendTo == null ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold); default: next(pos); } } throw new IllegalArgumentException( "Unterminated quoted string at position " + start); } private StringBuffer appendQuotedString(String pattern, ParsePosition pos, StringBuffer appendTo, boolean escapingOn) { int start = pos.getIndex(); char[] c = pattern.toCharArray(); if (escapingOn && c[start] == QUOTE) { next(pos); return appendTo == null ? null : appendTo.append(QUOTE); } int lastHold = start; for (int i = pos.getIndex(); i < pattern.length(); i++) { if (escapingOn && pattern.substring(i).startsWith(ESCAPED_QUOTE)) { appendTo.append(c, lastHold, pos.getIndex() - lastHold).append( QUOTE); pos.setIndex(i + ESCAPED_QUOTE.length()); lastHold = pos.getIndex(); continue; } switch (c[pos.getIndex()]) { case QUOTE: next(pos); return appendTo == null ? null : appendTo.append(c, lastHold, pos.getIndex() - lastHold); default: next(pos); } } throw new IllegalArgumentException( "Unterminated quoted string at position " + start); }
src/java/org/apache/commons/lang/text/ExtendedMessageFormat.java
Lang-44
public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } if (val.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (val.startsWith("0x") || val.startsWith("-0x")) { return createInteger(val); } char lastChar = val.charAt(val.length() - 1); String mant; String dec; String exp; int decPos = val.indexOf('.'); int expPos = val.indexOf('e') + val.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = val.substring(0, val.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(val + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException e) { // ignore the bad number } //Fall through case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // empty catch } //Fall through default : throw new NumberFormatException(val + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(val); } catch (NumberFormatException nfe) { // empty catch } try { return createLong(val); } catch (NumberFormatException nfe) { // empty catch } return createBigInteger(val); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(val); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // empty catch } try { Double d = createDouble(val); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } return createBigDecimal(val); } } } public static Number createNumber(String val) throws NumberFormatException { if (val == null) { return null; } if (val.length() == 0) { throw new NumberFormatException("\"\" is not a valid number."); } if (val.length() == 1 && !Character.isDigit(val.charAt(0))) { throw new NumberFormatException(val + " is not a valid number."); } if (val.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (val.startsWith("0x") || val.startsWith("-0x")) { return createInteger(val); } char lastChar = val.charAt(val.length() - 1); String mant; String dec; String exp; int decPos = val.indexOf('.'); int expPos = val.indexOf('e') + val.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(val + " is not a valid number."); } dec = val.substring(decPos + 1, expPos); } else { dec = val.substring(decPos + 1); } mant = val.substring(0, decPos); } else { if (expPos > -1) { mant = val.substring(0, expPos); } else { mant = val; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = val.substring(0, val.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(val + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException e) { // ignore the bad number } //Fall through case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // empty catch } //Fall through default : throw new NumberFormatException(val + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < val.length() - 1) { exp = val.substring(expPos + 1, val.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(val); } catch (NumberFormatException nfe) { // empty catch } try { return createLong(val); } catch (NumberFormatException nfe) { // empty catch } return createBigInteger(val); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(val); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // empty catch } try { Double d = createDouble(val); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // empty catch } return createBigDecimal(val); } } }
src/java/org/apache/commons/lang/NumberUtils.java
Lang-45
public static String abbreviate(String str, int lower, int upper, String appendToEnd) { // initial parameter checks if (str == null) { return null; } if (str.length() == 0) { return StringUtils.EMPTY; } // if the lower value is greater than the length of the string, // set to the length of the string // if the upper value is -1 (i.e. no limit) or is greater // than the length of the string, set to the length of the string if (upper == -1 || upper > str.length()) { upper = str.length(); } // if upper is less than lower, raise it to lower if (upper < lower) { upper = lower; } StringBuffer result = new StringBuffer(); int index = StringUtils.indexOf(str, " ", lower); if (index == -1) { result.append(str.substring(0, upper)); // only if abbreviation has occured do we append the appendToEnd value if (upper != str.length()) { result.append(StringUtils.defaultString(appendToEnd)); } } else if (index > upper) { result.append(str.substring(0, upper)); result.append(StringUtils.defaultString(appendToEnd)); } else { result.append(str.substring(0, index)); result.append(StringUtils.defaultString(appendToEnd)); } return result.toString(); } public static String abbreviate(String str, int lower, int upper, String appendToEnd) { // initial parameter checks if (str == null) { return null; } if (str.length() == 0) { return StringUtils.EMPTY; } // if the lower value is greater than the length of the string, // set to the length of the string if (lower > str.length()) { lower = str.length(); } // if the upper value is -1 (i.e. no limit) or is greater // than the length of the string, set to the length of the string if (upper == -1 || upper > str.length()) { upper = str.length(); } // if upper is less than lower, raise it to lower if (upper < lower) { upper = lower; } StringBuffer result = new StringBuffer(); int index = StringUtils.indexOf(str, " ", lower); if (index == -1) { result.append(str.substring(0, upper)); // only if abbreviation has occured do we append the appendToEnd value if (upper != str.length()) { result.append(StringUtils.defaultString(appendToEnd)); } } else if (index > upper) { result.append(str.substring(0, upper)); result.append(StringUtils.defaultString(appendToEnd)); } else { result.append(str.substring(0, index)); result.append(StringUtils.defaultString(appendToEnd)); } return result.toString(); }
src/java/org/apache/commons/lang/WordUtils.java
Lang-48
public EqualsBuilder append(Object lhs, Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { // The simple case, not an array, just test the element isEquals = lhs.equals(rhs); } else if (lhs.getClass() != rhs.getClass()) { // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] this.setEquals(false); } // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays of the same depth else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // Not an array of primitives append((Object[]) lhs, (Object[]) rhs); } return this; } public EqualsBuilder append(Object lhs, Object rhs) { if (isEquals == false) { return this; } if (lhs == rhs) { return this; } if (lhs == null || rhs == null) { this.setEquals(false); return this; } Class lhsClass = lhs.getClass(); if (!lhsClass.isArray()) { if (lhs instanceof java.math.BigDecimal) { isEquals = (((java.math.BigDecimal)lhs).compareTo(rhs) == 0); } else { // The simple case, not an array, just test the element isEquals = lhs.equals(rhs); } } else if (lhs.getClass() != rhs.getClass()) { // Here when we compare different dimensions, for example: a boolean[][] to a boolean[] this.setEquals(false); } // 'Switch' on type of array, to dispatch to the correct handler // This handles multi dimensional arrays of the same depth else if (lhs instanceof long[]) { append((long[]) lhs, (long[]) rhs); } else if (lhs instanceof int[]) { append((int[]) lhs, (int[]) rhs); } else if (lhs instanceof short[]) { append((short[]) lhs, (short[]) rhs); } else if (lhs instanceof char[]) { append((char[]) lhs, (char[]) rhs); } else if (lhs instanceof byte[]) { append((byte[]) lhs, (byte[]) rhs); } else if (lhs instanceof double[]) { append((double[]) lhs, (double[]) rhs); } else if (lhs instanceof float[]) { append((float[]) lhs, (float[]) rhs); } else if (lhs instanceof boolean[]) { append((boolean[]) lhs, (boolean[]) rhs); } else { // Not an array of primitives append((Object[]) lhs, (Object[]) rhs); } return this; }
src/java/org/apache/commons/lang/builder/EqualsBuilder.java
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
Lang-5
public static Locale toLocale(final String str) { if (str == null) { return null; } final int len = str.length(); if (len < 2) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch0 = str.charAt(0); final char ch1 = str.charAt(1); if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } final char ch4 = str.charAt(4); if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } if (len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } public static Locale toLocale(final String str) { if (str == null) { return null; } final int len = str.length(); if (len < 2) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch0 = str.charAt(0); if (ch0 == '_') { if (len < 3) { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch1 = str.charAt(1); final char ch2 = str.charAt(2); if (!Character.isUpperCase(ch1) || !Character.isUpperCase(ch2)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 3) { return new Locale("", str.substring(1, 3)); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(3) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale("", str.substring(1, 3), str.substring(4)); } else { final char ch1 = str.charAt(1); if (!Character.isLowerCase(ch0) || !Character.isLowerCase(ch1)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str); } if (len < 5) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } final char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } final char ch4 = str.charAt(4); if (!Character.isUpperCase(ch3) || !Character.isUpperCase(ch4)) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } if (len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } }
src/main/java/org/apache/commons/lang3/LocaleUtils.java
Lang-51
public static boolean toBoolean(String str) { // Previously used equalsIgnoreCase, which was fast for interned 'true'. // Non interned 'true' matched 15 times slower. // // Optimisation provides same performance as before for interned 'true'. // Similar performance for null, 'false', and other strings not length 2/3/4. // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower. if (str == "true") { return true; } if (str == null) { return false; } switch (str.length()) { case 2: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); return (ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N'); } case 3: { char ch = str.charAt(0); if (ch == 'y') { return (str.charAt(1) == 'e' || str.charAt(1) == 'E') && (str.charAt(2) == 's' || str.charAt(2) == 'S'); } if (ch == 'Y') { return (str.charAt(1) == 'E' || str.charAt(1) == 'e') && (str.charAt(2) == 'S' || str.charAt(2) == 's'); } } case 4: { char ch = str.charAt(0); if (ch == 't') { return (str.charAt(1) == 'r' || str.charAt(1) == 'R') && (str.charAt(2) == 'u' || str.charAt(2) == 'U') && (str.charAt(3) == 'e' || str.charAt(3) == 'E'); } if (ch == 'T') { return (str.charAt(1) == 'R' || str.charAt(1) == 'r') && (str.charAt(2) == 'U' || str.charAt(2) == 'u') && (str.charAt(3) == 'E' || str.charAt(3) == 'e'); } } } return false; } public static boolean toBoolean(String str) { // Previously used equalsIgnoreCase, which was fast for interned 'true'. // Non interned 'true' matched 15 times slower. // // Optimisation provides same performance as before for interned 'true'. // Similar performance for null, 'false', and other strings not length 2/3/4. // 'true'/'TRUE' match 4 times slower, 'tRUE'/'True' 7 times slower. if (str == "true") { return true; } if (str == null) { return false; } switch (str.length()) { case 2: { char ch0 = str.charAt(0); char ch1 = str.charAt(1); return (ch0 == 'o' || ch0 == 'O') && (ch1 == 'n' || ch1 == 'N'); } case 3: { char ch = str.charAt(0); if (ch == 'y') { return (str.charAt(1) == 'e' || str.charAt(1) == 'E') && (str.charAt(2) == 's' || str.charAt(2) == 'S'); } if (ch == 'Y') { return (str.charAt(1) == 'E' || str.charAt(1) == 'e') && (str.charAt(2) == 'S' || str.charAt(2) == 's'); } return false; } case 4: { char ch = str.charAt(0); if (ch == 't') { return (str.charAt(1) == 'r' || str.charAt(1) == 'R') && (str.charAt(2) == 'u' || str.charAt(2) == 'U') && (str.charAt(3) == 'e' || str.charAt(3) == 'E'); } if (ch == 'T') { return (str.charAt(1) == 'R' || str.charAt(1) == 'r') && (str.charAt(2) == 'U' || str.charAt(2) == 'u') && (str.charAt(3) == 'E' || str.charAt(3) == 'e'); } } } return false; }
src/java/org/apache/commons/lang/BooleanUtils.java
Lang-52
private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'': if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"': out.write('\\'); out.write('"'); break; case '\\': out.write('\\'); out.write('\\'); break; default : out.write(ch); break; } } } } private static void escapeJavaStyleString(Writer out, String str, boolean escapeSingleQuote) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // handle unicode if (ch > 0xfff) { out.write("\\u" + hex(ch)); } else if (ch > 0xff) { out.write("\\u0" + hex(ch)); } else if (ch > 0x7f) { out.write("\\u00" + hex(ch)); } else if (ch < 32) { switch (ch) { case '\b': out.write('\\'); out.write('b'); break; case '\n': out.write('\\'); out.write('n'); break; case '\t': out.write('\\'); out.write('t'); break; case '\f': out.write('\\'); out.write('f'); break; case '\r': out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + hex(ch)); } else { out.write("\\u000" + hex(ch)); } break; } } else { switch (ch) { case '\'': if (escapeSingleQuote) { out.write('\\'); } out.write('\''); break; case '"': out.write('\\'); out.write('"'); break; case '\\': out.write('\\'); out.write('\\'); break; case '/': out.write('\\'); out.write('/'); break; default : out.write(ch); break; } } } }
src/java/org/apache/commons/lang/StringEscapeUtils.java
Lang-53
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; if (field == Calendar.SECOND) { done = true; } } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); if (field == Calendar.MINUTE) { done = true; } } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); } private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; } if (field == Calendar.SECOND) { done = true; } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); } if (field == Calendar.MINUTE) { done = true; } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
src/java/org/apache/commons/lang/time/DateUtils.java
Lang-54
public static Locale toLocale(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch3 = str.charAt(3); char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } } } public static Locale toLocale(String str) { if (str == null) { return null; } int len = str.length(); if (len != 2 && len != 5 && len < 7) { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch0 = str.charAt(0); char ch1 = str.charAt(1); if (ch0 < 'a' || ch0 > 'z' || ch1 < 'a' || ch1 > 'z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 2) { return new Locale(str, ""); } else { if (str.charAt(2) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } char ch3 = str.charAt(3); if (ch3 == '_') { return new Locale(str.substring(0, 2), "", str.substring(4)); } char ch4 = str.charAt(4); if (ch3 < 'A' || ch3 > 'Z' || ch4 < 'A' || ch4 > 'Z') { throw new IllegalArgumentException("Invalid locale format: " + str); } if (len == 5) { return new Locale(str.substring(0, 2), str.substring(3, 5)); } else { if (str.charAt(5) != '_') { throw new IllegalArgumentException("Invalid locale format: " + str); } return new Locale(str.substring(0, 2), str.substring(3, 5), str.substring(6)); } } }
src/java/org/apache/commons/lang/LocaleUtils.java
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
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
Lang-58
public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && isDigits(numeric.substring(1)) && (numeric.charAt(0) == '-' || Character.isDigit(numeric.charAt(0)))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //Fall through case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //Fall through default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } } public static Number createNumber(String str) throws NumberFormatException { if (str == null) { return null; } if (StringUtils.isBlank(str)) { throw new NumberFormatException("A blank string is not a valid number"); } if (str.startsWith("--")) { // this is protection for poorness in java.lang.BigDecimal. // it accepts this as a legal value, but it does not appear // to be in specification of class. OS X Java parses it to // a wrong value. return null; } if (str.startsWith("0x") || str.startsWith("-0x")) { return createInteger(str); } char lastChar = str.charAt(str.length() - 1); String mant; String dec; String exp; int decPos = str.indexOf('.'); int expPos = str.indexOf('e') + str.indexOf('E') + 1; if (decPos > -1) { if (expPos > -1) { if (expPos < decPos) { throw new NumberFormatException(str + " is not a valid number."); } dec = str.substring(decPos + 1, expPos); } else { dec = str.substring(decPos + 1); } mant = str.substring(0, decPos); } else { if (expPos > -1) { mant = str.substring(0, expPos); } else { mant = str; } dec = null; } if (!Character.isDigit(lastChar)) { if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length() - 1); } else { exp = null; } //Requesting a specific type.. String numeric = str.substring(0, str.length() - 1); boolean allZeros = isAllZeros(mant) && isAllZeros(exp); switch (lastChar) { case 'l' : case 'L' : if (dec == null && exp == null && (numeric.charAt(0) == '-' && isDigits(numeric.substring(1)) || isDigits(numeric))) { try { return createLong(numeric); } catch (NumberFormatException nfe) { //Too big for a long } return createBigInteger(numeric); } throw new NumberFormatException(str + " is not a valid number."); case 'f' : case 'F' : try { Float f = NumberUtils.createFloat(numeric); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { //If it's too big for a float or the float value = 0 and the string //has non-zeros in it, then float does not have the precision we want return f; } } catch (NumberFormatException nfe) { // ignore the bad number } //Fall through case 'd' : case 'D' : try { Double d = NumberUtils.createDouble(numeric); if (!(d.isInfinite() || (d.floatValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } try { return createBigDecimal(numeric); } catch (NumberFormatException e) { // ignore the bad number } //Fall through default : throw new NumberFormatException(str + " is not a valid number."); } } else { //User doesn't have a preference on the return type, so let's start //small and go from there... if (expPos > -1 && expPos < str.length() - 1) { exp = str.substring(expPos + 1, str.length()); } else { exp = null; } if (dec == null && exp == null) { //Must be an int,long,bigint try { return createInteger(str); } catch (NumberFormatException nfe) { // ignore the bad number } try { return createLong(str); } catch (NumberFormatException nfe) { // ignore the bad number } return createBigInteger(str); } else { //Must be a float,double,BigDec boolean allZeros = isAllZeros(mant) && isAllZeros(exp); try { Float f = createFloat(str); if (!(f.isInfinite() || (f.floatValue() == 0.0F && !allZeros))) { return f; } } catch (NumberFormatException nfe) { // ignore the bad number } try { Double d = createDouble(str); if (!(d.isInfinite() || (d.doubleValue() == 0.0D && !allZeros))) { return d; } } catch (NumberFormatException nfe) { // ignore the bad number } return createBigDecimal(str); } } }
src/java/org/apache/commons/lang/math/NumberUtils.java
Lang-59
public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); int strLen = str.length(); if (strLen >= width) { str.getChars(0, strLen, buffer, size); } else { int padLen = width - strLen; str.getChars(0, strLen, buffer, size); for (int i = 0; i < padLen; i++) { buffer[size + strLen + i] = padChar; } } size += width; } return this; } public StrBuilder appendFixedWidthPadRight(Object obj, int width, char padChar) { if (width > 0) { ensureCapacity(size + width); String str = (obj == null ? getNullText() : obj.toString()); int strLen = str.length(); if (strLen >= width) { str.getChars(0, width, buffer, size); } else { int padLen = width - strLen; str.getChars(0, strLen, buffer, size); for (int i = 0; i < padLen; i++) { buffer[size + strLen + i] = padChar; } } size += width; } return this; }
src/java/org/apache/commons/lang/text/StrBuilder.java
Lang-6
public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = input.length(); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); pos+= c.length; continue; } // // contract with translators is that they have to understand codepoints // // and they just took care of a surrogate pair for (int pt = 0; pt < consumed; pt++) { pos += Character.charCount(Character.codePointAt(input, pos)); } } } public final void translate(CharSequence input, Writer out) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (input == null) { return; } int pos = 0; int len = input.length(); while (pos < len) { int consumed = translate(input, pos, out); if (consumed == 0) { char[] c = Character.toChars(Character.codePointAt(input, pos)); out.write(c); pos+= c.length; continue; } // // contract with translators is that they have to understand codepoints // // and they just took care of a surrogate pair for (int pt = 0; pt < consumed; pt++) { pos += Character.charCount(Character.codePointAt(input, pt)); } } }
src/main/java/org/apache/commons/lang3/text/translate/CharSequenceTranslator.java
Lang-61
public int indexOf(String str, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (str == null || startIndex >= size) { return -1; } int strLen = str.length(); if (strLen == 1) { return indexOf(str.charAt(0), startIndex); } if (strLen == 0) { return startIndex; } if (strLen > size) { return -1; } char[] thisBuf = buffer; int len = thisBuf.length - strLen; outer: for (int i = startIndex; i < len; i++) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != thisBuf[i + j]) { continue outer; } } return i; } return -1; } public int indexOf(String str, int startIndex) { startIndex = (startIndex < 0 ? 0 : startIndex); if (str == null || startIndex >= size) { return -1; } int strLen = str.length(); if (strLen == 1) { return indexOf(str.charAt(0), startIndex); } if (strLen == 0) { return startIndex; } if (strLen > size) { return -1; } char[] thisBuf = buffer; int len = size - strLen + 1; outer: for (int i = startIndex; i < len; i++) { for (int j = 0; j < strLen; j++) { if (str.charAt(j) != thisBuf[i + j]) { continue outer; } } return i; } return -1; }
src/java/org/apache/commons/lang/text/StrBuilder.java
Lang-65
private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. // truncate milliseconds // truncate seconds // truncate minutes // reset time // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field val.set(fields[i][0], val.get(fields[i][0]) - offset); } throw new IllegalArgumentException("The field " + field + " is not supported"); } private static void modify(Calendar val, int field, boolean round) { if (val.get(Calendar.YEAR) > 280000000) { throw new ArithmeticException("Calendar value too large for accurate calculations"); } if (field == Calendar.MILLISECOND) { return; } // ----------------- Fix for LANG-59 ---------------------- START --------------- // see http://issues.apache.org/jira/browse/LANG-59 // // Manually truncate milliseconds, seconds and minutes, rather than using // Calendar methods. Date date = val.getTime(); long time = date.getTime(); boolean done = false; // truncate milliseconds int millisecs = val.get(Calendar.MILLISECOND); if (!round || millisecs < 500) { time = time - millisecs; if (field == Calendar.SECOND) { done = true; } } // truncate seconds int seconds = val.get(Calendar.SECOND); if (!done && (!round || seconds < 30)) { time = time - (seconds * 1000L); if (field == Calendar.MINUTE) { done = true; } } // truncate minutes int minutes = val.get(Calendar.MINUTE); if (!done && (!round || minutes < 30)) { time = time - (minutes * 60000L); } // reset time if (date.getTime() != time) { date.setTime(time); val.setTime(date); } // ----------------- Fix for LANG-59 ----------------------- END ---------------- boolean roundUp = false; for (int i = 0; i < fields.length; i++) { for (int j = 0; j < fields[i].length; j++) { if (fields[i][j] == field) { //This is our field... we stop looping if (round && roundUp) { if (field == DateUtils.SEMI_MONTH) { //This is a special case that's hard to generalize //If the date is 1, we round up to 16, otherwise // we subtract 15 days and add 1 month if (val.get(Calendar.DATE) == 1) { val.add(Calendar.DATE, 15); } else { val.add(Calendar.DATE, -15); val.add(Calendar.MONTH, 1); } } else { //We need at add one to this field since the // last number causes us to round up val.add(fields[i][0], 1); } } return; } } //We have various fields that are not easy roundings int offset = 0; boolean offsetSet = false; //These are special types of fields that require different rounding rules switch (field) { case DateUtils.SEMI_MONTH: if (fields[i][0] == Calendar.DATE) { //If we're going to drop the DATE field's value, // we want to do this our own way. //We need to subtrace 1 since the date has a minimum of 1 offset = val.get(Calendar.DATE) - 1; //If we're above 15 days adjustment, that means we're in the // bottom half of the month and should stay accordingly. if (offset >= 15) { offset -= 15; } //Record whether we're in the top or bottom half of that range roundUp = offset > 7; offsetSet = true; } break; case Calendar.AM_PM: if (fields[i][0] == Calendar.HOUR_OF_DAY) { //If we're going to drop the HOUR field's value, // we want to do this our own way. offset = val.get(Calendar.HOUR_OF_DAY); if (offset >= 12) { offset -= 12; } roundUp = offset > 6; offsetSet = true; } break; } if (!offsetSet) { int min = val.getActualMinimum(fields[i][0]); int max = val.getActualMaximum(fields[i][0]); //Calculate the offset from the minimum allowed value offset = val.get(fields[i][0]) - min; //Set roundUp if this is more than half way between the minimum and maximum roundUp = offset > ((max - min) / 2); } //We need to remove this field if (offset != 0) { val.set(fields[i][0], val.get(fields[i][0]) - offset); } } throw new IllegalArgumentException("The field " + field + " is not supported"); }
src/java/org/apache/commons/lang/time/DateUtils.java
Lang-9
private void init() { thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR); nameValues= new ConcurrentHashMap<Integer, KeyValue[]>(); StringBuilder regex= new StringBuilder(); List<Strategy> collector = new ArrayList<Strategy>(); Matcher patternMatcher= formatPattern.matcher(pattern); if(!patternMatcher.lookingAt()) { throw new IllegalArgumentException("Invalid pattern"); } currentFormatField= patternMatcher.group(); Strategy currentStrategy= getStrategy(currentFormatField); for(;;) { patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd()); if(!patternMatcher.lookingAt()) { nextStrategy = null; break; } String nextFormatField= patternMatcher.group(); nextStrategy = getStrategy(nextFormatField); if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= nextFormatField; currentStrategy= nextStrategy; } if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= null; strategies= collector.toArray(new Strategy[collector.size()]); parsePattern= Pattern.compile(regex.toString()); } private void init() { thisYear= Calendar.getInstance(timeZone, locale).get(Calendar.YEAR); nameValues= new ConcurrentHashMap<Integer, KeyValue[]>(); StringBuilder regex= new StringBuilder(); List<Strategy> collector = new ArrayList<Strategy>(); Matcher patternMatcher= formatPattern.matcher(pattern); if(!patternMatcher.lookingAt()) { throw new IllegalArgumentException("Invalid pattern"); } currentFormatField= patternMatcher.group(); Strategy currentStrategy= getStrategy(currentFormatField); for(;;) { patternMatcher.region(patternMatcher.end(), patternMatcher.regionEnd()); if(!patternMatcher.lookingAt()) { nextStrategy = null; break; } String nextFormatField= patternMatcher.group(); nextStrategy = getStrategy(nextFormatField); if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= nextFormatField; currentStrategy= nextStrategy; } if (patternMatcher.regionStart() != patternMatcher.regionEnd()) { throw new IllegalArgumentException("Failed to parse \""+pattern+"\" ; gave up at index "+patternMatcher.regionStart()); } if(currentStrategy.addRegex(this, regex)) { collector.add(currentStrategy); } currentFormatField= null; strategies= collector.toArray(new Strategy[collector.size()]); parsePattern= Pattern.compile(regex.toString()); }
src/main/java/org/apache/commons/lang3/time/FastDateParser.java
Math-10
public void atan2(final double[] y, final int yOffset, final double[] x, final int xOffset, final double[] result, final int resultOffset) { // compute r = sqrt(x^2+y^2) double[] tmp1 = new double[getSize()]; multiply(x, xOffset, x, xOffset, tmp1, 0); // x^2 double[] tmp2 = new double[getSize()]; multiply(y, yOffset, y, yOffset, tmp2, 0); // y^2 add(tmp1, 0, tmp2, 0, tmp2, 0); // x^2 + y^2 rootN(tmp2, 0, 2, tmp1, 0); // r = sqrt(x^2 + y^2) if (x[xOffset] >= 0) { // compute atan2(y, x) = 2 atan(y / (r + x)) add(tmp1, 0, x, xOffset, tmp2, 0); // r + x divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r + x) atan(tmp1, 0, tmp2, 0); // atan(y / (r + x)) for (int i = 0; i < tmp2.length; ++i) { result[resultOffset + i] = 2 * tmp2[i]; // 2 * atan(y / (r + x)) } } else { // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) subtract(tmp1, 0, x, xOffset, tmp2, 0); // r - x divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r - x) atan(tmp1, 0, tmp2, 0); // atan(y / (r - x)) result[resultOffset] = ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x)) for (int i = 1; i < tmp2.length; ++i) { result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x)) } } // fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly } public void atan2(final double[] y, final int yOffset, final double[] x, final int xOffset, final double[] result, final int resultOffset) { // compute r = sqrt(x^2+y^2) double[] tmp1 = new double[getSize()]; multiply(x, xOffset, x, xOffset, tmp1, 0); // x^2 double[] tmp2 = new double[getSize()]; multiply(y, yOffset, y, yOffset, tmp2, 0); // y^2 add(tmp1, 0, tmp2, 0, tmp2, 0); // x^2 + y^2 rootN(tmp2, 0, 2, tmp1, 0); // r = sqrt(x^2 + y^2) if (x[xOffset] >= 0) { // compute atan2(y, x) = 2 atan(y / (r + x)) add(tmp1, 0, x, xOffset, tmp2, 0); // r + x divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r + x) atan(tmp1, 0, tmp2, 0); // atan(y / (r + x)) for (int i = 0; i < tmp2.length; ++i) { result[resultOffset + i] = 2 * tmp2[i]; // 2 * atan(y / (r + x)) } } else { // compute atan2(y, x) = +/- pi - 2 atan(y / (r - x)) subtract(tmp1, 0, x, xOffset, tmp2, 0); // r - x divide(y, yOffset, tmp2, 0, tmp1, 0); // y /(r - x) atan(tmp1, 0, tmp2, 0); // atan(y / (r - x)) result[resultOffset] = ((tmp2[0] <= 0) ? -FastMath.PI : FastMath.PI) - 2 * tmp2[0]; // +/-pi - 2 * atan(y / (r - x)) for (int i = 1; i < tmp2.length; ++i) { result[resultOffset + i] = -2 * tmp2[i]; // +/-pi - 2 * atan(y / (r - x)) } } // fix value to take special cases (+0/+0, +0/-0, -0/+0, -0/-0, +/-infinity) correctly result[resultOffset] = FastMath.atan2(y[yOffset], x[xOffset]); }
src/main/java/org/apache/commons/math3/analysis/differentiation/DSCompiler.java
Math-101
public Complex parse(String source, ParsePosition pos) { int initialIndex = pos.getIndex(); // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse real Number re = parseNumber(source, getRealFormat(), pos); if (re == null) { // invalid real number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse sign int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); int sign = 0; switch (c) { case 0 : // no sign // return real only complex number return new Complex(re.doubleValue(), 0.0); case '-' : sign = -1; break; case '+' : sign = 1; break; default : // invalid sign // set index back to initial, error index should be the last // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse imaginary Number im = parseNumber(source, getRealFormat(), pos); if (im == null) { // invalid imaginary number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse imaginary character int n = getImaginaryCharacter().length(); startIndex = pos.getIndex(); int endIndex = startIndex + n; if ( source.substring(startIndex, endIndex).compareTo( getImaginaryCharacter()) != 0) { // set index back to initial, error index should be the start index // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } pos.setIndex(endIndex); return new Complex(re.doubleValue(), im.doubleValue() * sign); } public Complex parse(String source, ParsePosition pos) { int initialIndex = pos.getIndex(); // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse real Number re = parseNumber(source, getRealFormat(), pos); if (re == null) { // invalid real number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse sign int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); int sign = 0; switch (c) { case 0 : // no sign // return real only complex number return new Complex(re.doubleValue(), 0.0); case '-' : sign = -1; break; case '+' : sign = 1; break; default : // invalid sign // set index back to initial, error index should be the last // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse imaginary Number im = parseNumber(source, getRealFormat(), pos); if (im == null) { // invalid imaginary number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse imaginary character int n = getImaginaryCharacter().length(); startIndex = pos.getIndex(); int endIndex = startIndex + n; if ((startIndex >= source.length()) || (endIndex > source.length()) || source.substring(startIndex, endIndex).compareTo( getImaginaryCharacter()) != 0) { // set index back to initial, error index should be the start index // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } pos.setIndex(endIndex); return new Complex(re.doubleValue(), im.doubleValue() * sign); }
src/java/org/apache/commons/math/complex/ComplexFormat.java
Math-102
public double chiSquare(double[] expected, long[] observed) throws IllegalArgumentException { if ((expected.length < 2) || (expected.length != observed.length)) { throw new IllegalArgumentException( "observed, expected array lengths incorrect"); } if (!isPositive(expected) || !isNonNegative(observed)) { throw new IllegalArgumentException( "observed counts must be non-negative and expected counts must be postive"); } double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { dev = ((double) observed[i] - expected[i]); sumSq += dev * dev / expected[i]; } return sumSq; } public double chiSquare(double[] expected, long[] observed) throws IllegalArgumentException { if ((expected.length < 2) || (expected.length != observed.length)) { throw new IllegalArgumentException( "observed, expected array lengths incorrect"); } if (!isPositive(expected) || !isNonNegative(observed)) { throw new IllegalArgumentException( "observed counts must be non-negative and expected counts must be postive"); } double sumExpected = 0d; double sumObserved = 0d; for (int i = 0; i < observed.length; i++) { sumExpected += expected[i]; sumObserved += observed[i]; } double ratio = 1.0d; boolean rescale = false; if (Math.abs(sumExpected - sumObserved) > 10E-6) { ratio = sumObserved / sumExpected; rescale = true; } double sumSq = 0.0d; double dev = 0.0d; for (int i = 0; i < observed.length; i++) { if (rescale) { dev = ((double) observed[i] - ratio * expected[i]); sumSq += dev * dev / (ratio * expected[i]); } else { dev = ((double) observed[i] - expected[i]); sumSq += dev * dev / expected[i]; } } return sumSq; }
src/java/org/apache/commons/math/stat/inference/ChiSquareTestImpl.java
Math-103
public double cumulativeProbability(double x) throws MathException { return 0.5 * (1.0 + Erf.erf((x - mean) / (standardDeviation * Math.sqrt(2.0)))); } public double cumulativeProbability(double x) throws MathException { try { return 0.5 * (1.0 + Erf.erf((x - mean) / (standardDeviation * Math.sqrt(2.0)))); } catch (MaxIterationsExceededException ex) { if (x < (mean - 20 * standardDeviation)) { // JDK 1.5 blows at 38 return 0.0d; } else if (x > (mean + 20 * standardDeviation)) { return 1.0d; } else { throw ex; } } }
src/java/org/apache/commons/math/distribution/NormalDistributionImpl.java
Math-105
public double getSumSquaredErrors() { return sumYY - sumXY * sumXY / sumXX; } public double getSumSquaredErrors() { return Math.max(0d, sumYY - sumXY * sumXY / sumXX); }
src/java/org/apache/commons/math/stat/regression/SimpleRegression.java
Math-106
public Fraction parse(String source, ParsePosition pos) { // try to parse improper fraction Fraction ret = super.parse(source, pos); if (ret != null) { return ret; } int initialIndex = pos.getIndex(); // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse whole Number whole = getWholeFormat().parse(source, pos); if (whole == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse numerator Number num = getNumeratorFormat().parse(source, pos); if (num == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // minus signs should be leading, invalid expression // parse '/' int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); switch (c) { case 0 : // no '/' // return num as a fraction return new Fraction(num.intValue(), 1); case '/' : // found '/', continue parsing denominator break; default : // invalid '/' // set index back to initial, error index should be the last // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse denominator Number den = getDenominatorFormat().parse(source, pos); if (den == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // minus signs must be leading, invalid int w = whole.intValue(); int n = num.intValue(); int d = den.intValue(); return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d); } public Fraction parse(String source, ParsePosition pos) { // try to parse improper fraction Fraction ret = super.parse(source, pos); if (ret != null) { return ret; } int initialIndex = pos.getIndex(); // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse whole Number whole = getWholeFormat().parse(source, pos); if (whole == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse numerator Number num = getNumeratorFormat().parse(source, pos); if (num == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } if (num.intValue() < 0) { // minus signs should be leading, invalid expression pos.setIndex(initialIndex); return null; } // parse '/' int startIndex = pos.getIndex(); char c = parseNextCharacter(source, pos); switch (c) { case 0 : // no '/' // return num as a fraction return new Fraction(num.intValue(), 1); case '/' : // found '/', continue parsing denominator break; default : // invalid '/' // set index back to initial, error index should be the last // character examined. pos.setIndex(initialIndex); pos.setErrorIndex(startIndex); return null; } // parse whitespace parseAndIgnoreWhitespace(source, pos); // parse denominator Number den = getDenominatorFormat().parse(source, pos); if (den == null) { // invalid integer number // set index back to initial, error index should already be set // character examined. pos.setIndex(initialIndex); return null; } if (den.intValue() < 0) { // minus signs must be leading, invalid pos.setIndex(initialIndex); return null; } int w = whole.intValue(); int n = num.intValue(); int d = den.intValue(); return new Fraction(((Math.abs(w) * d) + n) * MathUtils.sign(w), d); }
src/java/org/apache/commons/math/fraction/ProperFractionFormat.java
Math-11
public double density(final double[] vals) throws DimensionMismatchException { final int dim = getDimension(); if (vals.length != dim) { throw new DimensionMismatchException(vals.length, dim); } return FastMath.pow(2 * FastMath.PI, -dim / 2) * FastMath.pow(covarianceMatrixDeterminant, -0.5) * getExponentTerm(vals); } public double density(final double[] vals) throws DimensionMismatchException { final int dim = getDimension(); if (vals.length != dim) { throw new DimensionMismatchException(vals.length, dim); } return FastMath.pow(2 * FastMath.PI, -0.5 * dim) * FastMath.pow(covarianceMatrixDeterminant, -0.5) * getExponentTerm(vals); }
src/main/java/org/apache/commons/math3/distribution/MultivariateNormalDistribution.java
Math-13
private RealMatrix squareRoot(RealMatrix m) { final EigenDecomposition dec = new EigenDecomposition(m); return dec.getSquareRoot(); } private RealMatrix squareRoot(RealMatrix m) { if (m instanceof DiagonalMatrix) { final int dim = m.getRowDimension(); final RealMatrix sqrtM = new DiagonalMatrix(dim); for (int i = 0; i < dim; i++) { sqrtM.setEntry(i, i, FastMath.sqrt(m.getEntry(i, i))); } return sqrtM; } else { final EigenDecomposition dec = new EigenDecomposition(m); return dec.getSquareRoot(); } }
src/main/java/org/apache/commons/math3/optimization/general/AbstractLeastSquaresOptimizer.java
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
Math-19
private void checkParameters() { final double[] init = getStartPoint(); final double[] lB = getLowerBound(); final double[] uB = getUpperBound(); // Checks whether there is at least one finite bound value. boolean hasFiniteBounds = false; for (int i = 0; i < lB.length; i++) { if (!Double.isInfinite(lB[i]) || !Double.isInfinite(uB[i])) { hasFiniteBounds = true; break; } } // Checks whether there is at least one infinite bound value. boolean hasInfiniteBounds = false; if (hasFiniteBounds) { for (int i = 0; i < lB.length; i++) { if (Double.isInfinite(lB[i]) || Double.isInfinite(uB[i])) { hasInfiniteBounds = true; break; } } if (hasInfiniteBounds) { // If there is at least one finite bound, none can be infinite, // because mixed cases are not supported by the current code. throw new MathUnsupportedOperationException(); } else { // Convert API to internal handling of boundaries. boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; // Abort early if the normalization will overflow (cf. "encode" method). } } else { // Convert API to internal handling of boundaries. boundaries = null; } if (inputSigma != null) { if (inputSigma.length != init.length) { throw new DimensionMismatchException(inputSigma.length, init.length); } for (int i = 0; i < init.length; i++) { if (inputSigma[i] < 0) { throw new NotPositiveException(inputSigma[i]); } if (boundaries != null) { if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) { throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]); } } } } } private void checkParameters() { final double[] init = getStartPoint(); final double[] lB = getLowerBound(); final double[] uB = getUpperBound(); // Checks whether there is at least one finite bound value. boolean hasFiniteBounds = false; for (int i = 0; i < lB.length; i++) { if (!Double.isInfinite(lB[i]) || !Double.isInfinite(uB[i])) { hasFiniteBounds = true; break; } } // Checks whether there is at least one infinite bound value. boolean hasInfiniteBounds = false; if (hasFiniteBounds) { for (int i = 0; i < lB.length; i++) { if (Double.isInfinite(lB[i]) || Double.isInfinite(uB[i])) { hasInfiniteBounds = true; break; } } if (hasInfiniteBounds) { // If there is at least one finite bound, none can be infinite, // because mixed cases are not supported by the current code. throw new MathUnsupportedOperationException(); } else { // Convert API to internal handling of boundaries. boundaries = new double[2][]; boundaries[0] = lB; boundaries[1] = uB; // Abort early if the normalization will overflow (cf. "encode" method). for (int i = 0; i < lB.length; i++) { if (Double.isInfinite(boundaries[1][i] - boundaries[0][i])) { final double max = Double.MAX_VALUE + boundaries[0][i]; final NumberIsTooLargeException e = new NumberIsTooLargeException(boundaries[1][i], max, true); e.getContext().addMessage(LocalizedFormats.OVERFLOW); e.getContext().addMessage(LocalizedFormats.INDEX, i); throw e; } } } } else { // Convert API to internal handling of boundaries. boundaries = null; } if (inputSigma != null) { if (inputSigma.length != init.length) { throw new DimensionMismatchException(inputSigma.length, init.length); } for (int i = 0; i < init.length; i++) { if (inputSigma[i] < 0) { throw new NotPositiveException(inputSigma[i]); } if (boundaries != null) { if (inputSigma[i] > boundaries[1][i] - boundaries[0][i]) { throw new OutOfRangeException(inputSigma[i], 0, boundaries[1][i] - boundaries[0][i]); } } } } }
src/main/java/org/apache/commons/math3/optimization/direct/CMAESOptimizer.java
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
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
Math-21
public RectangularCholeskyDecomposition(RealMatrix matrix, double small) throws NonPositiveDefiniteMatrixException { final int order = matrix.getRowDimension(); final double[][] c = matrix.getData(); final double[][] b = new double[order][order]; int[] swap = new int[order]; int[] index = new int[order]; for (int i = 0; i < order; ++i) { index[i] = i; } int r = 0; for (boolean loop = true; loop;) { // find maximal diagonal element swap[r] = r; for (int i = r + 1; i < order; ++i) { int ii = index[i]; int isi = index[swap[i]]; if (c[ii][ii] > c[isi][isi]) { swap[r] = i; } } // swap elements if (swap[r] != r) { int tmp = index[r]; index[r] = index[swap[r]]; index[swap[r]] = tmp; } // check diagonal element int ir = index[r]; if (c[ir][ir] < small) { if (r == 0) { throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small); } // check remaining diagonal elements for (int i = r; i < order; ++i) { if (c[index[i]][index[i]] < -small) { // there is at least one sufficiently negative diagonal element, // the symmetric positive semidefinite matrix is wrong throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small); } } // all remaining diagonal elements are close to zero, we consider we have // found the rank of the symmetric positive semidefinite matrix ++r; loop = false; } else { // transform the matrix final double sqrt = FastMath.sqrt(c[ir][ir]); b[r][r] = sqrt; final double inverse = 1 / sqrt; for (int i = r + 1; i < order; ++i) { final int ii = index[i]; final double e = inverse * c[ii][ir]; b[i][r] = e; c[ii][ii] -= e * e; for (int j = r + 1; j < i; ++j) { final int ij = index[j]; final double f = c[ii][ij] - e * b[j][r]; c[ii][ij] = f; c[ij][ii] = f; } } // prepare next iteration loop = ++r < order; } } // build the root matrix rank = r; root = MatrixUtils.createRealMatrix(order, r); for (int i = 0; i < order; ++i) { for (int j = 0; j < r; ++j) { root.setEntry(index[i], j, b[i][j]); } } } public RectangularCholeskyDecomposition(RealMatrix matrix, double small) throws NonPositiveDefiniteMatrixException { final int order = matrix.getRowDimension(); final double[][] c = matrix.getData(); final double[][] b = new double[order][order]; int[] index = new int[order]; for (int i = 0; i < order; ++i) { index[i] = i; } int r = 0; for (boolean loop = true; loop;) { // find maximal diagonal element int swapR = r; for (int i = r + 1; i < order; ++i) { int ii = index[i]; int isr = index[swapR]; if (c[ii][ii] > c[isr][isr]) { swapR = i; } } // swap elements if (swapR != r) { final int tmpIndex = index[r]; index[r] = index[swapR]; index[swapR] = tmpIndex; final double[] tmpRow = b[r]; b[r] = b[swapR]; b[swapR] = tmpRow; } // check diagonal element int ir = index[r]; if (c[ir][ir] < small) { if (r == 0) { throw new NonPositiveDefiniteMatrixException(c[ir][ir], ir, small); } // check remaining diagonal elements for (int i = r; i < order; ++i) { if (c[index[i]][index[i]] < -small) { // there is at least one sufficiently negative diagonal element, // the symmetric positive semidefinite matrix is wrong throw new NonPositiveDefiniteMatrixException(c[index[i]][index[i]], i, small); } } // all remaining diagonal elements are close to zero, we consider we have // found the rank of the symmetric positive semidefinite matrix ++r; loop = false; } else { // transform the matrix final double sqrt = FastMath.sqrt(c[ir][ir]); b[r][r] = sqrt; final double inverse = 1 / sqrt; final double inverse2 = 1 / c[ir][ir]; for (int i = r + 1; i < order; ++i) { final int ii = index[i]; final double e = inverse * c[ii][ir]; b[i][r] = e; c[ii][ii] -= c[ii][ir] * c[ii][ir] * inverse2; for (int j = r + 1; j < i; ++j) { final int ij = index[j]; final double f = c[ii][ij] - e * b[j][r]; c[ii][ij] = f; c[ij][ii] = f; } } // prepare next iteration loop = ++r < order; } } // build the root matrix rank = r; root = MatrixUtils.createRealMatrix(order, r); for (int i = 0; i < order; ++i) { for (int j = 0; j < r; ++j) { root.setEntry(index[i], j, b[i][j]); } } }
src/main/java/org/apache/commons/math3/linear/RectangularCholeskyDecomposition.java
Math-23
protected UnivariatePointValuePair doOptimize() { final boolean isMinim = getGoalType() == GoalType.MINIMIZE; final double lo = getMin(); final double mid = getStartValue(); final double hi = getMax(); // Optional additional convergence criteria. final ConvergenceChecker<UnivariatePointValuePair> checker = getConvergenceChecker(); double a; double b; if (lo < hi) { a = lo; b = hi; } else { a = hi; b = lo; } double x = mid; double v = x; double w = x; double d = 0; double e = 0; double fx = computeObjectiveValue(x); if (!isMinim) { fx = -fx; } double fv = fx; double fw = fx; UnivariatePointValuePair previous = null; UnivariatePointValuePair current = new UnivariatePointValuePair(x, isMinim ? fx : -fx); // Best point encountered so far (which is the initial guess). int iter = 0; while (true) { final double m = 0.5 * (a + b); final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold; final double tol2 = 2 * tol1; // Default stopping criterion. final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a); if (!stop) { double p = 0; double q = 0; double r = 0; double u = 0; if (FastMath.abs(e) > tol1) { // Fit parabola. r = (x - w) * (fx - fv); q = (x - v) * (fx - fw); p = (x - v) * q - (x - w) * r; q = 2 * (q - r); if (q > 0) { p = -p; } else { q = -q; } r = e; e = d; if (p > q * (a - x) && p < q * (b - x) && FastMath.abs(p) < FastMath.abs(0.5 * q * r)) { // Parabolic interpolation step. d = p / q; u = x + d; // f must not be evaluated too close to a or b. if (u - a < tol2 || b - u < tol2) { if (x <= m) { d = tol1; } else { d = -tol1; } } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } // Update by at least "tol1". if (FastMath.abs(d) < tol1) { if (d >= 0) { u = x + tol1; } else { u = x - tol1; } } else { u = x + d; } double fu = computeObjectiveValue(u); if (!isMinim) { fu = -fu; } // User-defined convergence checker. previous = current; current = new UnivariatePointValuePair(u, isMinim ? fu : -fu); if (checker != null) { if (checker.converged(iter, previous, current)) { return best(current, previous, isMinim); } } // Update a, b, v, w and x. if (fu <= fx) { if (u < x) { b = x; } else { a = x; } v = w; fv = fw; w = x; fw = fx; x = u; fx = fu; } else { if (u < x) { a = u; } else { b = u; } if (fu <= fw || Precision.equals(w, x)) { v = w; fv = fw; w = u; fw = fu; } else if (fu <= fv || Precision.equals(v, x) || Precision.equals(v, w)) { v = u; fv = fu; } } } else { // Default termination (Brent's criterion). return best(current, previous, isMinim); } ++iter; } } protected UnivariatePointValuePair doOptimize() { final boolean isMinim = getGoalType() == GoalType.MINIMIZE; final double lo = getMin(); final double mid = getStartValue(); final double hi = getMax(); // Optional additional convergence criteria. final ConvergenceChecker<UnivariatePointValuePair> checker = getConvergenceChecker(); double a; double b; if (lo < hi) { a = lo; b = hi; } else { a = hi; b = lo; } double x = mid; double v = x; double w = x; double d = 0; double e = 0; double fx = computeObjectiveValue(x); if (!isMinim) { fx = -fx; } double fv = fx; double fw = fx; UnivariatePointValuePair previous = null; UnivariatePointValuePair current = new UnivariatePointValuePair(x, isMinim ? fx : -fx); // Best point encountered so far (which is the initial guess). UnivariatePointValuePair best = current; int iter = 0; while (true) { final double m = 0.5 * (a + b); final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold; final double tol2 = 2 * tol1; // Default stopping criterion. final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a); if (!stop) { double p = 0; double q = 0; double r = 0; double u = 0; if (FastMath.abs(e) > tol1) { // Fit parabola. r = (x - w) * (fx - fv); q = (x - v) * (fx - fw); p = (x - v) * q - (x - w) * r; q = 2 * (q - r); if (q > 0) { p = -p; } else { q = -q; } r = e; e = d; if (p > q * (a - x) && p < q * (b - x) && FastMath.abs(p) < FastMath.abs(0.5 * q * r)) { // Parabolic interpolation step. d = p / q; u = x + d; // f must not be evaluated too close to a or b. if (u - a < tol2 || b - u < tol2) { if (x <= m) { d = tol1; } else { d = -tol1; } } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } // Update by at least "tol1". if (FastMath.abs(d) < tol1) { if (d >= 0) { u = x + tol1; } else { u = x - tol1; } } else { u = x + d; } double fu = computeObjectiveValue(u); if (!isMinim) { fu = -fu; } // User-defined convergence checker. previous = current; current = new UnivariatePointValuePair(u, isMinim ? fu : -fu); best = best(best, best(current, previous, isMinim), isMinim); if (checker != null) { if (checker.converged(iter, previous, current)) { return best; } } // Update a, b, v, w and x. if (fu <= fx) { if (u < x) { b = x; } else { a = x; } v = w; fv = fw; w = x; fw = fx; x = u; fx = fu; } else { if (u < x) { a = u; } else { b = u; } if (fu <= fw || Precision.equals(w, x)) { v = w; fv = fw; w = u; fw = fu; } else if (fu <= fv || Precision.equals(v, x) || Precision.equals(v, w)) { v = u; fv = fu; } } } else { // Default termination (Brent's criterion). return best(best, best(current, previous, isMinim), isMinim); } ++iter; } }
src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java
Math-24
protected UnivariatePointValuePair doOptimize() { final boolean isMinim = getGoalType() == GoalType.MINIMIZE; final double lo = getMin(); final double mid = getStartValue(); final double hi = getMax(); // Optional additional convergence criteria. final ConvergenceChecker<UnivariatePointValuePair> checker = getConvergenceChecker(); double a; double b; if (lo < hi) { a = lo; b = hi; } else { a = hi; b = lo; } double x = mid; double v = x; double w = x; double d = 0; double e = 0; double fx = computeObjectiveValue(x); if (!isMinim) { fx = -fx; } double fv = fx; double fw = fx; UnivariatePointValuePair previous = null; UnivariatePointValuePair current = new UnivariatePointValuePair(x, isMinim ? fx : -fx); int iter = 0; while (true) { final double m = 0.5 * (a + b); final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold; final double tol2 = 2 * tol1; // Default stopping criterion. final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a); if (!stop) { double p = 0; double q = 0; double r = 0; double u = 0; if (FastMath.abs(e) > tol1) { // Fit parabola. r = (x - w) * (fx - fv); q = (x - v) * (fx - fw); p = (x - v) * q - (x - w) * r; q = 2 * (q - r); if (q > 0) { p = -p; } else { q = -q; } r = e; e = d; if (p > q * (a - x) && p < q * (b - x) && FastMath.abs(p) < FastMath.abs(0.5 * q * r)) { // Parabolic interpolation step. d = p / q; u = x + d; // f must not be evaluated too close to a or b. if (u - a < tol2 || b - u < tol2) { if (x <= m) { d = tol1; } else { d = -tol1; } } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } // Update by at least "tol1". if (FastMath.abs(d) < tol1) { if (d >= 0) { u = x + tol1; } else { u = x - tol1; } } else { u = x + d; } double fu = computeObjectiveValue(u); if (!isMinim) { fu = -fu; } // User-defined convergence checker. previous = current; current = new UnivariatePointValuePair(u, isMinim ? fu : -fu); if (checker != null) { if (checker.converged(iter, previous, current)) { return current; } } // Update a, b, v, w and x. if (fu <= fx) { if (u < x) { b = x; } else { a = x; } v = w; fv = fw; w = x; fw = fx; x = u; fx = fu; } else { if (u < x) { a = u; } else { b = u; } if (fu <= fw || Precision.equals(w, x)) { v = w; fv = fw; w = u; fw = fu; } else if (fu <= fv || Precision.equals(v, x) || Precision.equals(v, w)) { v = u; fv = fu; } } } else { // Default termination (Brent's criterion). return current; } ++iter; } } protected UnivariatePointValuePair doOptimize() { final boolean isMinim = getGoalType() == GoalType.MINIMIZE; final double lo = getMin(); final double mid = getStartValue(); final double hi = getMax(); // Optional additional convergence criteria. final ConvergenceChecker<UnivariatePointValuePair> checker = getConvergenceChecker(); double a; double b; if (lo < hi) { a = lo; b = hi; } else { a = hi; b = lo; } double x = mid; double v = x; double w = x; double d = 0; double e = 0; double fx = computeObjectiveValue(x); if (!isMinim) { fx = -fx; } double fv = fx; double fw = fx; UnivariatePointValuePair previous = null; UnivariatePointValuePair current = new UnivariatePointValuePair(x, isMinim ? fx : -fx); int iter = 0; while (true) { final double m = 0.5 * (a + b); final double tol1 = relativeThreshold * FastMath.abs(x) + absoluteThreshold; final double tol2 = 2 * tol1; // Default stopping criterion. final boolean stop = FastMath.abs(x - m) <= tol2 - 0.5 * (b - a); if (!stop) { double p = 0; double q = 0; double r = 0; double u = 0; if (FastMath.abs(e) > tol1) { // Fit parabola. r = (x - w) * (fx - fv); q = (x - v) * (fx - fw); p = (x - v) * q - (x - w) * r; q = 2 * (q - r); if (q > 0) { p = -p; } else { q = -q; } r = e; e = d; if (p > q * (a - x) && p < q * (b - x) && FastMath.abs(p) < FastMath.abs(0.5 * q * r)) { // Parabolic interpolation step. d = p / q; u = x + d; // f must not be evaluated too close to a or b. if (u - a < tol2 || b - u < tol2) { if (x <= m) { d = tol1; } else { d = -tol1; } } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } } else { // Golden section step. if (x < m) { e = b - x; } else { e = a - x; } d = GOLDEN_SECTION * e; } // Update by at least "tol1". if (FastMath.abs(d) < tol1) { if (d >= 0) { u = x + tol1; } else { u = x - tol1; } } else { u = x + d; } double fu = computeObjectiveValue(u); if (!isMinim) { fu = -fu; } // User-defined convergence checker. previous = current; current = new UnivariatePointValuePair(u, isMinim ? fu : -fu); if (checker != null) { if (checker.converged(iter, previous, current)) { return best(current, previous, isMinim); } } // Update a, b, v, w and x. if (fu <= fx) { if (u < x) { b = x; } else { a = x; } v = w; fv = fw; w = x; fw = fx; x = u; fx = fu; } else { if (u < x) { a = u; } else { b = u; } if (fu <= fw || Precision.equals(w, x)) { v = w; fv = fw; w = u; fw = fu; } else if (fu <= fv || Precision.equals(v, x) || Precision.equals(v, w)) { v = u; fv = fu; } } } else { // Default termination (Brent's criterion). return best(current, previous, isMinim); } ++iter; } }
src/main/java/org/apache/commons/math3/optimization/univariate/BrentOptimizer.java
Math-25
private void guessAOmega() { // initialize the sums for the linear model between the two integrals double sx2 = 0; double sy2 = 0; double sxy = 0; double sxz = 0; double syz = 0; double currentX = observations[0].getX(); double currentY = observations[0].getY(); double f2Integral = 0; double fPrime2Integral = 0; final double startX = currentX; for (int i = 1; i < observations.length; ++i) { // one step forward final double previousX = currentX; final double previousY = currentY; currentX = observations[i].getX(); currentY = observations[i].getY(); // update the integrals of f<sup>2</sup> and f'<sup>2</sup> // considering a linear model for f (and therefore constant f') final double dx = currentX - previousX; final double dy = currentY - previousY; final double f2StepIntegral = dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3; final double fPrime2StepIntegral = dy * dy / dx; final double x = currentX - startX; f2Integral += f2StepIntegral; fPrime2Integral += fPrime2StepIntegral; sx2 += x * x; sy2 += f2Integral * f2Integral; sxy += x * f2Integral; sxz += x * fPrime2Integral; syz += f2Integral * fPrime2Integral; } // compute the amplitude and pulsation coefficients double c1 = sy2 * sxz - sxy * syz; double c2 = sxy * sxz - sx2 * syz; double c3 = sx2 * sy2 - sxy * sxy; if ((c1 / c2 < 0) || (c2 / c3 < 0)) { final int last = observations.length - 1; // Range of the observations, assuming that the // observations are sorted. final double xRange = observations[last].getX() - observations[0].getX(); if (xRange == 0) { throw new ZeroException(); } omega = 2 * Math.PI / xRange; double yMin = Double.POSITIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; for (int i = 1; i < observations.length; ++i) { final double y = observations[i].getY(); if (y < yMin) { yMin = y; } if (y > yMax) { yMax = y; } } a = 0.5 * (yMax - yMin); } else { // In some ill-conditioned cases (cf. MATH-844), the guesser // procedure cannot produce sensible results. a = FastMath.sqrt(c1 / c2); omega = FastMath.sqrt(c2 / c3); } } private void guessAOmega() { // initialize the sums for the linear model between the two integrals double sx2 = 0; double sy2 = 0; double sxy = 0; double sxz = 0; double syz = 0; double currentX = observations[0].getX(); double currentY = observations[0].getY(); double f2Integral = 0; double fPrime2Integral = 0; final double startX = currentX; for (int i = 1; i < observations.length; ++i) { // one step forward final double previousX = currentX; final double previousY = currentY; currentX = observations[i].getX(); currentY = observations[i].getY(); // update the integrals of f<sup>2</sup> and f'<sup>2</sup> // considering a linear model for f (and therefore constant f') final double dx = currentX - previousX; final double dy = currentY - previousY; final double f2StepIntegral = dx * (previousY * previousY + previousY * currentY + currentY * currentY) / 3; final double fPrime2StepIntegral = dy * dy / dx; final double x = currentX - startX; f2Integral += f2StepIntegral; fPrime2Integral += fPrime2StepIntegral; sx2 += x * x; sy2 += f2Integral * f2Integral; sxy += x * f2Integral; sxz += x * fPrime2Integral; syz += f2Integral * fPrime2Integral; } // compute the amplitude and pulsation coefficients double c1 = sy2 * sxz - sxy * syz; double c2 = sxy * sxz - sx2 * syz; double c3 = sx2 * sy2 - sxy * sxy; if ((c1 / c2 < 0) || (c2 / c3 < 0)) { final int last = observations.length - 1; // Range of the observations, assuming that the // observations are sorted. final double xRange = observations[last].getX() - observations[0].getX(); if (xRange == 0) { throw new ZeroException(); } omega = 2 * Math.PI / xRange; double yMin = Double.POSITIVE_INFINITY; double yMax = Double.NEGATIVE_INFINITY; for (int i = 1; i < observations.length; ++i) { final double y = observations[i].getY(); if (y < yMin) { yMin = y; } if (y > yMax) { yMax = y; } } a = 0.5 * (yMax - yMin); } else { if (c2 == 0) { // In some ill-conditioned cases (cf. MATH-844), the guesser // procedure cannot produce sensible results. throw new MathIllegalStateException(LocalizedFormats.ZERO_DENOMINATOR); } a = FastMath.sqrt(c1 / c2); omega = FastMath.sqrt(c2 / c3); } }
src/main/java/org/apache/commons/math3/optimization/fitting/HarmonicFitter.java
Math-26
private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) throws FractionConversionException { long overflow = Integer.MAX_VALUE; double r0 = value; long a0 = (long)FastMath.floor(r0); if (a0 > overflow) { throw new FractionConversionException(value, a0, 1l); } // check for (almost) integer arguments, which should not go // to iterations. if (FastMath.abs(a0 - value) < epsilon) { this.numerator = (int) a0; this.denominator = 1; return; } long p0 = 1; long q0 = 0; long p1 = a0; long q1 = 1; long p2 = 0; long q2 = 1; int n = 0; boolean stop = false; do { ++n; double r1 = 1.0 / (r0 - a0); long a1 = (long)FastMath.floor(r1); p2 = (a1 * p1) + p0; q2 = (a1 * q1) + q0; if ((p2 > overflow) || (q2 > overflow)) { throw new FractionConversionException(value, p2, q2); } double convergent = (double)p2 / (double)q2; if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) { p0 = p1; p1 = p2; q0 = q1; q1 = q2; a0 = a1; r0 = r1; } else { stop = true; } } while (!stop); if (n >= maxIterations) { throw new FractionConversionException(value, maxIterations); } if (q2 < maxDenominator) { this.numerator = (int) p2; this.denominator = (int) q2; } else { this.numerator = (int) p1; this.denominator = (int) q1; } } private Fraction(double value, double epsilon, int maxDenominator, int maxIterations) throws FractionConversionException { long overflow = Integer.MAX_VALUE; double r0 = value; long a0 = (long)FastMath.floor(r0); if (FastMath.abs(a0) > overflow) { throw new FractionConversionException(value, a0, 1l); } // check for (almost) integer arguments, which should not go // to iterations. if (FastMath.abs(a0 - value) < epsilon) { this.numerator = (int) a0; this.denominator = 1; return; } long p0 = 1; long q0 = 0; long p1 = a0; long q1 = 1; long p2 = 0; long q2 = 1; int n = 0; boolean stop = false; do { ++n; double r1 = 1.0 / (r0 - a0); long a1 = (long)FastMath.floor(r1); p2 = (a1 * p1) + p0; q2 = (a1 * q1) + q0; if ((FastMath.abs(p2) > overflow) || (FastMath.abs(q2) > overflow)) { throw new FractionConversionException(value, p2, q2); } double convergent = (double)p2 / (double)q2; if (n < maxIterations && FastMath.abs(convergent - value) > epsilon && q2 < maxDenominator) { p0 = p1; p1 = p2; q0 = q1; q1 = q2; a0 = a1; r0 = r1; } else { stop = true; } } while (!stop); if (n >= maxIterations) { throw new FractionConversionException(value, maxIterations); } if (q2 < maxDenominator) { this.numerator = (int) p2; this.denominator = (int) q2; } else { this.numerator = (int) p1; this.denominator = (int) q1; } }
src/main/java/org/apache/commons/math3/fraction/Fraction.java
Math-27
public double percentageValue() { return multiply(100).doubleValue(); } public double percentageValue() { return 100 * doubleValue(); }
src/main/java/org/apache/commons/math3/fraction/Fraction.java
Math-28
private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && minRow != row; i++) { if (row == tableau.getBasicRow(i)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } return minRatioPositions.get(0); } private Integer getPivotRow(SimplexTableau tableau, final int col) { // create a list of all the rows that tie for the lowest score in the minimum ratio test List<Integer> minRatioPositions = new ArrayList<Integer>(); double minRatio = Double.MAX_VALUE; for (int i = tableau.getNumObjectiveFunctions(); i < tableau.getHeight(); i++) { final double rhs = tableau.getEntry(i, tableau.getWidth() - 1); final double entry = tableau.getEntry(i, col); if (Precision.compareTo(entry, 0d, maxUlps) > 0) { final double ratio = rhs / entry; // check if the entry is strictly equal to the current min ratio // do not use a ulp/epsilon check final int cmp = Double.compare(ratio, minRatio); if (cmp == 0) { minRatioPositions.add(i); } else if (cmp < 0) { minRatio = ratio; minRatioPositions = new ArrayList<Integer>(); minRatioPositions.add(i); } } } if (minRatioPositions.size() == 0) { return null; } else if (minRatioPositions.size() > 1) { // there's a degeneracy as indicated by a tie in the minimum ratio test // 1. check if there's an artificial variable that can be forced out of the basis if (tableau.getNumArtificialVariables() > 0) { for (Integer row : minRatioPositions) { for (int i = 0; i < tableau.getNumArtificialVariables(); i++) { int column = i + tableau.getArtificialVariableOffset(); final double entry = tableau.getEntry(row, column); if (Precision.equals(entry, 1d, maxUlps) && row.equals(tableau.getBasicRow(column))) { return row; } } } } // 2. apply Bland's rule to prevent cycling: // take the row for which the corresponding basic variable has the smallest index // // see http://www.stanford.edu/class/msande310/blandrule.pdf // see http://en.wikipedia.org/wiki/Bland%27s_rule (not equivalent to the above paper) // // Additional heuristic: if we did not get a solution after half of maxIterations // revert to the simple case of just returning the top-most row // This heuristic is based on empirical data gathered while investigating MATH-828. if (getIterations() < getMaxIterations() / 2) { Integer minRow = null; int minIndex = tableau.getWidth(); for (Integer row : minRatioPositions) { int i = tableau.getNumObjectiveFunctions(); for (; i < tableau.getWidth() - 1 && minRow != row; i++) { if (row == tableau.getBasicRow(i)) { if (i < minIndex) { minIndex = i; minRow = row; } } } } return minRow; } } return minRatioPositions.get(0); }
src/main/java/org/apache/commons/math3/optimization/linear/SimplexSolver.java
Math-3
public static double linearCombination(final double[] a, final double[] b) throws DimensionMismatchException { final int len = a.length; if (len != b.length) { throw new DimensionMismatchException(len, b.length); } // Revert to scalar multiplication. final double[] prodHigh = new double[len]; double prodLowSum = 0; for (int i = 0; i < len; i++) { final double ai = a[i]; final double ca = SPLIT_FACTOR * ai; final double aHigh = ca - (ca - ai); final double aLow = ai - aHigh; final double bi = b[i]; final double cb = SPLIT_FACTOR * bi; final double bHigh = cb - (cb - bi); final double bLow = bi - bHigh; prodHigh[i] = ai * bi; final double prodLow = aLow * bLow - (((prodHigh[i] - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow); prodLowSum += prodLow; } final double prodHighCur = prodHigh[0]; double prodHighNext = prodHigh[1]; double sHighPrev = prodHighCur + prodHighNext; double sPrime = sHighPrev - prodHighNext; double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime); final int lenMinusOne = len - 1; for (int i = 1; i < lenMinusOne; i++) { prodHighNext = prodHigh[i + 1]; final double sHighCur = sHighPrev + prodHighNext; sPrime = sHighCur - prodHighNext; sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime); sHighPrev = sHighCur; } double result = sHighPrev + (prodLowSum + sLowSum); if (Double.isNaN(result)) { // either we have split infinite numbers or some coefficients were NaNs, // just rely on the naive implementation and let IEEE754 handle this result = 0; for (int i = 0; i < len; ++i) { result += a[i] * b[i]; } } return result; } public static double linearCombination(final double[] a, final double[] b) throws DimensionMismatchException { final int len = a.length; if (len != b.length) { throw new DimensionMismatchException(len, b.length); } if (len == 1) { // Revert to scalar multiplication. return a[0] * b[0]; } final double[] prodHigh = new double[len]; double prodLowSum = 0; for (int i = 0; i < len; i++) { final double ai = a[i]; final double ca = SPLIT_FACTOR * ai; final double aHigh = ca - (ca - ai); final double aLow = ai - aHigh; final double bi = b[i]; final double cb = SPLIT_FACTOR * bi; final double bHigh = cb - (cb - bi); final double bLow = bi - bHigh; prodHigh[i] = ai * bi; final double prodLow = aLow * bLow - (((prodHigh[i] - aHigh * bHigh) - aLow * bHigh) - aHigh * bLow); prodLowSum += prodLow; } final double prodHighCur = prodHigh[0]; double prodHighNext = prodHigh[1]; double sHighPrev = prodHighCur + prodHighNext; double sPrime = sHighPrev - prodHighNext; double sLowSum = (prodHighNext - (sHighPrev - sPrime)) + (prodHighCur - sPrime); final int lenMinusOne = len - 1; for (int i = 1; i < lenMinusOne; i++) { prodHighNext = prodHigh[i + 1]; final double sHighCur = sHighPrev + prodHighNext; sPrime = sHighCur - prodHighNext; sLowSum += (prodHighNext - (sHighCur - sPrime)) + (sHighPrev - sPrime); sHighPrev = sHighCur; } double result = sHighPrev + (prodLowSum + sLowSum); if (Double.isNaN(result)) { // either we have split infinite numbers or some coefficients were NaNs, // just rely on the naive implementation and let IEEE754 handle this result = 0; for (int i = 0; i < len; ++i) { result += a[i] * b[i]; } } return result; }
src/main/java/org/apache/commons/math3/util/MathArrays.java
Math-30
private double calculateAsymptoticPValue(final double Umin, final int n1, final int n2) throws ConvergenceException, MaxCountExceededException { final int n1n2prod = n1 * n2; // http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation final double EU = n1n2prod / 2.0; final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0; final double z = (Umin - EU) / FastMath.sqrt(VarU); final NormalDistribution standardNormal = new NormalDistribution(0, 1); return 2 * standardNormal.cumulativeProbability(z); } private double calculateAsymptoticPValue(final double Umin, final int n1, final int n2) throws ConvergenceException, MaxCountExceededException { final double n1n2prod = n1 * n2; // http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation final double EU = n1n2prod / 2.0; final double VarU = n1n2prod * (n1 + n2 + 1) / 12.0; final double z = (Umin - EU) / FastMath.sqrt(VarU); final NormalDistribution standardNormal = new NormalDistribution(0, 1); return 2 * standardNormal.cumulativeProbability(z); }
src/main/java/org/apache/commons/math3/stat/inference/MannWhitneyUTest.java