method2testcases
stringlengths
118
6.63k
### Question: GsonToObjectFunction implements RuntimeSetterFunction<String, Object> { @Nullable @Override public Object apply(@Nullable String input, Type runtimeOutputType) { return input == null ? null : new Gson().fromJson(input, runtimeOutputType); } @Nullable @Override Object apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); String json = new Gson().toJson(list); Method m = A.class.getDeclaredMethod("setList", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("list", m); invoker.invoke(a, json); assertThat(a.getList().toString(), equalTo(list.toString())); B b = new B(3, 5); String json2 = new Gson().toJson(b); Method m2 = A.class.getDeclaredMethod("setB", B.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("b", m2); invoker2.invoke(a, json2); assertThat(a.getB(), equalTo(b)); }
### Question: Document extends Element { public static Document createShell(String baseUri) { Validate.notNull(baseUri); Document doc = new Document(baseUri); Element html = doc.appendElement("html"); html.appendElement("head"); html.appendElement("body"); return doc; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdateDisabled() { final Document docDisabled = Document.createShell(""); final String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlNoCharset, docDisabled.toString()); assertNull(docDisabled.select("meta[charset]").first()); }
### Question: Document extends Element { public void charset(Charset charset) { updateMetaCharsetElement(true); outputSettings.charset(charset); ensureMetaCharsetElement(); } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdateEnabledAfterCharsetChange() { final Document doc = createHtmlDocument("dontTouch"); doc.charset(Charset.forName(charsetUtf8)); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertTrue(doc.select("meta[name=charset]").isEmpty()); }
### Question: Document extends Element { public void updateMetaCharsetElement(boolean update) { this.updateMetaCharset = update; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); }
### Question: FormElement extends Element { public Elements elements() { return elements; } FormElement(Tag tag, String baseUri, Attributes attributes); Elements elements(); FormElement addElement(Element element); Connection submit(); List<Connection.KeyVal> formData(); }### Answer: @Test public void hasAssociatedControls() { String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http: Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); }
### Question: FormElement extends Element { public Connection submit() { String action = hasAttr("action") ? absUrl("action") : baseUri(); Validate.notEmpty(action, "Could not determine a form action URL for submit. Ensure you set a base URI when parsing."); Connection.Method method = attr("method").toUpperCase().equals("POST") ? Connection.Method.POST : Connection.Method.GET; return Jsoup.connect(action) .data(formData()) .method(method); } FormElement(Tag tag, String baseUri, Attributes attributes); Elements elements(); FormElement addElement(Element element); Connection submit(); List<Connection.KeyVal> formData(); }### Answer: @Test public void createsSubmitableConnection() { String html = "<form action='/search'><input name='q'></form>"; Document doc = Jsoup.parse(html, "http: doc.select("[name=q]").attr("value", "jsoup"); FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals(Connection.Method.GET, con.request().method()); assertEquals("http: List<Connection.KeyVal> dataList = (List<Connection.KeyVal>) con.request().data(); assertEquals("q=jsoup", dataList.get(0).toString()); doc.select("form").attr("method", "post"); Connection con2 = form.submit(); assertEquals(Connection.Method.POST, con2.request().method()); } @Test public void actionWithNoValue() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html, "http: FormElement form = ((FormElement) doc.select("form").first()); Connection con = form.submit(); assertEquals("http: } @Test public void actionWithNoBaseUri() { String html = "<form><input name='q'></form>"; Document doc = Jsoup.parse(html); FormElement form = ((FormElement) doc.select("form").first()); boolean threw = false; try { Connection con = form.submit(); } catch (IllegalArgumentException e) { threw = true; assertEquals("Could not determine a form action URL for submit. Ensure you set a base URI when parsing.", e.getMessage()); } assertTrue(threw); }
### Question: ObjectToGsonFunction implements GetterFunction<Object, String> { @Nullable @Override public String apply(@Nullable Object input) { return input == null ? null : new Gson().toJson(input); } @Nullable @Override String apply(@Nullable Object input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); a.setList(list); Method m = A.class.getDeclaredMethod("getList"); GetterInvoker invoker = FunctionalGetterInvoker.create("list", m); String r = (String) invoker.invoke(a); assertThat(r, is(new Gson().toJson(list))); B b = new B(3, 5); a.setB(b); Method m2 = A.class.getDeclaredMethod("getB"); GetterInvoker invoker2 = FunctionalGetterInvoker.create("b", m2); String r2 = (String) invoker2.invoke(a); assertThat(r2, is(new Gson().toJson(b))); }
### Question: Attribute implements Map.Entry<String, String>, Cloneable { public String html() { StringBuilder accum = new StringBuilder(); try { html(accum, (new Document("")).outputSettings()); } catch(IOException exception) { throw new SerializationException(exception); } return accum.toString(); } Attribute(String key, String value); Attribute(String key, String val, Attributes parent); String getKey(); void setKey(String key); String getValue(); String setValue(String val); String html(); @Override String toString(); static Attribute createFromEncoded(String unencodedKey, String encodedValue); @Override boolean equals(Object o); @Override int hashCode(); @Override Attribute clone(); }### Answer: @Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &amp;\"", attr.html()); assertEquals(attr.html(), attr.toString()); }
### Question: TextNode extends LeafNode { public boolean isBlank() { return StringUtil.isBlank(coreValue()); } TextNode(String text); TextNode(String text, String baseUri); String nodeName(); String text(); TextNode text(String text); String getWholeText(); boolean isBlank(); TextNode splitText(int offset); @Override String toString(); static TextNode createFromEncoded(String encodedText, String baseUri); static TextNode createFromEncoded(String encodedText); }### Answer: @Test public void testBlank() { TextNode one = new TextNode(""); TextNode two = new TextNode(" "); TextNode three = new TextNode(" \n\n "); TextNode four = new TextNode("Hello"); TextNode five = new TextNode(" \nHello "); assertTrue(one.isBlank()); assertTrue(two.isBlank()); assertTrue(three.isBlank()); assertFalse(four.isBlank()); assertFalse(five.isBlank()); }
### Question: TextNode extends LeafNode { public TextNode splitText(int offset) { final String text = coreValue(); Validate.isTrue(offset >= 0, "Split offset must be not be negative"); Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length"); String head = text.substring(0, offset); String tail = text.substring(offset); text(head); TextNode tailNode = new TextNode(tail, this.baseUri()); if (parent() != null) parent().addChildren(siblingIndex()+1, tailNode); return tailNode; } TextNode(String text); TextNode(String text, String baseUri); String nodeName(); String text(); TextNode text(String text); String getWholeText(); boolean isBlank(); TextNode splitText(int offset); @Override String toString(); static TextNode createFromEncoded(String encodedText, String baseUri); static TextNode createFromEncoded(String encodedText); }### Answer: @Test public void testSplitText() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); assertEquals("Hello ", tn.getWholeText()); assertEquals("there", tail.getWholeText()); tail.text("there!"); assertEquals("Hello there!", div.text()); assertTrue(tn.parent() == tail.parent()); } @Test public void testSplitAnEmbolden() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); tail.wrap("<b></b>"); assertEquals("Hello <b>there</b>", TextUtil.stripNewlines(div.html())); }
### Question: Element extends Node { public Element getElementById(String id) { Validate.notEmpty(id); Elements elements = Collector.collect(new Evaluator.Id(id), this); if (elements.size() > 0) return elements.get(0); else return null; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testGetElementById() { Document doc = Jsoup.parse(reference); Element div = doc.getElementById("div1"); assertEquals("div1", div.id()); assertNull(doc.getElementById("none")); Document doc2 = Jsoup.parse("<div id=1><div id=2><p>Hello <span id=2>world!</span></p></div></div>"); Element div2 = doc2.getElementById("2"); assertEquals("div", div2.tagName()); Element span = div2.child(0).getElementById("2"); assertEquals("span", span.tagName()); }
### Question: ObjectToFastjsonFunction implements GetterFunction<Object, String> { @Nullable @Override public String apply(@Nullable Object input) { return input == null ? null : JSON.toJSONString(input); } @Nullable @Override String apply(@Nullable Object input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); a.setList(list); Method m = A.class.getDeclaredMethod("getList"); GetterInvoker invoker = FunctionalGetterInvoker.create("list", m); String r = (String) invoker.invoke(a); assertThat(r, is(JSON.toJSONString(list))); B b = new B(3, 5); a.setB(b); Method m2 = A.class.getDeclaredMethod("getB"); GetterInvoker invoker2 = FunctionalGetterInvoker.create("b", m2); String r2 = (String) invoker2.invoke(a); assertThat(r2, is(JSON.toJSONString(b))); }
### Question: Element extends Node { public int elementSiblingIndex() { if (parent() == null) return 0; return indexInList(this, parent().childElementsList()); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testElementSiblingIndex() { Document doc = Jsoup.parse("<div><p>One</p>...<p>Two</p>...<p>Three</p>"); Elements ps = doc.select("p"); assertTrue(0 == ps.get(0).elementSiblingIndex()); assertTrue(1 == ps.get(1).elementSiblingIndex()); assertTrue(2 == ps.get(2).elementSiblingIndex()); }
### Question: Element extends Node { public Element prependElement(String tagName) { Element child = new Element(Tag.valueOf(tagName), baseUri()); prependChild(child); return child; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testPrependElement() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependElement("p").text("Before"); assertEquals("Before", div.child(0).text()); assertEquals("Hello", div.child(1).text()); }
### Question: Element extends Node { public Element prependText(String text) { Validate.notNull(text); TextNode node = new TextNode(text); prependChild(node); return this; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testPrependText() { Document doc = Jsoup.parse("<div id=1><p>Hello</p></div>"); Element div = doc.getElementById("1"); div.prependText("there & now > "); assertEquals("there & now > Hello", div.text()); assertEquals("there &amp; now &gt; <p>Hello</p>", TextUtil.stripNewlines(div.html())); }
### Question: FastjsonToObjectFunction implements RuntimeSetterFunction<String, Object> { @Nullable @Override public Object apply(@Nullable String input, Type runtimeOutputType) { return input == null ? null : JSON.parseObject(input, runtimeOutputType); } @Nullable @Override Object apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); String json = JSON.toJSONString(list); Method m = A.class.getDeclaredMethod("setList", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("list", m); invoker.invoke(a, json); assertThat(a.getList().toString(), equalTo(list.toString())); B b = new B(3, 5); String json2 = JSON.toJSONString(b); Method m2 = A.class.getDeclaredMethod("setB", B.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("b", m2); invoker2.invoke(a, json2); assertThat(a.getB(), equalTo(b)); }
### Question: Element extends Node { @Override public Element wrap(String html) { return (Element) super.wrap(html); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testWrap() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p = doc.select("p").first(); p.wrap("<div class='head'></div>"); assertEquals("<div><div class=\"head\"><p>Hello</p></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); Element ret = p.wrap("<div><div class=foo></div><p>What?</p></div>"); assertEquals("<div><div class=\"head\"><div><div class=\"foo\"><p>Hello</p></div><p>What?</p></div></div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); assertEquals(ret, p); }
### Question: Element extends Node { @Override public Element before(String html) { return (Element) super.before(html); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void before() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.before("<div>one</div><div>two</div>"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().before("<p>Three</p><!-- four -->"); assertEquals("<div><div>one</div><div>two</div><p>Hello</p><p>Three</p><!-- four --><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); }
### Question: Element extends Node { @Override public Element after(String html) { return (Element) super.after(html); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void after() { Document doc = Jsoup.parse("<div><p>Hello</p><p>There</p></div>"); Element p1 = doc.select("p").first(); p1.after("<div>one</div><div>two</div>"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p></div>", TextUtil.stripNewlines(doc.body().html())); doc.select("p").last().after("<p>Three</p><!-- four -->"); assertEquals("<div><p>Hello</p><div>one</div><div>two</div><p>There</p><p>Three</p><!-- four --></div>", TextUtil.stripNewlines(doc.body().html())); }
### Question: Element extends Node { public boolean hasText() { for (Node child: childNodes) { if (child instanceof TextNode) { TextNode textNode = (TextNode) child; if (!textNode.isBlank()) return true; } else if (child instanceof Element) { Element el = (Element) child; if (el.hasText()) return true; } } return false; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testHasText() { Document doc = Jsoup.parse("<div><p>Hello</p><p></p></div>"); Element div = doc.select("div").first(); Elements ps = doc.select("p"); assertTrue(div.hasText()); assertTrue(ps.first().hasText()); assertFalse(ps.last().hasText()); }
### Question: Element extends Node { public Map<String, String> dataset() { return attributes().dataset(); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void dataset() { Document doc = Jsoup.parse("<div id=1 data-name=jsoup class=new data-package=jar>Hello</div><p id=2>Hello</p>"); Element div = doc.select("div").first(); Map<String, String> dataset = div.dataset(); Attributes attributes = div.attributes(); assertEquals(2, dataset.size()); assertEquals("jsoup", dataset.get("name")); assertEquals("jar", dataset.get("package")); dataset.put("name", "jsoup updated"); dataset.put("language", "java"); dataset.remove("package"); assertEquals(2, dataset.size()); assertEquals(4, attributes.size()); assertEquals("jsoup updated", attributes.get("data-name")); assertEquals("jsoup updated", dataset.get("name")); assertEquals("java", attributes.get("data-language")); assertEquals("java", dataset.get("language")); attributes.put("data-food", "bacon"); assertEquals(3, dataset.size()); assertEquals("bacon", dataset.get("food")); attributes.put("data-", "empty"); assertEquals(null, dataset.get("")); Element p = doc.select("p").first(); assertEquals(0, p.dataset().size()); }
### Question: Element extends Node { @Override public Element clone() { return (Element) super.clone(); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testClone() { Document doc = Jsoup.parse("<div><p>One<p><span>Two</div>"); Element p = doc.select("p").get(1); Element clone = p.clone(); assertNull(clone.parent()); assertEquals(0, clone.siblingIndex); assertEquals(1, p.siblingIndex); assertNotNull(p.parent()); clone.append("<span>Three"); assertEquals("<p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(clone.outerHtml())); assertEquals("<div><p>One</p><p><span>Two</span></p></div>", TextUtil.stripNewlines(doc.body().html())); doc.body().appendChild(clone); assertNotNull(clone.parent()); assertEquals("<div><p>One</p><p><span>Two</span></p></div><p><span>Two</span><span>Three</span></p>", TextUtil.stripNewlines(doc.body().html())); }
### Question: Element extends Node { public Element appendChild(Node child) { Validate.notNull(child); reparentChild(child); ensureChildNodes(); childNodes.add(child); child.setSiblingIndex(childNodes.size() - 1); return this; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testHashcodeIsStableWithContentChanges() { Element root = new Element(Tag.valueOf("root"), ""); HashSet<Element> set = new HashSet<Element>(); set.add(root); root.appendChild(new Element(Tag.valueOf("a"), "")); assertTrue(set.contains(root)); }
### Question: StringToLongArrayFunction implements SetterFunction<String, long[]> { @Nullable @Override public long[] apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new long[0]; } String[] ss = input.split(SEPARATOR); long[] r = new long[ss.length]; for (int i = 0; i < ss.length; i++) { r[i] = Long.parseLong(ss[i]); } return r; } @Nullable @Override long[] apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", long[].class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1000000000000000000,2,3"); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new long[]{1000000000000000000L, 2, 3}))); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new long[]{}))); }
### Question: Element extends Node { public boolean is(String cssQuery) { return is(QueryParser.parse(cssQuery)); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testIs() { String html = "<div><p>One <a class=big>Two</a> Three</p><p>Another</p>"; Document doc = Jsoup.parse(html); Element p = doc.select("p").first(); assertTrue(p.is("p")); assertFalse(p.is("div")); assertTrue(p.is("p:has(a)")); assertTrue(p.is("p:first-child")); assertFalse(p.is("p:last-child")); assertTrue(p.is("*")); assertTrue(p.is("div p")); Element q = doc.select("p").last(); assertTrue(q.is("p")); assertTrue(q.is("p ~ p")); assertTrue(q.is("p + p")); assertTrue(q.is("p:last-child")); assertFalse(q.is("p a")); assertFalse(q.is("a")); }
### Question: Element extends Node { public String tagName() { return tag.getName(); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void elementByTagName() { Element a = new Element("P"); assertTrue(a.tagName().equals("P")); }
### Question: Element extends Node { public Element appendTo(Element parent) { Validate.notNull(parent); parent.appendChild(this); return this; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Override Attributes attributes(); @Override String baseUri(); @Override int childNodeSize(); @Override String nodeName(); String tagName(); Element tagName(String tagName); Tag tag(); boolean isBlock(); String id(); Element attr(String attributeKey, String attributeValue); Element attr(String attributeKey, boolean attributeValue); Map<String, String> dataset(); @Override final Element parent(); Elements parents(); Element child(int index); Elements children(); List<TextNode> textNodes(); List<DataNode> dataNodes(); Elements select(String cssQuery); boolean is(String cssQuery); boolean is(Evaluator evaluator); Element appendChild(Node child); Element appendTo(Element parent); Element prependChild(Node child); Element insertChildren(int index, Collection<? extends Node> children); Element insertChildren(int index, Node... children); Element appendElement(String tagName); Element prependElement(String tagName); Element appendText(String text); Element prependText(String text); Element append(String html); Element prepend(String html); @Override Element before(String html); @Override Element before(Node node); @Override Element after(String html); @Override Element after(Node node); Element empty(); @Override Element wrap(String html); String cssSelector(); Elements siblingElements(); Element nextElementSibling(); Element previousElementSibling(); Element firstElementSibling(); int elementSiblingIndex(); Element lastElementSibling(); Elements getElementsByTag(String tagName); Element getElementById(String id); Elements getElementsByClass(String className); Elements getElementsByAttribute(String key); Elements getElementsByAttributeStarting(String keyPrefix); Elements getElementsByAttributeValue(String key, String value); Elements getElementsByAttributeValueNot(String key, String value); Elements getElementsByAttributeValueStarting(String key, String valuePrefix); Elements getElementsByAttributeValueEnding(String key, String valueSuffix); Elements getElementsByAttributeValueContaining(String key, String match); Elements getElementsByAttributeValueMatching(String key, Pattern pattern); Elements getElementsByAttributeValueMatching(String key, String regex); Elements getElementsByIndexLessThan(int index); Elements getElementsByIndexGreaterThan(int index); Elements getElementsByIndexEquals(int index); Elements getElementsContainingText(String searchText); Elements getElementsContainingOwnText(String searchText); Elements getElementsMatchingText(Pattern pattern); Elements getElementsMatchingText(String regex); Elements getElementsMatchingOwnText(Pattern pattern); Elements getElementsMatchingOwnText(String regex); Elements getAllElements(); String text(); String ownText(); Element text(String text); boolean hasText(); String data(); String className(); Set<String> classNames(); Element classNames(Set<String> classNames); boolean hasClass(String className); Element addClass(String className); Element removeClass(String className); Element toggleClass(String className); String val(); Element val(String value); String html(); @Override T html(T appendable); Element html(String html); String toString(); @Override Element clone(); }### Answer: @Test public void testAppendTo() { String parentHtml = "<div class='a'></div>"; String childHtml = "<div class='b'></div><p>Two</p>"; Document parentDoc = Jsoup.parse(parentHtml); Element parent = parentDoc.body(); Document childDoc = Jsoup.parse(childHtml); Element div = childDoc.select("div").first(); Element p = childDoc.select("p").first(); Element appendTo1 = div.appendTo(parent); assertEquals(div, appendTo1); Element appendTo2 = p.appendTo(div); assertEquals(p, appendTo2); assertEquals("<div class=\"a\"></div>\n<div class=\"b\">\n <p>Two</p>\n</div>", parentDoc.body().html()); assertEquals("", childDoc.body().html()); }
### Question: Entities { static String escape(String string, Document.OutputSettings out) { StringBuilder accum = new StringBuilder(string.length() * 2); try { escape(accum, string, out, false, false, false); } catch (IOException e) { throw new SerializationException(e); } return accum.toString(); } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); }### Answer: @Test public void escape() { String text = "Hello &<> Å å π 新 there ¾ © »"; String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); String escapedAsciiFull = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(extended)); String escapedAsciiXhtml = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(xhtml)); String escapedUtfFull = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(extended)); String escapedUtfMin = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(xhtml)); assertEquals("Hello &amp;&lt;&gt; &Aring; &aring; &#x3c0; &#x65b0; there &frac34; &copy; &raquo;", escapedAscii); assertEquals("Hello &amp;&lt;&gt; &angst; &aring; &pi; &#x65b0; there &frac34; &copy; &raquo;", escapedAsciiFull); assertEquals("Hello &amp;&lt;&gt; &#xc5; &#xe5; &#x3c0; &#x65b0; there &#xbe; &#xa9; &#xbb;", escapedAsciiXhtml); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfFull); assertEquals("Hello &amp;&lt;&gt; Å å π 新 there ¾ © »", escapedUtfMin); assertEquals(text, Entities.unescape(escapedAscii)); assertEquals(text, Entities.unescape(escapedAsciiFull)); assertEquals(text, Entities.unescape(escapedAsciiXhtml)); assertEquals(text, Entities.unescape(escapedUtfFull)); assertEquals(text, Entities.unescape(escapedUtfMin)); } @Test public void escapedSupplemtary() { String text = "\uD835\uDD59"; String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); assertEquals("&#x1d559;", escapedAscii); String escapedAsciiFull = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(extended)); assertEquals("&hopf;", escapedAsciiFull); String escapedUtf= Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(extended)); assertEquals(text, escapedUtf); } @Test public void escapeSupplementaryCharacter() { String text = new String(Character.toChars(135361)); String escapedAscii = Entities.escape(text, new OutputSettings().charset("ascii").escapeMode(base)); assertEquals("&#x210c1;", escapedAscii); String escapedUtf = Entities.escape(text, new OutputSettings().charset("UTF-8").escapeMode(base)); assertEquals(text, escapedUtf); } @Test public void caseSensitive() { String unescaped = "Ü ü & &"; assertEquals("&Uuml; &uuml; &amp; &amp;", Entities.escape(unescaped, new OutputSettings().charset("ascii").escapeMode(extended))); String escaped = "&Uuml; &uuml; &amp; &AMP"; assertEquals("Ü ü & &", Entities.unescape(escaped)); }
### Question: Entities { public static String getByName(String name) { String val = multipoints.get(name); if (val != null) return val; int codepoint = extended.codepointForName(name); if (codepoint != empty) return new String(new int[]{codepoint}, 0, 1); return emptyName; } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); }### Answer: @Test public void getByName() { assertEquals("≫⃒", Entities.getByName("nGt")); assertEquals("fj", Entities.getByName("fjlig")); assertEquals("≫", Entities.getByName("gg")); assertEquals("©", Entities.getByName("copy")); }
### Question: Entities { static String unescape(String string) { return unescape(string, false); } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); }### Answer: @Test public void notMissingMultis() { String text = "&nparsl;"; String un = "\u2AFD\u20E5"; assertEquals(un, Entities.unescape(text)); } @Test public void notMissingSupplementals() { String text = "&npolint; &qfr;"; String un = "⨔ \uD835\uDD2E"; assertEquals(un, Entities.unescape(text)); } @Test public void unescape() { String text = "Hello &AElig; &amp;&LT&gt; &reg &angst; &angst &#960; &#960 &#x65B0; there &! &frac34; &copy; &COPY;"; assertEquals("Hello Æ &<> ® Å &angst π π 新 there &! ¾ © ©", Entities.unescape(text)); assertEquals("&0987654321; &unknown", Entities.unescape("&0987654321; &unknown")); } @Test public void strictUnescape() { String text = "Hello &amp= &amp;"; assertEquals("Hello &amp= &", Entities.unescape(text, true)); assertEquals("Hello &= &", Entities.unescape(text)); assertEquals("Hello &= &", Entities.unescape(text, false)); } @Test public void quoteReplacements() { String escaped = "&#92; &#36;"; String unescaped = "\\ $"; assertEquals(unescaped, Entities.unescape(escaped)); } @Test public void noSpuriousDecodes() { String string = "http: assertEquals(string, Entities.unescape(string)); }
### Question: StringArrayToStringFunction implements GetterFunction<String[], String> { @Nullable @Override public String apply(@Nullable String[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable String[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new String[]{"1", "2", "3"}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new String[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: StringToStringArrayFunction implements SetterFunction<String, String[]> { @Nullable @Override public String[] apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new String[0]; } return input.split(SEPARATOR); } @Nullable @Override String[] apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", String[].class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new String[]{"1", "2", "3"}))); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new String[]{}))); }
### Question: IntArrayToStringFunction implements GetterFunction<int[], String> { @Nullable @Override public String apply(@Nullable int[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable int[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new int[]{1, 2, 3}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new int[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { public final Class<? super T> getRawType() { Class<?> rawType = getRawType(runtimeType); @SuppressWarnings("unchecked") Class<? super T> result = (Class<? super T>) rawType; return result; } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testGetRawType() throws Exception { TypeToken<List<String>> token = new TypeToken<List<String>>() { }; assertThat(token.getRawType().equals(List.class), is(true)); TypeToken<String> token2 = new TypeToken<String>() { }; assertThat(token2.getRawType().equals(String.class), is(true)); }
### Question: Cleaner { public boolean isValidBodyHtml(String bodyHtml) { Document clean = Document.createShell(""); Document dirty = Document.createShell(""); ParseErrorList errorList = ParseErrorList.tracking(1); List<Node> nodes = Parser.parseFragment(bodyHtml, dirty.body(), "", errorList); dirty.body().insertChildren(0, nodes); int numDiscarded = copySafeNodes(dirty.body(), clean.body()); return numDiscarded == 0 && errorList.size() == 0; } Cleaner(Whitelist whitelist); Document clean(Document dirtyDocument); boolean isValid(Document dirtyDocument); boolean isValidBodyHtml(String bodyHtml); }### Answer: @Test public void testIsValidBodyHtml() { String ok = "<p>Test <b><a href='http: String ok1 = "<p>Test <b><a href='http: String nok1 = "<p><script></script>Not <b>OK</b></p>"; String nok2 = "<p align=right>Test Not <b>OK</b></p>"; String nok3 = "<!-- comment --><p>Not OK</p>"; String nok4 = "<html><head>Foo</head><body><b>OK</b></body></html>"; String nok5 = "<p>Test <b><a href='http: String nok6 = "<p>Test <b><a href='http: String nok7 = "</div>What"; assertTrue(Jsoup.isValid(ok, Whitelist.basic())); assertTrue(Jsoup.isValid(ok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok2, Whitelist.basic())); assertFalse(Jsoup.isValid(nok3, Whitelist.basic())); assertFalse(Jsoup.isValid(nok4, Whitelist.basic())); assertFalse(Jsoup.isValid(nok5, Whitelist.basic())); assertFalse(Jsoup.isValid(nok6, Whitelist.basic())); assertFalse(Jsoup.isValid(ok, Whitelist.none())); assertFalse(Jsoup.isValid(nok7, Whitelist.basic())); }
### Question: Cleaner { public boolean isValid(Document dirtyDocument) { Validate.notNull(dirtyDocument); Document clean = Document.createShell(dirtyDocument.baseUri()); int numDiscarded = copySafeNodes(dirtyDocument.body(), clean.body()); return numDiscarded == 0 && dirtyDocument.head().childNodes().size() == 0; } Cleaner(Whitelist whitelist); Document clean(Document dirtyDocument); boolean isValid(Document dirtyDocument); boolean isValidBodyHtml(String bodyHtml); }### Answer: @Test public void testIsValidDocument() { String ok = "<html><head></head><body><p>Hello</p></body><html>"; String nok = "<html><head><script>woops</script><title>Hello</title></head><body><p>Hello</p></body><html>"; Whitelist relaxed = Whitelist.relaxed(); Cleaner cleaner = new Cleaner(relaxed); Document okDoc = Jsoup.parse(ok); assertTrue(cleaner.isValid(okDoc)); assertFalse(cleaner.isValid(Jsoup.parse(nok))); assertFalse(new Cleaner(Whitelist.none()).isValid(okDoc)); } @Test public void testScriptTagInWhiteList() { Whitelist whitelist = Whitelist.relaxed(); whitelist.addTags( "script" ); assertTrue( Jsoup.isValid("Hello<script>alert('Doh')</script>World !", whitelist ) ); }
### Question: StringToIntegerListFunction implements SetterFunction<String, List<Integer>> { @Nullable @Override public List<Integer> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<Integer>(); } String[] ss = input.split(SEPARATOR); List<Integer> r = new ArrayList<Integer>(); for (int i = 0; i < ss.length; i++) { r.add(Integer.parseInt(ss[i])); } return r; } @Nullable @Override List<Integer> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); List<Integer> list = Lists.newArrayList(1, 2, 3); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<Integer>().toString())); }
### Question: CharacterReader { char consume() { bufferUp(); char val = isEmpty() ? EOF : charBuf[bufPos]; bufPos++; return val; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consume() { CharacterReader r = new CharacterReader("one"); assertEquals(0, r.pos()); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals(1, r.pos()); assertEquals('n', r.current()); assertEquals(1, r.pos()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); }
### Question: CharacterReader { void unconsume() { bufPos--; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void unconsume() { CharacterReader r = new CharacterReader("one"); assertEquals('o', r.consume()); assertEquals('n', r.current()); r.unconsume(); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.unconsume(); assertFalse(r.isEmpty()); assertEquals('e', r.current()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); r.unconsume(); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.current()); }
### Question: CharacterReader { void mark() { bufMark = bufPos; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void mark() { CharacterReader r = new CharacterReader("one"); r.consume(); r.mark(); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.rewindToMark(); assertEquals('n', r.consume()); }
### Question: CharacterReader { String consumeToEnd() { bufferUp(); String data = cacheString(charBuf, stringCache, bufPos, bufLength - bufPos); bufPos = bufLength; return data; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeToEnd() { String in = "one two three"; CharacterReader r = new CharacterReader(in); String toEnd = r.consumeToEnd(); assertEquals(in, toEnd); assertTrue(r.isEmpty()); }
### Question: CharacterReader { int nextIndexOf(char c) { bufferUp(); for (int i = bufPos; i < bufLength; i++) { if (c == charBuf[i]) return i - bufPos; } return -1; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void nextIndexOfUnmatched() { CharacterReader r = new CharacterReader("<[[one]]"); assertEquals(-1, r.nextIndexOf("]]>")); }
### Question: StringToLongListFunction implements SetterFunction<String, List<Long>> { @Nullable @Override public List<Long> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<Long>(); } String[] ss = input.split(SEPARATOR); List<Long> r = new ArrayList<Long>(); for (int i = 0; i < ss.length; i++) { r.add(Long.parseLong(ss[i])); } return r; } @Nullable @Override List<Long> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "100000000000000000,2,3"); List<Long> list = Lists.newArrayList(100000000000000000L, 2L, 3L); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<Long>().toString())); }
### Question: CharacterReader { public void advance() { bufPos++; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void advance() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals('O', r.consume()); r.advance(); assertEquals('e', r.consume()); }
### Question: CharacterReader { public String consumeToAny(final char... chars) { bufferUp(); final int start = bufPos; final int remaining = bufLength; final char[] val = charBuf; OUTER: while (bufPos < remaining) { for (char c : chars) { if (val[bufPos] == c) break OUTER; } bufPos++; } return bufPos > start ? cacheString(charBuf, stringCache, start, bufPos -start) : ""; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeToAny() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One ", r.consumeToAny('&', ';')); assertTrue(r.matches('&')); assertTrue(r.matches("&bar;")); assertEquals('&', r.consume()); assertEquals("bar", r.consumeToAny('&', ';')); assertEquals(';', r.consume()); assertEquals(" qux", r.consumeToAny('&', ';')); }
### Question: CharacterReader { String consumeLetterSequence() { bufferUp(); int start = bufPos; while (bufPos < bufLength) { char c = charBuf[bufPos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)) bufPos++; else break; } return cacheString(charBuf, stringCache, start, bufPos - start); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeLetterSequence() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One", r.consumeLetterSequence()); assertEquals(" &", r.consumeTo("bar;")); assertEquals("bar", r.consumeLetterSequence()); assertEquals("; qux", r.consumeToEnd()); }
### Question: CharacterReader { String consumeLetterThenDigitSequence() { bufferUp(); int start = bufPos; while (bufPos < bufLength) { char c = charBuf[bufPos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)) bufPos++; else break; } while (!isEmpty()) { char c = charBuf[bufPos]; if (c >= '0' && c <= '9') bufPos++; else break; } return cacheString(charBuf, stringCache, start, bufPos - start); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeLetterThenDigitSequence() { CharacterReader r = new CharacterReader("One12 Two &bar; qux"); assertEquals("One12", r.consumeLetterThenDigitSequence()); assertEquals(' ', r.consume()); assertEquals("Two", r.consumeLetterThenDigitSequence()); assertEquals(" &bar; qux", r.consumeToEnd()); }
### Question: CharacterReader { boolean matches(char c) { return !isEmpty() && charBuf[bufPos] == c; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matches() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matches('O')); assertTrue(r.matches("One Two Three")); assertTrue(r.matches("One")); assertFalse(r.matches("one")); assertEquals('O', r.consume()); assertFalse(r.matches("One")); assertTrue(r.matches("ne Two Three")); assertFalse(r.matches("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matches("ne")); assertTrue(r.isEmpty()); }
### Question: CharacterReader { boolean matchesIgnoreCase(String seq) { bufferUp(); int scanLength = seq.length(); if (scanLength > bufLength - bufPos) return false; for (int offset = 0; offset < scanLength; offset++) { char upScan = Character.toUpperCase(seq.charAt(offset)); char upTarget = Character.toUpperCase(charBuf[bufPos + offset]); if (upScan != upTarget) return false; } return true; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matchesIgnoreCase() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matchesIgnoreCase("O")); assertTrue(r.matchesIgnoreCase("o")); assertTrue(r.matches('O')); assertFalse(r.matches('o')); assertTrue(r.matchesIgnoreCase("One Two Three")); assertTrue(r.matchesIgnoreCase("ONE two THREE")); assertTrue(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("one")); assertEquals('O', r.consume()); assertFalse(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("NE Two Three")); assertFalse(r.matchesIgnoreCase("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matchesIgnoreCase("ne")); }
### Question: CharacterReader { boolean containsIgnoreCase(String seq) { String loScan = seq.toLowerCase(Locale.ENGLISH); String hiScan = seq.toUpperCase(Locale.ENGLISH); return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void containsIgnoreCase() { CharacterReader r = new CharacterReader("One TWO three"); assertTrue(r.containsIgnoreCase("two")); assertTrue(r.containsIgnoreCase("three")); assertFalse(r.containsIgnoreCase("one")); }
### Question: CharacterReader { boolean matchesAny(char... seq) { if (isEmpty()) return false; bufferUp(); char c = charBuf[bufPos]; for (char seek : seq) { if (seek == c) return true; } return false; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matchesAny() { char[] scan = {' ', '\n', '\t'}; CharacterReader r = new CharacterReader("One\nTwo\tThree"); assertFalse(r.matchesAny(scan)); assertEquals("One", r.consumeToAny(scan)); assertTrue(r.matchesAny(scan)); assertEquals('\n', r.consume()); assertFalse(r.matchesAny(scan)); }
### Question: CharacterReader { static boolean rangeEquals(final char[] charBuf, final int start, int count, final String cached) { if (count == cached.length()) { int i = start; int j = 0; while (count-- != 0) { if (charBuf[i++] != cached.charAt(j++)) return false; } return true; } return false; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void rangeEquals() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE"); assertTrue(r.rangeEquals(0, 5, "Check")); assertFalse(r.rangeEquals(0, 5, "CHOKE")); assertFalse(r.rangeEquals(0, 5, "Chec")); assertTrue(r.rangeEquals(6, 5, "Check")); assertFalse(r.rangeEquals(6, 5, "Chuck")); assertTrue(r.rangeEquals(12, 5, "Check")); assertFalse(r.rangeEquals(12, 5, "Cheeky")); assertTrue(r.rangeEquals(18, 5, "CHOKE")); assertFalse(r.rangeEquals(18, 5, "CHIKE")); }
### Question: TokenQueue { 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; last = c; } while (depth > 0); final String out = (end >= 0) ? queue.substring(start, end) : ""; if (depth > 0) { Validate.fail("Did not find balanced marker at '" + out + "'"); } return out; } TokenQueue(String data); boolean isEmpty(); char peek(); void addFirst(Character c); void addFirst(String seq); boolean matches(String seq); boolean matchesCS(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchesStartTag(); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); void advance(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToIgnoreCase(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompToIgnoreCase(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeWord(); String consumeTagName(); String consumeElementSelector(); String consumeCssIdentifier(); String consumeAttributeKey(); String remainder(); @Override String toString(); }### Answer: @Test public void chompBalanced() { TokenQueue tq = new TokenQueue(":contains(one (two) three) four"); String pre = tq.consumeTo("("); String guts = tq.chompBalanced('(', ')'); String remainder = tq.remainder(); assertEquals(":contains", pre); assertEquals("one (two) three", guts); assertEquals(" four", remainder); }
### Question: LongArrayToStringFunction implements GetterFunction<long[], String> { @Nullable @Override public String apply(@Nullable long[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable long[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new long[]{1, 2, 3}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new long[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: TokenQueue { public static String unescape(String in) { StringBuilder out = StringUtil.stringBuilder(); char last = 0; for (char c : in.toCharArray()) { if (c == ESC) { if (last != 0 && last == ESC) out.append(c); } else out.append(c); last = c; } return out.toString(); } TokenQueue(String data); boolean isEmpty(); char peek(); void addFirst(Character c); void addFirst(String seq); boolean matches(String seq); boolean matchesCS(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchesStartTag(); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); void advance(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToIgnoreCase(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompToIgnoreCase(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeWord(); String consumeTagName(); String consumeElementSelector(); String consumeCssIdentifier(); String consumeAttributeKey(); String remainder(); @Override String toString(); }### Answer: @Test public void unescape() { assertEquals("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\")); }
### Question: LongListToStringFunction implements GetterFunction<List<Long>, String> { @Nullable @Override public String apply(@Nullable List<Long> input) { if (input == null) { return null; } if (input.size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input.get(0)); for (int i = 1; i < input.size(); i++) { builder.append(SEPARATOR).append(input.get(i)); } return builder.toString(); } @Nullable @Override String apply(@Nullable List<Long> input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(Lists.newArrayList(1000000000000000L, 2l, 3L)); assertThat((String) invoker.invoke(a), is("1000000000000000,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new ArrayList<Long>()); assertThat((String) invoker.invoke(a), is("")); }
### Question: Tag { public static Tag valueOf(String tagName, ParseSettings settings) { Validate.notNull(tagName); Tag tag = tags.get(tagName); if (tag == null) { tagName = settings.normalizeTag(tagName); Validate.notEmpty(tagName); tag = tags.get(tagName); if (tag == null) { tag = new Tag(tagName); tag.isBlock = false; } } return tag; } private Tag(String tagName); String getName(); static Tag valueOf(String tagName, ParseSettings settings); static Tag valueOf(String tagName); boolean isBlock(); boolean formatAsBlock(); boolean canContainBlock(); boolean isInline(); boolean isData(); boolean isEmpty(); boolean isSelfClosing(); boolean isKnownTag(); static boolean isKnownTag(String tagName); boolean preserveWhitespace(); boolean isFormListed(); boolean isFormSubmittable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test @MultiLocaleTest public void canBeInsensitive() { Tag script1 = Tag.valueOf("script", ParseSettings.htmlDefault); Tag script2 = Tag.valueOf("SCRIPT", ParseSettings.htmlDefault); assertSame(script1, script2); } @Test public void trims() { Tag p1 = Tag.valueOf("p"); Tag p2 = Tag.valueOf(" p "); assertEquals(p1, p2); } @Test(expected = IllegalArgumentException.class) public void valueOfChecksNotNull() { Tag.valueOf(null); } @Test(expected = IllegalArgumentException.class) public void valueOfChecksNotEmpty() { Tag.valueOf(" "); }
### Question: StringToStringListFunction implements SetterFunction<String, List<String>> { @Nullable @Override public List<String> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<String>(); } String[] ss = input.split(SEPARATOR); List<String> r = new ArrayList<String>(); for (int i = 0; i < ss.length; i++) { r.add(ss[i]); } return r; } @Nullable @Override List<String> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); List<String> list = Lists.newArrayList("1", "2", "3"); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<String>().toString())); }
### Question: HttpConnection implements Connection { public Connection headers(Map<String,String> headers) { Validate.notNull(headers, "Header map must not be null"); for (Map.Entry<String,String> entry : headers.entrySet()) { req.header(entry.getKey(),entry.getValue()); } return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void headers() { Connection con = HttpConnection.connect("http: Map<String, String> headers = new HashMap<String, String>(); headers.put("content-type", "text/html"); headers.put("Connection", "keep-alive"); headers.put("Host", "http: con.headers(headers); assertEquals("text/html", con.request().header("content-type")); assertEquals("keep-alive", con.request().header("Connection")); assertEquals("http: }
### Question: HttpConnection implements Connection { public Connection header(String name, String value) { req.header(name, value); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void sameHeadersCombineWithComma() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("no-cache"); values.add("no-store"); headers.put("Cache-Control", values); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals("no-cache, no-store", res.header("Cache-Control")); }
### Question: HttpConnection implements Connection { public Connection cookies(Map<String, String> cookies) { Validate.notNull(cookies, "Cookie map must not be null"); for (Map.Entry<String, String> entry : cookies.entrySet()) { req.cookie(entry.getKey(), entry.getValue()); } return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void ignoresEmptySetCookies() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Set-Cookie", Collections.<String>emptyList()); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(0, res.cookies().size()); }
### Question: HttpConnection implements Connection { public static Connection connect(String url) { Connection con = new HttpConnection(); con.url(url); return con; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); }
### Question: HttpConnection implements Connection { public Connection userAgent(String userAgent) { Validate.notNull(userAgent, "User agent must not be null"); req.header(USER_AGENT, userAgent); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void userAgent() { Connection con = HttpConnection.connect("http: assertEquals(HttpConnection.DEFAULT_UA, con.request().header("User-Agent")); con.userAgent("Mozilla"); assertEquals("Mozilla", con.request().header("User-Agent")); }
### Question: HttpConnection implements Connection { public Connection timeout(int millis) { req.timeout(millis); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void timeout() { Connection con = HttpConnection.connect("http: assertEquals(30 * 1000, con.request().timeout()); con.timeout(1000); assertEquals(1000, con.request().timeout()); }
### Question: HttpConnection implements Connection { public Connection referrer(String referrer) { Validate.notNull(referrer, "Referrer must not be null"); req.header("Referer", referrer); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void referrer() { Connection con = HttpConnection.connect("http: con.referrer("http: assertEquals("http: }
### Question: HttpConnection implements Connection { public Connection method(Method method) { req.method(method); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void method() { Connection con = HttpConnection.connect("http: assertEquals(Connection.Method.GET, con.request().method()); con.method(Connection.Method.POST); assertEquals(Connection.Method.POST, con.request().method()); }
### Question: HttpConnection implements Connection { public Connection data(String key, String value) { req.data(KeyVal.create(key, value)); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void data() { Connection con = HttpConnection.connect("http: con.data("Name", "Val", "Foo", "bar"); Collection<Connection.KeyVal> values = con.request().data(); Object[] data = values.toArray(); Connection.KeyVal one = (Connection.KeyVal) data[0]; Connection.KeyVal two = (Connection.KeyVal) data[1]; assertEquals("Name", one.key()); assertEquals("Val", one.value()); assertEquals("Foo", two.key()); assertEquals("bar", two.value()); }
### Question: IntegerListToStringFunction implements GetterFunction<List<Integer>, String> { @Nullable @Override public String apply(@Nullable List<Integer> input) { if (input == null) { return null; } if (input.size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input.get(0)); for (int i = 1; i < input.size(); i++) { builder.append(SEPARATOR).append(input.get(i)); } return builder.toString(); } @Nullable @Override String apply(@Nullable List<Integer> input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(Lists.newArrayList(1, 2, 3)); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new ArrayList<Integer>()); assertThat((String) invoker.invoke(a), is("")); }
### Question: HttpConnection implements Connection { public Connection cookie(String name, String value) { req.cookie(name, value); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void cookie() { Connection con = HttpConnection.connect("http: con.cookie("Name", "Val"); assertEquals("Val", con.request().cookie("Name")); }
### Question: HttpConnection implements Connection { public Connection requestBody(String body) { req.requestBody(body); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void requestBody() { Connection con = HttpConnection.connect("http: con.requestBody("foo"); assertEquals("foo", con.request().requestBody()); }
### Question: HttpConnection implements Connection { private static String encodeUrl(String url) { try { URL u = new URL(url); return encodeUrl(u).toExternalForm(); } catch (Exception e) { return url; } } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void encodeUrl() throws MalformedURLException { URL url1 = new URL("http: URL url2 = HttpConnection.encodeUrl(url1); assertEquals("http: }
### Question: StringUtil { public static String join(Collection strings, String sep) { return join(strings.iterator(), sep); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void join() { assertEquals("", StringUtil.join(Arrays.asList(""), " ")); assertEquals("one", StringUtil.join(Arrays.asList("one"), " ")); assertEquals("one two three", StringUtil.join(Arrays.asList("one", "two", "three"), " ")); }
### Question: StringUtil { public static String padding(int width) { if (width < 0) throw new IllegalArgumentException("width must be > 0"); if (width < padding.length) return padding[width]; char[] out = new char[width]; for (int i = 0; i < width; i++) out[i] = ' '; return String.valueOf(out); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void padding() { assertEquals("", StringUtil.padding(0)); assertEquals(" ", StringUtil.padding(1)); assertEquals(" ", StringUtil.padding(2)); assertEquals(" ", StringUtil.padding(15)); assertEquals(" ", StringUtil.padding(45)); }
### Question: StringUtil { public static boolean isBlank(String string) { if (string == null || string.length() == 0) return true; int l = string.length(); for (int i = 0; i < l; i++) { if (!StringUtil.isWhitespace(string.codePointAt(i))) return false; } return true; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isBlank() { assertTrue(StringUtil.isBlank(null)); assertTrue(StringUtil.isBlank("")); assertTrue(StringUtil.isBlank(" ")); assertTrue(StringUtil.isBlank(" \r\n ")); assertFalse(StringUtil.isBlank("hello")); assertFalse(StringUtil.isBlank(" hello ")); }
### Question: StringUtil { public static boolean isNumeric(String string) { if (string == null || string.length() == 0) return false; int l = string.length(); for (int i = 0; i < l; i++) { if (!Character.isDigit(string.codePointAt(i))) return false; } return true; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isNumeric() { assertFalse(StringUtil.isNumeric(null)); assertFalse(StringUtil.isNumeric(" ")); assertFalse(StringUtil.isNumeric("123 546")); assertFalse(StringUtil.isNumeric("hello")); assertFalse(StringUtil.isNumeric("123.334")); assertTrue(StringUtil.isNumeric("1")); assertTrue(StringUtil.isNumeric("1234")); }
### Question: StringUtil { public static boolean isWhitespace(int c){ return c == ' ' || c == '\t' || c == '\n' || c == '\f' || c == '\r'; } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void isWhitespace() { assertTrue(StringUtil.isWhitespace('\t')); assertTrue(StringUtil.isWhitespace('\n')); assertTrue(StringUtil.isWhitespace('\r')); assertTrue(StringUtil.isWhitespace('\f')); assertTrue(StringUtil.isWhitespace(' ')); assertFalse(StringUtil.isWhitespace('\u00a0')); assertFalse(StringUtil.isWhitespace('\u2000')); assertFalse(StringUtil.isWhitespace('\u3000')); }
### Question: StringUtil { public static String normaliseWhitespace(String string) { StringBuilder sb = StringUtil.stringBuilder(); appendNormalisedWhitespace(sb, string, false); return sb.toString(); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void normaliseWhiteSpace() { assertEquals(" ", normaliseWhitespace(" \r \n \r\n")); assertEquals(" hello there ", normaliseWhitespace(" hello \r \n there \n")); assertEquals("hello", normaliseWhitespace("hello")); assertEquals("hello there", normaliseWhitespace("hello\nthere")); } @Test public void normaliseWhiteSpaceHandlesHighSurrogates() { String test71540chars = "\ud869\udeb2\u304b\u309a 1"; String test71540charsExpectedSingleWhitespace = "\ud869\udeb2\u304b\u309a 1"; assertEquals(test71540charsExpectedSingleWhitespace, normaliseWhitespace(test71540chars)); String extractedText = Jsoup.parse(test71540chars).text(); assertEquals(test71540charsExpectedSingleWhitespace, extractedText); }
### Question: IntegerToEnumFunction implements RuntimeSetterFunction<Integer, Enum> { @Nullable @Override public Enum apply(@Nullable Integer input, Type runtimeOutputType) { if (input == null) { return null; } Class<?> rawType = TypeToken.of(runtimeOutputType).getRawType(); EnumSet<?> es = cache.get(rawType); for (Enum<?> e : es) { if (e.ordinal() == input) { return e; } } throw new IllegalStateException("cant' trans Integer(" + input + ") to " + runtimeOutputType); } @Nullable @Override Enum apply(@Nullable Integer input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setE", E.class); SetterInvoker invoker = FunctionalSetterInvoker.create("e", m); invoker.invoke(a, 2); assertThat(a.getE(), is(E.Z)); Method m2 = A.class.getDeclaredMethod("setE2", E2.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("e2", m2); invoker2.invoke(a, 2); assertThat(a.getE2(), is(E2.C)); }
### Question: StringUtil { public static URL resolve(URL base, String relUrl) throws MalformedURLException { if (relUrl.startsWith("?")) relUrl = base.getPath() + relUrl; if (relUrl.indexOf('.') == 0 && base.getFile().indexOf('/') != 0) { base = new URL(base.getProtocol(), base.getHost(), base.getPort(), "/" + base.getFile()); } return new URL(base, relUrl); } static String join(Collection strings, String sep); static String join(Iterator strings, String sep); static String padding(int width); static boolean isBlank(String string); static boolean isNumeric(String string); static boolean isWhitespace(int c); static boolean isActuallyWhitespace(int c); static String normaliseWhitespace(String string); static void appendNormalisedWhitespace(StringBuilder accum, String string, boolean stripLeading); static boolean in(String needle, String... haystack); static boolean inSorted(String needle, String[] haystack); static URL resolve(URL base, String relUrl); static String resolve(final String baseUrl, final String relUrl); static StringBuilder stringBuilder(); }### Answer: @Test public void resolvesRelativeUrls() { assertEquals("http: assertEquals("http: assertEquals("http: assertEquals("https: assertEquals("http: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("https: assertEquals("", resolve("wrong", "also wrong")); assertEquals("ftp: assertEquals("ftp: assertEquals("ftp: }
### Question: DataUtil { static String getCharsetFromContentType(String contentType) { if (contentType == null) return null; Matcher m = charsetPattern.matcher(contentType); if (m.find()) { String charset = m.group(1).trim(); charset = charset.replace("charset=", ""); return validateCharset(charset); } return null; } private DataUtil(); static Document load(File in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri, Parser parser); static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize); }### Answer: @Test public void testCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html;charset=utf-8 ")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset=UTF-8")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html")); assertEquals(null, DataUtil.getCharsetFromContentType(null)); assertEquals(null, DataUtil.getCharsetFromContentType("text/html;charset=Unknown")); } @Test public void testQuotedCharset() { assertEquals("utf-8", DataUtil.getCharsetFromContentType("text/html; charset=\"utf-8\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html;charset=\"UTF-8\"")); assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=\"ISO-8859-1\"")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=\"Unsupported\"")); assertEquals("UTF-8", DataUtil.getCharsetFromContentType("text/html; charset='UTF-8'")); } @Test public void shouldNotThrowExceptionOnEmptyCharset() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=")); assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=;")); } @Test public void shouldSelectFirstCharsetOnWeirdMultileCharsetsInMetaTags() { assertEquals("ISO-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=ISO-8859-1, charset=1251")); } @Test public void shouldCorrectCharsetForDuplicateCharsetString() { assertEquals("iso-8859-1", DataUtil.getCharsetFromContentType("text/html; charset=charset=iso-8859-1")); } @Test public void shouldReturnNullForIllegalCharsetNames() { assertEquals(null, DataUtil.getCharsetFromContentType("text/html; charset=$HJKDF§$/(")); }
### Question: StringToEnumFunction implements RuntimeSetterFunction<String, Enum> { @Nullable @Override public Enum apply(@Nullable String input, Type runtimeOutputType) { if (input == null) { return null; } Class rawType = TypeToken.of(runtimeOutputType).getRawType(); Enum r = Enum.valueOf(rawType, input); return r; } @Nullable @Override Enum apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setE", E.class); SetterInvoker invoker = FunctionalSetterInvoker.create("e", m); invoker.invoke(a, "Y"); assertThat(a.getE(), is(E.Y)); }
### Question: DataUtil { static String mimeBoundary() { final StringBuilder mime = new StringBuilder(boundaryLength); final Random rand = new Random(); for (int i = 0; i < boundaryLength; i++) { mime.append(mimeBoundaryChars[rand.nextInt(mimeBoundaryChars.length)]); } return mime.toString(); } private DataUtil(); static Document load(File in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri); static Document load(InputStream in, String charsetName, String baseUri, Parser parser); static ByteBuffer readToByteBuffer(InputStream inStream, int maxSize); }### Answer: @Test public void generatesMimeBoundaries() { String m1 = DataUtil.mimeBoundary(); String m2 = DataUtil.mimeBoundary(); assertEquals(DataUtil.boundaryLength, m1.length()); assertEquals(DataUtil.boundaryLength, m2.length()); assertNotSame(m1, m2); }
### Question: ClosureUtils { public static <E> Closure<E> exceptionClosure() { return ExceptionClosure.<E>exceptionClosure(); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testExceptionClosure() { assertNotNull(ClosureUtils.exceptionClosure()); assertSame(ClosureUtils.exceptionClosure(), ClosureUtils.exceptionClosure()); try { ClosureUtils.exceptionClosure().execute(null); } catch (final FunctorException ex) { try { ClosureUtils.exceptionClosure().execute(cString); } catch (final FunctorException ex2) { return; } } fail(); }
### Question: ClosureUtils { public static <E> Closure<E> nopClosure() { return NOPClosure.<E>nopClosure(); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testNopClosure() { final StringBuilder buf = new StringBuilder("Hello"); ClosureUtils.nopClosure().execute(null); assertEquals("Hello", buf.toString()); ClosureUtils.nopClosure().execute("Hello"); assertEquals("Hello", buf.toString()); }
### Question: ClosureUtils { public static <E> Closure<E> invokerClosure(final String methodName) { return asClosure(InvokerTransformer.<E, Object>invokerTransformer(methodName)); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testInvokeClosure() { StringBuffer buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("reverse").execute(buf); assertEquals("olleH", buf.toString()); buf = new StringBuffer("Hello"); ClosureUtils.invokerClosure("setLength", new Class[] {Integer.TYPE}, new Object[] {Integer.valueOf(2)}).execute(buf); assertEquals("He", buf.toString()); }
### Question: ClosureUtils { public static <E> Closure<E> forClosure(final int count, final Closure<? super E> closure) { return ForClosure.forClosure(count, closure); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testForClosure() { final MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.forClosure(5, cmd).execute(null); assertEquals(5, cmd.count); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(0, new MockClosure<Object>())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(-1, new MockClosure<Object>())); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(1, null)); assertSame(NOPClosure.INSTANCE, ClosureUtils.forClosure(3, null)); assertSame(cmd, ClosureUtils.forClosure(1, cmd)); }
### Question: ClosureUtils { public static <E> Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure) { return WhileClosure.<E>whileClosure(predicate, closure, false); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testWhileClosure() { MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), cmd).execute(null); assertEquals(0, cmd.count); cmd = new MockClosure<Object>(); ClosureUtils.whileClosure(PredicateUtils.uniquePredicate(), cmd).execute(null); assertEquals(1, cmd.count); try { ClosureUtils.whileClosure(null, ClosureUtils.nopClosure()); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.whileClosure(FalsePredicate.falsePredicate(), null); fail(); } catch (final NullPointerException ex) {} try { ClosureUtils.whileClosure(null, null); fail(); } catch (final NullPointerException ex) {} }
### Question: EnumToStringFunction implements GetterFunction<Enum, String> { @Nullable @Override public String apply(@Nullable Enum input) { return input == null ? null : input.name(); } @Nullable @Override String apply(@Nullable Enum input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); a.setE(E.Y); Method m = A.class.getDeclaredMethod("getE"); GetterInvoker invoker = FunctionalGetterInvoker.create("e", m); String r = (String) invoker.invoke(a); assertThat(r, is("Y")); }
### Question: ClosureUtils { public static <E> Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate) { return WhileClosure.<E>whileClosure(predicate, closure, true); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testDoWhileClosure() { MockClosure<Object> cmd = new MockClosure<Object>(); ClosureUtils.doWhileClosure(cmd, FalsePredicate.falsePredicate()).execute(null); assertEquals(1, cmd.count); cmd = new MockClosure<Object>(); ClosureUtils.doWhileClosure(cmd, PredicateUtils.uniquePredicate()).execute(null); assertEquals(2, cmd.count); try { ClosureUtils.doWhileClosure(null, null); fail(); } catch (final NullPointerException ex) {} }
### Question: ClosureUtils { public static <E> Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure) { return IfClosure.<E>ifClosure(predicate, trueClosure); } private ClosureUtils(); static Closure<E> exceptionClosure(); static Closure<E> nopClosure(); static Closure<E> asClosure(final Transformer<? super E, ?> transformer); static Closure<E> forClosure(final int count, final Closure<? super E> closure); static Closure<E> whileClosure(final Predicate<? super E> predicate, final Closure<? super E> closure); static Closure<E> doWhileClosure(final Closure<? super E> closure, final Predicate<? super E> predicate); static Closure<E> invokerClosure(final String methodName); static Closure<E> invokerClosure(final String methodName, final Class<?>[] paramTypes, final Object[] args); static Closure<E> chainedClosure(final Closure<? super E>... closures); static Closure<E> chainedClosure(final Collection<? extends Closure<? super E>> closures); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure); static Closure<E> ifClosure(final Predicate<? super E> predicate, final Closure<? super E> trueClosure, final Closure<? super E> falseClosure); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures); static Closure<E> switchClosure(final Predicate<? super E>[] predicates, final Closure<? super E>[] closures, final Closure<? super E> defaultClosure); static Closure<E> switchClosure(final Map<Predicate<E>, Closure<E>> predicatesAndClosures); @SuppressWarnings("unchecked") static Closure<E> switchMapClosure(final Map<? extends E, Closure<E>> objectsAndClosures); }### Answer: @Test public void testIfClosure() { MockClosure<Object> a = new MockClosure<Object>(); MockClosure<Object> b = null; ClosureUtils.ifClosure(TruePredicate.truePredicate(), a).execute(null); assertEquals(1, a.count); a = new MockClosure<Object>(); ClosureUtils.ifClosure(FalsePredicate.<Object>falsePredicate(), a).execute(null); assertEquals(0, a.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); ClosureUtils.ifClosure(TruePredicate.<Object>truePredicate(), a, b).execute(null); assertEquals(1, a.count); assertEquals(0, b.count); a = new MockClosure<Object>(); b = new MockClosure<Object>(); ClosureUtils.ifClosure(FalsePredicate.<Object>falsePredicate(), a, b).execute(null); assertEquals(0, a.count); assertEquals(1, b.count); }
### Question: ComparatorChain implements Comparator<E>, Serializable { @Override public int compare(final E o1, final E o2) throws UnsupportedOperationException { if (isLocked == false) { checkChainIntegrity(); isLocked = true; } final Iterator<Comparator<E>> comparators = comparatorChain.iterator(); for (int comparatorIndex = 0; comparators.hasNext(); ++comparatorIndex) { final Comparator<? super E> comparator = comparators.next(); int retval = comparator.compare(o1,o2); if (retval != 0) { if (orderingBits.get(comparatorIndex) == true) { if (retval > 0) { retval = -1; } else { retval = 1; } } return retval; } } return 0; } ComparatorChain(); ComparatorChain(final Comparator<E> comparator); ComparatorChain(final Comparator<E> comparator, final boolean reverse); ComparatorChain(final List<Comparator<E>> list); ComparatorChain(final List<Comparator<E>> list, final BitSet bits); void addComparator(final Comparator<E> comparator); void addComparator(final Comparator<E> comparator, final boolean reverse); void setComparator(final int index, final Comparator<E> comparator); void setComparator(final int index, final Comparator<E> comparator, final boolean reverse); void setForwardSort(final int index); void setReverseSort(final int index); int size(); boolean isLocked(); @Override int compare(final E o1, final E o2); @Override int hashCode(); @Override boolean equals(final Object object); }### Answer: @Test public void testBadNoopComparatorChain() { final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1,i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } } @Test public void testListComparatorChain() { final List<Comparator<Integer>> list = new LinkedList<Comparator<Integer>>(); list.add(new ComparableComparator<Integer>()); final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); final int correctValue = i1.compareTo(i2); assertTrue("Comparison returns the right order", chain.compare(i1, i2) == correctValue); } @Test public void testBadListComparatorChain() { final List<Comparator<Integer>> list = new LinkedList<Comparator<Integer>>(); final ComparatorChain<Integer> chain = new ComparatorChain<Integer>(list); final Integer i1 = Integer.valueOf(4); final Integer i2 = Integer.valueOf(6); try { chain.compare(i1, i2); fail("An exception should be thrown when a chain contains zero comparators."); } catch (final UnsupportedOperationException e) { } }
### Question: FixedOrderComparator implements Comparator<T>, Serializable { public boolean add(final T obj) { checkLocked(); final Integer position = map.put(obj, Integer.valueOf(counter++)); return position == null; } FixedOrderComparator(); FixedOrderComparator(final T... items); FixedOrderComparator(final List<T> items); boolean isLocked(); UnknownObjectBehavior getUnknownObjectBehavior(); void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); boolean add(final T obj); boolean addAsEqual(final T existingObj, final T newObj); @Override int compare(final T obj1, final T obj2); @Override int hashCode(); @Override boolean equals(final Object object); }### Answer: @Test public void testConstructorPlusAdd() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(); for (final String topCitie : topCities) { comparator.add(topCitie); } final String[] keys = topCities.clone(); assertComparatorYieldsOrder(keys, comparator); }
### Question: FixedOrderComparator implements Comparator<T>, Serializable { public boolean addAsEqual(final T existingObj, final T newObj) { checkLocked(); final Integer position = map.get(existingObj); if (position == null) { throw new IllegalArgumentException(existingObj + " not known to " + this); } final Integer result = map.put(newObj, position); return result == null; } FixedOrderComparator(); FixedOrderComparator(final T... items); FixedOrderComparator(final List<T> items); boolean isLocked(); UnknownObjectBehavior getUnknownObjectBehavior(); void setUnknownObjectBehavior(final UnknownObjectBehavior unknownObjectBehavior); boolean add(final T obj); boolean addAsEqual(final T existingObj, final T newObj); @Override int compare(final T obj1, final T obj2); @Override int hashCode(); @Override boolean equals(final Object object); }### Answer: @Test public void testAddAsEqual() { final FixedOrderComparator<String> comparator = new FixedOrderComparator<String>(topCities); comparator.addAsEqual("New York", "Minneapolis"); assertEquals(0, comparator.compare("New York", "Minneapolis")); assertEquals(-1, comparator.compare("Tokyo", "Minneapolis")); assertEquals(1, comparator.compare("Shanghai", "Minneapolis")); }
### Question: EnumToIntegerFunction implements GetterFunction<Enum, Integer> { @Nullable @Override public Integer apply(@Nullable Enum input) { return input == null ? null : input.ordinal(); } @Nullable @Override Integer apply(@Nullable Enum input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); a.setE(E.Y); Method m = A.class.getDeclaredMethod("getE"); GetterInvoker invoker = FunctionalGetterInvoker.create("e", m); Integer r = (Integer) invoker.invoke(a); assertThat(r, is(1)); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { public static <T> TypeToken<T> of(Class<T> type) { return new SimpleTypeToken<T>(type); } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testOf() throws Exception { TypeToken<String> token = TypeToken.of(String.class); assertThat(token.getType().equals(String.class), is(true)); assertThat(token.getRawType().equals(String.class), is(true)); }
### Question: SplitMapUtils { @SuppressWarnings("unchecked") public static <K, V> IterableMap<K, V> readableMap(final Get<K, V> get) { if (get == null) { throw new NullPointerException("Get must not be null"); } if (get instanceof Map) { return get instanceof IterableMap ? ((IterableMap<K, V>) get) : MapUtils.iterableMap((Map<K, V>) get); } return new WrappedGet<K, V>(get); } private SplitMapUtils(); @SuppressWarnings("unchecked") static IterableMap<K, V> readableMap(final Get<K, V> get); @SuppressWarnings("unchecked") static Map<K, V> writableMap(final Put<K, V> put); }### Answer: @Test public void testReadableMap() { final IterableMap<String, Integer> map = SplitMapUtils.readableMap(transformedMap); for (int i = 0; i < 10; i++) { assertFalse(map.containsValue(String.valueOf(i))); assertEquals(i, map.get(String.valueOf(i)).intValue()); } final MapIterator<String, Integer> it = map.mapIterator(); while (it.hasNext()) { final String k = it.next(); assertEquals(k, it.getKey()); assertEquals(Integer.valueOf(k), it.getValue()); } assertTrue(map instanceof Unmodifiable); int sz = map.size(); attemptPutOperation(new Runnable() { public void run() { map.clear(); } }); assertEquals(sz, map.size()); attemptPutOperation(new Runnable() { public void run() { map.put("foo", 100); } }); final HashMap<String, Integer> m = new HashMap<String, Integer>(); m.put("foo", 100); m.put("bar", 200); m.put("baz", 300); attemptPutOperation(new Runnable() { public void run() { map.putAll(m); } }); final IterableMap<String, Integer> other = SplitMapUtils.readableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); for (int i = 0; i < 10; i++) { assertEquals(i, map.remove(String.valueOf(i)).intValue()); assertEquals(--sz, map.size()); } assertTrue(map.isEmpty()); assertSame(map, SplitMapUtils.readableMap(map)); } @Test public void testAlreadyReadableMap() { final HashedMap<String, Integer> hashedMap = new HashedMap<String, Integer>(); assertSame(hashedMap, SplitMapUtils.readableMap(hashedMap)); }
### Question: SplitMapUtils { @SuppressWarnings("unchecked") public static <K, V> Map<K, V> writableMap(final Put<K, V> put) { if (put == null) { throw new NullPointerException("Put must not be null"); } if (put instanceof Map) { return (Map<K, V>) put; } return new WrappedPut<K, V>(put); } private SplitMapUtils(); @SuppressWarnings("unchecked") static IterableMap<K, V> readableMap(final Get<K, V> get); @SuppressWarnings("unchecked") static Map<K, V> writableMap(final Put<K, V> put); }### Answer: @Test @SuppressWarnings("unchecked") public void testWritableMap() { final Map<String, String> map = SplitMapUtils.writableMap(transformedMap); attemptGetOperation(new Runnable() { public void run() { map.get(null); } }); attemptGetOperation(new Runnable() { public void run() { map.entrySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.keySet(); } }); attemptGetOperation(new Runnable() { public void run() { map.values(); } }); attemptGetOperation(new Runnable() { public void run() { map.size(); } }); attemptGetOperation(new Runnable() { public void run() { map.isEmpty(); } }); attemptGetOperation(new Runnable() { public void run() { map.containsKey(null); } }); attemptGetOperation(new Runnable() { public void run() { map.containsValue(null); } }); attemptGetOperation(new Runnable() { public void run() { map.remove(null); } }); final Map<String, String> other = SplitMapUtils.writableMap(transformedMap); assertEquals(other, map); assertEquals(other.hashCode(), map.hashCode()); int sz = backingMap.size(); assertFalse(backingMap.containsKey("foo")); map.put("new", "66"); assertEquals(++sz, backingMap.size()); final Map<String, String> more = new HashMap<String, String>(); more.put("foo", "77"); more.put("bar", "88"); more.put("baz", "99"); map.putAll(more); assertEquals(sz + more.size(), backingMap.size()); map.clear(); assertTrue(backingMap.isEmpty()); assertSame(map, SplitMapUtils.writableMap((Put<String, String>) map)); } @Test public void testAlreadyWritableMap() { final HashedMap<String, String> hashedMap = new HashedMap<String, String>(); assertSame(hashedMap, SplitMapUtils.writableMap(hashedMap)); }
### Question: BagUtils { public static <E> Bag<E> synchronizedBag(final Bag<E> bag) { return SynchronizedBag.synchronizedBag(bag); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testSynchronizedBag() { Bag<Object> bag = BagUtils.synchronizedBag(new HashBag<Object>()); assertTrue("Returned object should be a SynchronizedBag.", bag instanceof SynchronizedBag); try { BagUtils.synchronizedBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } }
### Question: BagUtils { public static <E> Bag<E> unmodifiableBag(final Bag<? extends E> bag) { return UnmodifiableBag.unmodifiableBag(bag); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testUnmodifiableBag() { Bag<Object> bag = BagUtils.unmodifiableBag(new HashBag<Object>()); assertTrue("Returned object should be an UnmodifiableBag.", bag instanceof UnmodifiableBag); try { BagUtils.unmodifiableBag(null); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } assertSame("UnmodifiableBag shall not be decorated", bag, BagUtils.unmodifiableBag(bag)); }
### Question: BagUtils { public static <E> Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate) { return PredicatedBag.predicatedBag(bag, predicate); } private BagUtils(); static Bag<E> synchronizedBag(final Bag<E> bag); static Bag<E> unmodifiableBag(final Bag<? extends E> bag); static Bag<E> predicatedBag(final Bag<E> bag, final Predicate<? super E> predicate); static Bag<E> transformingBag(final Bag<E> bag, final Transformer<? super E, ? extends E> transformer); static Bag<E> collectionBag(final Bag<E> bag); static SortedBag<E> synchronizedSortedBag(final SortedBag<E> bag); static SortedBag<E> unmodifiableSortedBag(final SortedBag<E> bag); static SortedBag<E> predicatedSortedBag(final SortedBag<E> bag, final Predicate<? super E> predicate); static SortedBag<E> transformingSortedBag(final SortedBag<E> bag, final Transformer<? super E, ? extends E> transformer); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static Bag<E> emptyBag(); @SuppressWarnings("unchecked") // OK, empty bag is compatible with any type static SortedBag<E> emptySortedBag(); @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_BAG; @SuppressWarnings("rawtypes") // OK, empty bag is compatible with any type static final Bag EMPTY_SORTED_BAG; }### Answer: @Test public void testPredicatedBag() { Bag<Object> bag = BagUtils.predicatedBag(new HashBag<Object>(), truePredicate); assertTrue("Returned object should be a PredicatedBag.", bag instanceof PredicatedBag); try { BagUtils.predicatedBag(null,truePredicate); fail("Expecting NullPointerException for null bag."); } catch (final NullPointerException ex) { } try { BagUtils.predicatedBag(new HashBag<Object>(), null); fail("Expecting NullPointerException for null predicate."); } catch (final NullPointerException ex) { } }