src_fm_fc_ms_ff
stringlengths
43
86.8k
target
stringlengths
20
276k
ClosedOutputStream extends OutputStream { @Override public void write(final int b) throws IOException { throw new IOException("write(" + b + ") failed: stream is closed"); } @Override void write(final int b); static final ClosedOutputStream CLOSED_OUTPUT_STREAM; }
@Test public void testRead() throws Exception { ClosedOutputStream cos = null; try { cos = new ClosedOutputStream(); cos.write('x'); fail("write(b)"); } catch (final IOException e) { } finally { cos.close(); } }
ProxyOutputStream extends FilterOutputStream { @Override public void write(final int idx) throws IOException { try { beforeWrite(1); out.write(idx); afterWrite(1); } catch (final IOException e) { handleIOException(e); } } ProxyOutputStream(final OutputStream proxy); @Override void write(final int idx); @Override void w...
@Test public void testWrite() throws Exception { proxied.write('y'); assertEquals(1, original.size()); assertEquals('y', original.toByteArray()[0]); } @Test public void testWriteNullBaSucceeds() throws Exception { final byte[] ba = null; original.write(ba); proxied.write(ba); }
TeeOutputStream extends ProxyOutputStream { @Override public void close() throws IOException { try { super.close(); } finally { this.branch.close(); } } TeeOutputStream(final OutputStream out, final OutputStream branch); @Override synchronized void write(final byte[] b); @Override synchronized void write(final byte[] b...
@Test public void testCloseBranchIOException() { final ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream(); final RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream(); final TeeOutputStream tos = new TeeOutputStream(goodOs, badOs); try { tos.close(); Assert.fail("Expect...
NullOutputStream extends OutputStream { @Override public void write(final byte[] b, final int off, final int len) { } @Override void write(final byte[] b, final int off, final int len); @Override void write(final int b); @Override void write(final byte[] b); static final NullOutputStream NULL_OUTPUT_STREAM; }
@Test public void testNull() throws IOException { final NullOutputStream nos = new NullOutputStream(); nos.write("string".getBytes()); nos.write("some string".getBytes(), 3, 5); nos.write(1); nos.write(0x0f); nos.flush(); nos.close(); nos.write("allowed".getBytes()); nos.write(255); }
ThresholdingOutputStream extends OutputStream { protected void setByteCount(final long count) { this.written = count; } ThresholdingOutputStream(final int threshold); @Override void write(final int b); @Override void write(final byte b[]); @Override void write(final byte b[], final int off, final int len); @Override vo...
@Test public void testSetByteCount() throws Exception { final AtomicBoolean reached = new AtomicBoolean(false); ThresholdingOutputStream tos = new ThresholdingOutputStream(3) { { setByteCount(2); } @Override protected OutputStream getStream() throws IOException { return new ByteArrayOutputStream(4); } @Override protect...
TaggedIOException extends IOExceptionWithCause { public TaggedIOException(final IOException original, final Serializable tag) { super(original.getMessage(), original); this.tag = tag; } TaggedIOException(final IOException original, final Serializable tag); static boolean isTaggedWith(final Throwable throwable, final Ob...
@Test public void testTaggedIOException() { final Serializable tag = UUID.randomUUID(); final IOException exception = new IOException("Test exception"); final TaggedIOException tagged = new TaggedIOException(exception, tag); assertTrue(TaggedIOException.isTaggedWith(tagged, tag)); assertFalse(TaggedIOException.isTagged...
CopyUtils { public static void copy(final byte[] input, final OutputStream output) throws IOException { output.write(input); } CopyUtils(); static void copy(final byte[] input, final OutputStream output); @Deprecated static void copy(final byte[] input, final Writer output); static void copy( final byte[] i...
@Test public void copy_byteArrayToOutputStream() throws Exception { final ByteArrayOutputStream baout = new ByteArrayOutputStream(); final OutputStream out = new YellOnFlushAndCloseOutputStream(baout, false, true); CopyUtils.copy(inData, out); assertEquals("Sizes differ", inData.length, baout.size()); assertTrue("Conte...
BlobByteObjectArrayTypeHandler extends BaseTypeHandler<Byte[]> { private Byte[] getBytes(Blob blob) throws SQLException { Byte[] returnValue = null; if (blob != null) { returnValue = ByteArrayUtils.convertToObjectArray(blob.getBytes(1, (int) blob.length())); } return returnValue; } @Override void setNonNullParameter(P...
@Override @Test public void shouldGetResultFromResultSetByPosition() throws Exception { byte[] byteArray = new byte[]{1, 2}; when(rs.getBlob(1)).thenReturn(blob); when(rs.wasNull()).thenReturn(false); when(blob.length()).thenReturn((long)byteArray.length); when(blob.getBytes(1, 2)).thenReturn(byteArray); assertThat(TYP...
FunctionalSetterInvoker extends MethodNamedObject implements SetterInvoker { public static FunctionalSetterInvoker create(String name, Method method) { return new FunctionalSetterInvoker(name, method); } private FunctionalSetterInvoker(String name, Method method); static FunctionalSetterInvoker create(String name, Met...
@Test public void testException() throws Exception { thrown.expect(ClassCastException.class); thrown.expectMessage("function[class org.jfaster.mango.invoker.FunctionalSetterInvokerTest$StringToIntegerFunction] on method[void org.jfaster.mango.invoker.FunctionalSetterInvokerTest$E.setX(java.lang.String)] error, method's...
FunctionalGetterInvoker extends MethodNamedObject implements GetterInvoker { public static FunctionalGetterInvoker create(String name, Method method) { return new FunctionalGetterInvoker(name, method); } private FunctionalGetterInvoker(String name, Method method); static FunctionalGetterInvoker create(String name, Met...
@Test public void testException() throws Exception { thrown.expect(ClassCastException.class); thrown.expectMessage("function[class org.jfaster.mango.invoker.FunctionalGetterInvokerTest$IntegerToStringFunction] on method[java.lang.String org.jfaster.mango.invoker.FunctionalGetterInvokerTest$E.getX()] error, function's i...
TypeToken extends TypeCapture<T> implements Serializable { public final Type getType() { return runtimeType; } 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> wh...
@Test public void testGetType() throws Exception { TypeToken<List<String>> token = new TypeToken<List<String>>() { }; assertThat(token.getType(), equalTo(StringList.class.getGenericInterfaces()[0])); TypeToken<String> token2 = new TypeToken<String>() { }; assertThat(token2.getType().equals(String.class), is(true)); }
QueryParser { public static Evaluator parse(String query) { try { QueryParser p = new QueryParser(query); return p.parse(); } catch (IllegalArgumentException e) { throw new Selector.SelectorParseException(e.getMessage()); } } private QueryParser(String query); static Evaluator parse(String query); }
@Test public void testOrGetsCorrectPrecedence() { Evaluator eval = QueryParser.parse("a b, c d, e f"); assertTrue(eval instanceof CombiningEvaluator.Or); CombiningEvaluator.Or or = (CombiningEvaluator.Or) eval; assertEquals(3, or.evaluators.size()); for (Evaluator innerEval: or.evaluators) { assertTrue(innerEval instan...
StringToIntArrayFunction implements SetterFunction<String, int[]> { @Nullable @Override public int[] apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new int[0]; } String[] ss = input.split(SEPARATOR); int[] r = new int[ss.length]; for (int i = 0; i < ss.length; i++)...
@Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", int[].class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new int[]{1, 2, 3}))); invoker.invoke(a, null); ...
Node implements Cloneable { public String absUrl(String attributeKey) { Validate.notEmpty(attributeKey); if (!hasAttr(attributeKey)) { return ""; } else { return StringUtil.resolve(baseUri(), attr(attributeKey)); } } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); a...
@Test public void handlesBaseUri() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); attribs.put("relHref", "/foo"); attribs.put("absHref", "http: Element noBase = new Element(tag, "", attribs); assertEquals("", noBase.absUrl("relHref")); assertEquals("http: Element withBase = new Element(tag, "http:...
Node implements Cloneable { public void remove() { Validate.notNull(parentNode); parentNode.removeChild(this); } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(...
@Test public void testRemove() { Document doc = Jsoup.parse("<p>One <span>two</span> three</p>"); Element p = doc.select("p").first(); p.childNode(0).remove(); assertEquals("two three", p.text()); assertEquals("<span>two</span> three", TextUtil.stripNewlines(p.html())); }
Node implements Cloneable { public Document ownerDocument() { Node root = root(); return (root instanceof Document) ? (Document) root : null; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String at...
@Test public void ownerDocument() { Document doc = Jsoup.parse("<p>Hello"); Element p = doc.select("p").first(); assertTrue(p.ownerDocument() == doc); assertTrue(doc.ownerDocument() == doc); assertNull(doc.parent()); }
Node implements Cloneable { public Node root() { Node node = this; while (node.parentNode != null) node = node.parentNode; return node; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attribut...
@Test public void root() { Document doc = Jsoup.parse("<div><p>Hello"); Element p = doc.select("p").first(); Node root = p.root(); assertTrue(doc == root); assertNull(root.parent()); assertTrue(doc.root() == doc); assertTrue(doc.root() == doc.ownerDocument()); Element standAlone = new Element(Tag.valueOf("p"), ""); ass...
Node implements Cloneable { public Node before(String html) { addSiblingHtml(siblingIndex, html); return this; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(...
@Test public void before() { Document doc = Jsoup.parse("<p>One <b>two</b> three</p>"); Element newNode = new Element(Tag.valueOf("em"), ""); newNode.appendText("four"); doc.select("b").first().before(newNode); assertEquals("<p>One <em>four</em><b>two</b> three</p>", doc.body().html()); doc.select("b").first().before("...
StringListToStringFunction implements GetterFunction<List<String>, String> { @Nullable @Override public String apply(@Nullable List<String> 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 < in...
@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), nullVa...
Node implements Cloneable { public Node after(String html) { addSiblingHtml(siblingIndex + 1, html); return this; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAt...
@Test public void after() { Document doc = Jsoup.parse("<p>One <b>two</b> three</p>"); Element newNode = new Element(Tag.valueOf("em"), ""); newNode.appendText("four"); doc.select("b").first().after(newNode); assertEquals("<p>One <b>two</b><em>four</em> three</p>", doc.body().html()); doc.select("b").first().after("<i>...
Node implements Cloneable { public Node unwrap() { Validate.notNull(parentNode); final List<Node> childNodes = ensureChildNodes(); Node firstChild = childNodes.size() > 0 ? childNodes.get(0) : null; parentNode.addChildren(siblingIndex, this.childNodesAsArray()); this.remove(); return firstChild; } protected Node(); ab...
@Test public void unwrap() { Document doc = Jsoup.parse("<div>One <span>Two <b>Three</b></span> Four</div>"); Element span = doc.select("span").first(); Node twoText = span.childNode(0); Node node = span.unwrap(); assertEquals("<div>One Two <b>Three</b> Four</div>", TextUtil.stripNewlines(doc.body().html())); assertTru...
Node implements Cloneable { public Node traverse(NodeVisitor nodeVisitor) { Validate.notNull(nodeVisitor); NodeTraversor traversor = new NodeTraversor(nodeVisitor); traversor.traverse(this); return this; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Att...
@Test public void traverse() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); doc.select("div").first().traverse(new NodeVisitor() { public void head(Node node, int depth) { accum.append("<" + node.nodeName() + ">"); } public void tail(Node node, ...
Node implements Cloneable { public List<Node> childNodesCopy() { final List<Node> nodes = ensureChildNodes(); final ArrayList<Node> children = new ArrayList<>(nodes.size()); for (Node node : nodes) { children.add(node.clone()); } return children; } protected Node(); abstract String nodeName(); boolean hasParent(); Str...
@Test public void childNodesCopy() { Document doc = Jsoup.parse("<div id=1>Text 1 <p>One</p> Text 2 <p>Two<p>Three</div><div id=2>"); Element div1 = doc.select("#1").first(); Element div2 = doc.select("#2").first(); List<Node> divChildren = div1.childNodesCopy(); assertEquals(5, divChildren.size()); TextNode tn1 = (Tex...
Node implements Cloneable { public String attr(String attributeKey) { Validate.notNull(attributeKey); if (!hasAttributes()) return EmptyString; String val = attributes().getIgnoreCase(attributeKey); if (val.length() > 0) return val; else if (attributeKey.startsWith("abs:")) return absUrl(attributeKey.substring("abs:".l...
@Test public void changingAttributeValueShouldReplaceExistingAttributeCaseInsensitive() { Document document = Jsoup.parse("<INPUT id=\"foo\" NAME=\"foo\" VALUE=\"\">"); Element inputElement = document.select("#foo").first(); inputElement.attr("value","bar"); assertEquals(singletonAttributes("value", "bar"), getAttribut...
Document extends Element { public OutputSettings outputSettings() { return outputSettings; } 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(); @O...
@Test public void testXhtmlReferences() { Document doc = Jsoup.parse("&lt; &gt; &amp; &quot; &apos; &times;"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); assertEquals("&lt; &gt; &amp; \" ' ×", doc.body().html()); } @Test public void testHtmlAndXmlSyntax() { String h = "<!DOCTYPE html><body><img async c...
Document extends Element { @Override public Document clone() { Document clone = (Document) super.clone(); clone.outputSettings = this.outputSettings.clone(); return clone; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void tit...
@Test public void testClone() { Document doc = Jsoup.parse("<title>Hello</title> <p>One<p>Two"); Document clone = doc.clone(); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); clone.title("Hello there"); clone.select("p").first().tex...
Document extends Element { public String location() { return location; } 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 outer...
@Test public void testLocation() throws IOException { File in = new ParseTest().getFile("/htmltests/yahoo-jp.html"); Document doc = Jsoup.parse(in, "UTF-8", "http: String location = doc.location(); String baseUri = doc.baseUri(); assertEquals("http: assertEquals("http: in = new ParseTest().getFile("/htmltests/nyt-artic...
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 runtimeOutputTyp...
@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.g...
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 ba...
@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()); }
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 tit...
@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[nam...
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); ...
@Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); }
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(); }
@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(...
FormElement extends Element { public List<Connection.KeyVal> formData() { ArrayList<Connection.KeyVal> data = new ArrayList<>(); for (Element el: elements) { if (!el.tag().isFormSubmittable()) continue; if (el.hasAttr("disabled")) continue; String name = el.attr("name"); if (name.length() == 0) continue; String type = ...
@Test public void createsFormData() { String html = "<form><input name='one' value='two'><select name='three'><option value='not'>" + "<option value='four' selected><option value='five' selected><textarea name=six>seven</textarea>" + "<input name='seven' type='radio' value='on' checked><input name='seven' type='radio' ...
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") ? Co...
@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....
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); }
@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...
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 va...
@Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &amp;\"", attr.html()); assertEquals(attr.html(), attr.toString()); }
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 toStrin...
@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(fou...
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...
@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!"); asser...
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...
@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.getE...
Element extends Node { public String text() { final StringBuilder accum = StringUtil.stringBuilder(); new NodeTraversor(new NodeVisitor() { public void head(Node node, int depth) { if (node instanceof TextNode) { TextNode textNode = (TextNode) node; appendNormalisedText(accum, textNode); } else if (node instanceof Elem...
@Test public void testNormalisesText() { String h = "<p>Hello<p>There.</p> \n <p>Here <b>is</b> \n s<b>om</b>e text."; Document doc = Jsoup.parse(h); String text = doc.text(); assertEquals("Hello There. Here is some text.", text); } @Test public void testKeepsPreText() { String h = "<p>Hello \n \n there.</p> <div><pre>...
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); }
@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...
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 baseUr...
@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()); }
Element extends Node { public boolean hasClass(String className) { final String classAttr = attributes().getIgnoreCase("class"); final int len = classAttr.length(); final int wantLen = className.length(); if (len == 0 || len < wantLen) { return false; } if (len == wantLen) { return className.equalsIgnoreCase(classAttr)...
@Test public void testHasClassDomMethods() { Tag tag = Tag.valueOf("a"); Attributes attribs = new Attributes(); Element el = new Element(tag, "", attribs); attribs.put("class", "toto"); boolean hasClass = el.hasClass("toto"); assertTrue(hasClass); attribs.put("class", " toto"); hasClass = el.hasClass("toto"); assertTru...
Element extends Node { public String html() { StringBuilder accum = StringUtil.stringBuilder(); html(accum); return getOutputSettings().prettyPrint() ? accum.toString().trim() : accum.toString(); } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String baseUri); @Overrid...
@Test public void testFormatHtml() { Document doc = Jsoup.parse("<title>Format test</title><div><p>Hello <span>jsoup <span>users</span></span></p><p>Good.</p></div>"); assertEquals("<html>\n <head>\n <title>Format test</title>\n </head>\n <body>\n <div>\n <p>Hello <span>jsoup <span>users</span></span></p>\n <p>Good.</p...
Element extends Node { public Elements select(String cssQuery) { return Selector.select(cssQuery, 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(); @Over...
@Test public void testEmptyElementFormatHtml() { Document doc = Jsoup.parse("<section><div></div></section>"); assertEquals("<section>\n <div></div>\n</section>", doc.select("section").first().outerHtml()); } @Test public void testHashAndEqualsAndValue() { String doc1 = "<div id=1><p class=one>One</p><p class=one>One</...
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(); @...
@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()); }
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 S...
@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())); }
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 runtimeOutputTy...
@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.g...
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(); @Overri...
@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>...
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(); @Ov...
@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").las...
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(); @Over...
@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(...
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(St...
@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()); }
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 ...
@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("js...
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 nod...
@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"); assertEqua...
Element extends Node { public Set<String> classNames() { String[] names = classSplit.split(className()); Set<String> classNames = new LinkedHashSet<>(Arrays.asList(names)); classNames.remove(""); return classNames; } Element(String tag); Element(Tag tag, String baseUri, Attributes attributes); Element(Tag tag, String...
@Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length==2); assertEquals("c1", arr1[0]); asser...
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 b...
@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)); }
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...
@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[]{100000000000000000...
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 ...
@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")...
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 tag...
@Test public void elementByTagName() { Element a = new Element("P"); assertTrue(a.tagName().equals("P")); }
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 i...
@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 = chi...
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 boole...
@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 = Entitie...
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 St...
@Test public void getByName() { assertEquals("≫⃒", Entities.getByName("nGt")); assertEquals("fj", Entities.getByName("fjlig")); assertEquals("≫", Entities.getByName("gg")); assertEquals("©", Entities.getByName("copy")); }
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 codepointsFor...
@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()...
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;...
@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())...
Cleaner { public Document clean(Document dirtyDocument) { Validate.notNull(dirtyDocument); Document clean = Document.createShell(dirtyDocument.baseUri()); if (dirtyDocument.body() != null) copySafeNodes(dirtyDocument.body(), clean.body()); return clean; } Cleaner(Whitelist whitelist); Document clean(Document dirtyDocum...
@Test public void simpleBehaviourTest() { String h = "<div><p class=foo><a href='http: String cleanHtml = Jsoup.clean(h, Whitelist.simpleText()); assertEquals("Hello <b>there</b>!", TextUtil.stripNewlines(cleanHtml)); } @Test public void simpleBehaviourTest2() { String h = "Hello <b>there</b>!"; String cleanHtml = Jsou...
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...
@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.invok...
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++) { b...
@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(...
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 TypeToke...
@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)); }
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); ...
@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...
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...
@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...
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<...
@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())); in...
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 consu...
@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()); asse...
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(); }
@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.uncons...
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(); }
@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()); }
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 ...
@Test public void consumeToEnd() { String in = "one two three"; CharacterReader r = new CharacterReader(in); String toEnd = r.consumeToEnd(); assertEquals(in, toEnd); assertTrue(r.isEmpty()); }
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(); S...
@Test public void nextIndexOfUnmatched() { CharacterReader r = new CharacterReader("<[[one]]"); assertEquals(-1, r.nextIndexOf("]]>")); }
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 (i...
@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().to...
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(); }
@Test public void advance() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals('O', r.consume()); r.advance(); assertEquals('e', r.consume()); }
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, ...
@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()); assertEq...
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); } CharacterRea...
@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()); }
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...
@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()); }
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)...
@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")); a...
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 + of...
@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...
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 i...
@Test public void containsIgnoreCase() { CharacterReader r = new CharacterReader("One TWO three"); assertTrue(r.containsIgnoreCase("two")); assertTrue(r.containsIgnoreCase("three")); assertFalse(r.containsIgnoreCase("one")); }
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()...
@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)); }
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 ...
@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")); ass...
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) ...
@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); }
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++) ...
@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...
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(); cha...
@Test public void unescape() { assertEquals("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\")); }
XmlTreeBuilder extends TreeBuilder { Document parse(Reader input, String baseUri) { return parse(input, baseUri, ParseErrorList.noTracking(), ParseSettings.preserveCase); } }
@Test public void testSimpleXmlParse() { String xml = "<doc id=2 href='/bar'>Foo <br /><link>One</link><link>Two</link></doc>"; XmlTreeBuilder tb = new XmlTreeBuilder(); Document doc = tb.parse(xml, "http: assertEquals("<doc id=\"2\" href=\"/bar\">Foo <br /><link>One</link><link>Two</link></doc>", TextUtil.stripNewline...
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.si...
@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); assertTha...
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 t...
@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)...
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<Strin...
@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())...
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 ...
@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("co...
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); C...
@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...
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 Connecti...
@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()); }
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 p...
@Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); }
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 ur...
@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")); }
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(St...
@Test public void timeout() { Connection con = HttpConnection.connect("http: assertEquals(30 * 1000, con.request().timeout()); con.timeout(1000); assertEquals(1000, con.request().timeout()); }
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); Con...
@Test public void referrer() { Connection con = HttpConnection.connect("http: con.referrer("http: assertEquals("http: }