method2testcases
stringlengths 118
6.63k
|
---|
### Question:
EndianUtils { public static long readSwappedUnsignedInteger(final byte[] data, final int offset) { final long low = ( ( ( data[ offset + 0 ] & 0xff ) << 0 ) + ( ( data[ offset + 1 ] & 0xff ) << 8 ) + ( ( data[ offset + 2 ] & 0xff ) << 16 ) ); final long high = data[ offset + 3 ] & 0xff; return (high << 24) + (0xffffffffL & low); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testReadSwappedUnsignedInteger() throws IOException { final byte[] bytes = new byte[] { 0x04, 0x03, 0x02, 0x01 }; assertEquals( 0x0000000001020304L, EndianUtils.readSwappedUnsignedInteger( bytes, 0 ) ); final ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x0000000001020304L, EndianUtils.readSwappedUnsignedInteger( input ) ); }
@Test public void testUnsignedOverrun() throws Exception { final byte[] target = new byte[] { 0, 0, 0, (byte)0x80 }; final long expected = 0x80000000L; long actual = EndianUtils.readSwappedUnsignedInteger(target, 0); assertEquals("readSwappedUnsignedInteger(byte[], int) was incorrect", expected, actual); final ByteArrayInputStream in = new ByteArrayInputStream(target); actual = EndianUtils.readSwappedUnsignedInteger(in); assertEquals("readSwappedUnsignedInteger(InputStream) was incorrect", expected, actual); } |
### Question:
EndianUtils { public static long readSwappedLong(final byte[] data, final int offset) { final long low = readSwappedInteger(data, offset); final long high = readSwappedInteger(data, offset + 4); return (high << 32) + (0xffffffffL & low); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testReadSwappedLong() throws IOException { final byte[] bytes = new byte[] { 0x08, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01 }; assertEquals( 0x0102030405060708L, EndianUtils.readSwappedLong( bytes, 0 ) ); final ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( 0x0102030405060708L, EndianUtils.readSwappedLong( input ) ); } |
### Question:
EndianUtils { public static void writeSwappedLong(final byte[] data, final int offset, final long value) { data[ offset + 0 ] = (byte)( ( value >> 0 ) & 0xff ); data[ offset + 1 ] = (byte)( ( value >> 8 ) & 0xff ); data[ offset + 2 ] = (byte)( ( value >> 16 ) & 0xff ); data[ offset + 3 ] = (byte)( ( value >> 24 ) & 0xff ); data[ offset + 4 ] = (byte)( ( value >> 32 ) & 0xff ); data[ offset + 5 ] = (byte)( ( value >> 40 ) & 0xff ); data[ offset + 6 ] = (byte)( ( value >> 48 ) & 0xff ); data[ offset + 7 ] = (byte)( ( value >> 56 ) & 0xff ); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testWriteSwappedLong() throws IOException { byte[] bytes = new byte[8]; EndianUtils.writeSwappedLong( bytes, 0, 0x0102030405060708L ); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(8); EndianUtils.writeSwappedLong( baos, 0x0102030405060708L ); bytes = baos.toByteArray(); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); } |
### Question:
EndianUtils { public static float readSwappedFloat(final byte[] data, final int offset) { return Float.intBitsToFloat( readSwappedInteger( data, offset ) ); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testReadSwappedFloat() throws IOException { final byte[] bytes = new byte[] { 0x04, 0x03, 0x02, 0x01 }; final float f1 = Float.intBitsToFloat( 0x01020304 ); final float f2 = EndianUtils.readSwappedFloat( bytes, 0 ); assertEquals( f1, f2, 0.0 ); final ByteArrayInputStream input = new ByteArrayInputStream(bytes); assertEquals( f1, EndianUtils.readSwappedFloat( input ), 0.0 ); } |
### Question:
EndianUtils { public static void writeSwappedFloat(final byte[] data, final int offset, final float value) { writeSwappedInteger( data, offset, Float.floatToIntBits( value ) ); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testWriteSwappedFloat() throws IOException { byte[] bytes = new byte[4]; final float f1 = Float.intBitsToFloat( 0x01020304 ); EndianUtils.writeSwappedFloat( bytes, 0, f1 ); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(4); EndianUtils.writeSwappedFloat( baos, f1 ); bytes = baos.toByteArray(); assertEquals( 0x04, bytes[0] ); assertEquals( 0x03, bytes[1] ); assertEquals( 0x02, bytes[2] ); assertEquals( 0x01, bytes[3] ); } |
### Question:
Elements extends ArrayList<Element> { public boolean is(String query) { Evaluator eval = QueryParser.parse(query); for (Element e : this) { if (e.is(eval)) return true; } return false; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void is() { String h = "<p>Hello<p title=foo>there<p>world"; Document doc = Jsoup.parse(h); Elements ps = doc.select("p"); assertTrue(ps.is("[title=foo]")); assertFalse(ps.is("[title=bar]")); } |
### Question:
EndianUtils { public static void writeSwappedDouble(final byte[] data, final int offset, final double value) { writeSwappedLong( data, offset, Double.doubleToLongBits( value ) ); } EndianUtils(); static short swapShort(final short value); static int swapInteger(final int value); static long swapLong(final long value); static float swapFloat(final float value); static double swapDouble(final double value); static void writeSwappedShort(final byte[] data, final int offset, final short value); static short readSwappedShort(final byte[] data, final int offset); static int readSwappedUnsignedShort(final byte[] data, final int offset); static void writeSwappedInteger(final byte[] data, final int offset, final int value); static int readSwappedInteger(final byte[] data, final int offset); static long readSwappedUnsignedInteger(final byte[] data, final int offset); static void writeSwappedLong(final byte[] data, final int offset, final long value); static long readSwappedLong(final byte[] data, final int offset); static void writeSwappedFloat(final byte[] data, final int offset, final float value); static float readSwappedFloat(final byte[] data, final int offset); static void writeSwappedDouble(final byte[] data, final int offset, final double value); static double readSwappedDouble(final byte[] data, final int offset); static void writeSwappedShort(final OutputStream output, final short value); static short readSwappedShort(final InputStream input); static int readSwappedUnsignedShort(final InputStream input); static void writeSwappedInteger(final OutputStream output, final int value); static int readSwappedInteger(final InputStream input); static long readSwappedUnsignedInteger(final InputStream input); static void writeSwappedLong(final OutputStream output, final long value); static long readSwappedLong(final InputStream input); static void writeSwappedFloat(final OutputStream output, final float value); static float readSwappedFloat(final InputStream input); static void writeSwappedDouble(final OutputStream output, final double value); static double readSwappedDouble(final InputStream input); }### Answer:
@Test public void testWriteSwappedDouble() throws IOException { byte[] bytes = new byte[8]; final double d1 = Double.longBitsToDouble( 0x0102030405060708L ); EndianUtils.writeSwappedDouble( bytes, 0, d1 ); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); final ByteArrayOutputStream baos = new ByteArrayOutputStream(8); EndianUtils.writeSwappedDouble( baos, d1 ); bytes = baos.toByteArray(); assertEquals( 0x08, bytes[0] ); assertEquals( 0x07, bytes[1] ); assertEquals( 0x06, bytes[2] ); assertEquals( 0x05, bytes[3] ); assertEquals( 0x04, bytes[4] ); assertEquals( 0x03, bytes[5] ); assertEquals( 0x02, bytes[6] ); assertEquals( 0x01, bytes[7] ); } |
### Question:
FullClassNameMatcher implements ClassNameMatcher { @Override public boolean matches(String className) { return classesSet.contains(className); } FullClassNameMatcher(String... classes); @Override boolean matches(String className); }### Answer:
@Test public void noNames() throws Exception { final FullClassNameMatcher m = new FullClassNameMatcher(); assertFalse(m.matches(Integer.class.getName())); }
@Test public void withNames() throws Exception { final FullClassNameMatcher m = new FullClassNameMatcher(NAMES_ARRAY); assertTrue(m.matches(Integer.class.getName())); assertFalse(m.matches(String.class.getName())); } |
### Question:
WildcardClassNameMatcher implements ClassNameMatcher { @Override public boolean matches(String className) { return FilenameUtils.wildcardMatch(className, pattern); } WildcardClassNameMatcher(String pattern); @Override boolean matches(String className); }### Answer:
@Test public void noPattern() { ClassNameMatcher ca = new WildcardClassNameMatcher("org.foo"); assertTrue(ca.matches("org.foo")); assertFalse(ca.matches("org.foo.and.more")); assertFalse(ca.matches("org_foo")); }
@Test public void star() { ClassNameMatcher ca = new WildcardClassNameMatcher("org*"); assertTrue(ca.matches("org.foo.should.match")); assertFalse(ca.matches("bar.should.not.match")); }
@Test public void starAndQuestionMark() { ClassNameMatcher ca = new WildcardClassNameMatcher("org?apache?something*"); assertTrue(ca.matches("org.apache_something.more")); assertFalse(ca.matches("org..apache_something.more")); } |
### Question:
RegexpClassNameMatcher implements ClassNameMatcher { @Override public boolean matches(String className) { return pattern.matcher(className).matches(); } RegexpClassNameMatcher(String regex); RegexpClassNameMatcher(Pattern pattern); @Override boolean matches(String className); }### Answer:
@Test public void testSimplePatternFromString() { ClassNameMatcher ca = new RegexpClassNameMatcher("foo.*"); assertTrue(ca.matches("foo.should.match")); assertFalse(ca.matches("bar.should.not.match")); }
@Test public void testSimplePatternFromPattern() { ClassNameMatcher ca = new RegexpClassNameMatcher(Pattern.compile("foo.*")); assertTrue(ca.matches("foo.should.match")); assertFalse(ca.matches("bar.should.not.match")); }
@Test public void testOrPattern() { ClassNameMatcher ca = new RegexpClassNameMatcher("foo.*|bar.*"); assertTrue(ca.matches("foo.should.match")); assertTrue(ca.matches("bar.should.match")); assertFalse(ca.matches("zoo.should.not.match")); } |
### Question:
Elements extends ArrayList<Element> { public Elements parents() { HashSet<Element> combo = new LinkedHashSet<>(); for (Element e: this) { combo.addAll(e.parents()); } return new Elements(combo); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void parents() { Document doc = Jsoup.parse("<div><p>Hello</p></div><p>There</p>"); Elements parents = doc.select("p").parents(); assertEquals(3, parents.size()); assertEquals("div", parents.get(0).tagName()); assertEquals("body", parents.get(1).tagName()); assertEquals("html", parents.get(2).tagName()); } |
### Question:
ValidatingObjectInputStream extends ObjectInputStream { public ValidatingObjectInputStream accept(Class<?>... classes) { for (Class<?> c : classes) { acceptMatchers.add(new FullClassNameMatcher(c.getName())); } return this; } ValidatingObjectInputStream(InputStream input); ValidatingObjectInputStream accept(Class<?>... classes); ValidatingObjectInputStream reject(Class<?>... classes); ValidatingObjectInputStream accept(String... patterns); ValidatingObjectInputStream reject(String... patterns); ValidatingObjectInputStream accept(Pattern pattern); ValidatingObjectInputStream reject(Pattern pattern); ValidatingObjectInputStream accept(ClassNameMatcher m); ValidatingObjectInputStream reject(ClassNameMatcher m); }### Answer:
@Test public void acceptCustomMatcher() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(ALWAYS_TRUE) ); }
@Test public void acceptPattern() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(Pattern.compile(".*MockSerializedClass.*")) ); }
@Test public void acceptWildcard() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept("org.apache.commons.io.*") ); }
@Test(expected = InvalidClassException.class) public void ourTestClassNotAccepted() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(Integer.class) ); }
@Test public void ourTestClassOnlyAccepted() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(MockSerializedClass.class) ); }
@Test public void ourTestClassAcceptedFirst() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(MockSerializedClass.class, Integer.class) ); }
@Test public void ourTestClassAcceptedSecond() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(Integer.class, MockSerializedClass.class) ); }
@Test public void ourTestClassAcceptedFirstWildcard() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept("*MockSerializedClass","*Integer") ); }
@Test public void ourTestClassAcceptedSecondWildcard() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept("*Integer","*MockSerializedClass") ); } |
### Question:
Elements extends ArrayList<Element> { public Elements not(String query) { Elements out = Selector.select(query, this); return Selector.filterOut(this, out); } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void not() { Document doc = Jsoup.parse("<div id=1><p>One</p></div> <div id=2><p><span>Two</span></p></div>"); Elements div1 = doc.select("div").not(":has(p > span)"); assertEquals(1, div1.size()); assertEquals("1", div1.first().id()); Elements div2 = doc.select("div").not("#1"); assertEquals(1, div2.size()); assertEquals("2", div2.first().id()); } |
### Question:
ValidatingObjectInputStream extends ObjectInputStream { public ValidatingObjectInputStream reject(Class<?>... classes) { for (Class<?> c : classes) { rejectMatchers.add(new FullClassNameMatcher(c.getName())); } return this; } ValidatingObjectInputStream(InputStream input); ValidatingObjectInputStream accept(Class<?>... classes); ValidatingObjectInputStream reject(Class<?>... classes); ValidatingObjectInputStream accept(String... patterns); ValidatingObjectInputStream reject(String... patterns); ValidatingObjectInputStream accept(Pattern pattern); ValidatingObjectInputStream reject(Pattern pattern); ValidatingObjectInputStream accept(ClassNameMatcher m); ValidatingObjectInputStream reject(ClassNameMatcher m); }### Answer:
@Test(expected = InvalidClassException.class) public void reject() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .accept(Long.class) .reject(MockSerializedClass.class, Integer.class) ); }
@Test(expected = InvalidClassException.class) public void rejectOnly() throws Exception { assertSerialization( willClose(new ValidatingObjectInputStream(testStream)) .reject(Integer.class) ); }
@Test(expected = RuntimeException.class) public void customInvalidMethod() throws Exception { class CustomVOIS extends ValidatingObjectInputStream { CustomVOIS(InputStream is) throws IOException { super(is); } @Override protected void invalidClassNameFound(String className) throws InvalidClassException { throw new RuntimeException("Custom exception"); } }; assertSerialization( willClose(new CustomVOIS(testStream)) .reject(Integer.class) ); } |
### Question:
PathFileComparator extends AbstractFileComparator implements Serializable { public int compare(final File file1, final File file2) { return caseSensitivity.checkCompareTo(file1.getPath(), file2.getPath()); } PathFileComparator(); PathFileComparator(final IOCase caseSensitivity); int compare(final File file1, final File file2); @Override String toString(); static final Comparator<File> PATH_COMPARATOR; static final Comparator<File> PATH_REVERSE; static final Comparator<File> PATH_INSENSITIVE_COMPARATOR; static final Comparator<File> PATH_INSENSITIVE_REVERSE; static final Comparator<File> PATH_SYSTEM_COMPARATOR; static final Comparator<File> PATH_SYSTEM_REVERSE; }### Answer:
@Test public void testCaseSensitivity() { final File file3 = new File("FOO/file.txt"); final Comparator<File> sensitive = new PathFileComparator(null); assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); final Comparator<File> insensitive = PathFileComparator.PATH_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } |
### Question:
NameFileComparator extends AbstractFileComparator implements Serializable { public int compare(final File file1, final File file2) { return caseSensitivity.checkCompareTo(file1.getName(), file2.getName()); } NameFileComparator(); NameFileComparator(final IOCase caseSensitivity); int compare(final File file1, final File file2); @Override String toString(); static final Comparator<File> NAME_COMPARATOR; static final Comparator<File> NAME_REVERSE; static final Comparator<File> NAME_INSENSITIVE_COMPARATOR; static final Comparator<File> NAME_INSENSITIVE_REVERSE; static final Comparator<File> NAME_SYSTEM_COMPARATOR; static final Comparator<File> NAME_SYSTEM_REVERSE; }### Answer:
@Test public void testCaseSensitivity() { final File file3 = new File("a/FOO.txt"); final Comparator<File> sensitive = new NameFileComparator(null); assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); final Comparator<File> insensitive = NameFileComparator.NAME_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } |
### Question:
SizeFileComparator extends AbstractFileComparator implements Serializable { public int compare(final File file1, final File file2) { long size1 = 0; if (file1.isDirectory()) { size1 = sumDirectoryContents && file1.exists() ? FileUtils.sizeOfDirectory(file1) : 0; } else { size1 = file1.length(); } long size2 = 0; if (file2.isDirectory()) { size2 = sumDirectoryContents && file2.exists() ? FileUtils.sizeOfDirectory(file2) : 0; } else { size2 = file2.length(); } final long result = size1 - size2; if (result < 0) { return -1; } else if (result > 0) { return 1; } else { return 0; } } SizeFileComparator(); SizeFileComparator(final boolean sumDirectoryContents); int compare(final File file1, final File file2); @Override String toString(); static final Comparator<File> SIZE_COMPARATOR; static final Comparator<File> SIZE_REVERSE; static final Comparator<File> SIZE_SUMDIR_COMPARATOR; static final Comparator<File> SIZE_SUMDIR_REVERSE; }### Answer:
@Test public void testNonexistantFile() { final File nonexistantFile = new File(new File("."), "nonexistant.txt"); assertFalse(nonexistantFile.exists()); assertTrue("less", comparator.compare(nonexistantFile, moreFile) < 0); }
@Test public void testCompareDirectorySizes() { assertEquals("sumDirectoryContents=false", 0, comparator.compare(smallerDir, largerDir)); assertEquals("less", -1, SizeFileComparator.SIZE_SUMDIR_COMPARATOR.compare(smallerDir, largerDir)); assertEquals("less", 1, SizeFileComparator.SIZE_SUMDIR_REVERSE.compare(smallerDir, largerDir)); } |
### Question:
ExtensionFileComparator extends AbstractFileComparator implements Serializable { public int compare(final File file1, final File file2) { final String suffix1 = FilenameUtils.getExtension(file1.getName()); final String suffix2 = FilenameUtils.getExtension(file2.getName()); return caseSensitivity.checkCompareTo(suffix1, suffix2); } ExtensionFileComparator(); ExtensionFileComparator(final IOCase caseSensitivity); int compare(final File file1, final File file2); @Override String toString(); static final Comparator<File> EXTENSION_COMPARATOR; static final Comparator<File> EXTENSION_REVERSE; static final Comparator<File> EXTENSION_INSENSITIVE_COMPARATOR; static final Comparator<File> EXTENSION_INSENSITIVE_REVERSE; static final Comparator<File> EXTENSION_SYSTEM_COMPARATOR; static final Comparator<File> EXTENSION_SYSTEM_REVERSE; }### Answer:
@Test public void testCaseSensitivity() { final File file3 = new File("abc.FOO"); final Comparator<File> sensitive = new ExtensionFileComparator(null); assertTrue("sensitive file1 & file2 = 0", sensitive.compare(equalFile1, equalFile2) == 0); assertTrue("sensitive file1 & file3 > 0", sensitive.compare(equalFile1, file3) > 0); assertTrue("sensitive file1 & less > 0", sensitive.compare(equalFile1, lessFile) > 0); final Comparator<File> insensitive = ExtensionFileComparator.EXTENSION_INSENSITIVE_COMPARATOR; assertTrue("insensitive file1 & file2 = 0", insensitive.compare(equalFile1, equalFile2) == 0); assertTrue("insensitive file1 & file3 = 0", insensitive.compare(equalFile1, file3) == 0); assertTrue("insensitive file1 & file4 > 0", insensitive.compare(equalFile1, lessFile) > 0); assertTrue("insensitive file3 & less > 0", insensitive.compare(file3, lessFile) > 0); } |
### Question:
CompositeFileComparator extends AbstractFileComparator implements Serializable { public int compare(final File file1, final File file2) { int result = 0; for (final Comparator<File> delegate : delegates) { result = delegate.compare(file1, file2); if (result != 0) { break; } } return result; } @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct CompositeFileComparator(final Comparator<File>... delegates); @SuppressWarnings("unchecked") // casts 1 & 2 must be OK because types are already correct CompositeFileComparator(final Iterable<Comparator<File>> delegates); int compare(final File file1, final File file2); @Override String toString(); }### Answer:
@Test public void constructorIterable_order() { final List<Comparator<File>> list = new ArrayList<Comparator<File>>(); list.add(SizeFileComparator.SIZE_COMPARATOR); list.add(ExtensionFileComparator.EXTENSION_COMPARATOR); final Comparator<File> c = new CompositeFileComparator(list); assertEquals("equal", 0, c.compare(equalFile1, equalFile2)); assertTrue("less", c.compare(lessFile, moreFile) < 0); assertTrue("more", c.compare(moreFile, lessFile) > 0); } |
### Question:
ClosedInputStream extends InputStream { @Override public int read() { return EOF; } @Override int read(); static final ClosedInputStream CLOSED_INPUT_STREAM; }### Answer:
@Test public void testRead() throws Exception { final ClosedInputStream cis = new ClosedInputStream(); assertEquals("read()", -1, cis.read()); cis.close(); } |
### Question:
Elements extends ArrayList<Element> { public Elements traverse(NodeVisitor nodeVisitor) { Validate.notNull(nodeVisitor); NodeTraversor traversor = new NodeTraversor(nodeVisitor); for (Element el: this) { traversor.traverse(el); } return this; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void traverse() { Document doc = Jsoup.parse("<div><p>Hello</p></div><div>There</div>"); final StringBuilder accum = new StringBuilder(); doc.select("div").traverse(new NodeVisitor() { public void head(Node node, int depth) { accum.append("<" + node.nodeName() + ">"); } public void tail(Node node, int depth) { accum.append("</" + node.nodeName() + ">"); } }); assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString()); } |
### Question:
NullReader extends Reader { @Override public int read() throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position++; return processChar(); } NullReader(final long size); NullReader(final long size, final boolean markSupported, final boolean throwEofException); long getPosition(); long getSize(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] chars); @Override int read(final char[] chars, final int offset, final int length); @Override synchronized void reset(); @Override long skip(final long numberOfChars); }### Answer:
@Test public void testRead() throws Exception { final int size = 5; final TestNullReader reader = new TestNullReader(size); for (int i = 0; i < size; i++) { assertEquals("Check Value [" + i + "]", i, reader.read()); } assertEquals("End of File", -1, reader.read()); try { final int result = reader.read(); fail("Should have thrown an IOException, value=[" + result + "]"); } catch (final IOException e) { assertEquals("Read after end of file", e.getMessage()); } reader.close(); assertEquals("Available after close", 0, reader.getPosition()); } |
### Question:
NullReader extends Reader { @Override public long skip(final long numberOfChars) throws IOException { if (eof) { throw new IOException("Skip after end of file"); } if (position == size) { return doEndOfFile(); } position += numberOfChars; long returnLength = numberOfChars; if (position > size) { returnLength = numberOfChars - (position - size); position = size; } return returnLength; } NullReader(final long size); NullReader(final long size, final boolean markSupported, final boolean throwEofException); long getPosition(); long getSize(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] chars); @Override int read(final char[] chars, final int offset, final int length); @Override synchronized void reset(); @Override long skip(final long numberOfChars); }### Answer:
@Test public void testSkip() throws Exception { final Reader reader = new TestNullReader(10, true, false); assertEquals("Read 1", 0, reader.read()); assertEquals("Read 2", 1, reader.read()); assertEquals("Skip 1", 5, reader.skip(5)); assertEquals("Read 3", 7, reader.read()); assertEquals("Skip 2", 2, reader.skip(5)); assertEquals("Skip 3 (EOF)", -1, reader.skip(5)); try { reader.skip(5); fail("Expected IOException for skipping after end of file"); } catch (final IOException e) { assertEquals("Skip after EOF IOException message", "Skip after end of file", e.getMessage()); } reader.close(); } |
### Question:
CloseShieldInputStream extends ProxyInputStream { @Override public void close() { in = new ClosedInputStream(); } CloseShieldInputStream(final InputStream in); @Override void close(); }### Answer:
@Test public void testClose() throws IOException { shielded.close(); assertFalse("closed", closed); assertEquals("read()", -1, shielded.read()); assertEquals("read()", data[0], original.read()); } |
### Question:
TeeInputStream extends ProxyInputStream { @Override public int read() throws IOException { final int ch = super.read(); if (ch != EOF) { branch.write(ch); } return ch; } TeeInputStream(final InputStream input, final OutputStream branch); TeeInputStream(
final InputStream input, final OutputStream branch, final boolean closeBranch); @Override void close(); @Override int read(); @Override int read(final byte[] bts, final int st, final int end); @Override int read(final byte[] bts); }### Answer:
@Test public void testReadOneByte() throws Exception { assertEquals('a', tee.read()); assertEquals("a", new String(output.toString(ASCII))); }
@Test public void testReadEverything() throws Exception { assertEquals('a', tee.read()); assertEquals('b', tee.read()); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("abc", new String(output.toString(ASCII))); }
@Test public void testReadToArray() throws Exception { final byte[] buffer = new byte[8]; assertEquals(3, tee.read(buffer)); assertEquals('a', buffer[0]); assertEquals('b', buffer[1]); assertEquals('c', buffer[2]); assertEquals(-1, tee.read(buffer)); assertEquals("abc", new String(output.toString(ASCII))); }
@Test public void testReadToArrayWithOffset() throws Exception { final byte[] buffer = new byte[8]; assertEquals(3, tee.read(buffer, 4, 4)); assertEquals('a', buffer[4]); assertEquals('b', buffer[5]); assertEquals('c', buffer[6]); assertEquals(-1, tee.read(buffer, 4, 4)); assertEquals("abc", new String(output.toString(ASCII))); }
@Test public void testSkip() throws Exception { assertEquals('a', tee.read()); assertEquals(1, tee.skip(1)); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("ac", new String(output.toString(ASCII))); }
@Test public void testMarkReset() throws Exception { assertEquals('a', tee.read()); tee.mark(1); assertEquals('b', tee.read()); tee.reset(); assertEquals('b', tee.read()); assertEquals('c', tee.read()); assertEquals(-1, tee.read()); assertEquals("abbc", new String(output.toString(ASCII))); } |
### Question:
CharSequenceInputStream extends InputStream { @Override public boolean markSupported() { return true; } CharSequenceInputStream(final CharSequence cs, final Charset charset, final int bufferSize); CharSequenceInputStream(final CharSequence cs, final String charset, final int bufferSize); CharSequenceInputStream(final CharSequence cs, final Charset charset); CharSequenceInputStream(final CharSequence cs, final String charset); @Override int read(final byte[] b, int off, int len); @Override int read(); @Override int read(final byte[] b); @Override long skip(long n); @Override int available(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override synchronized void reset(); @Override boolean markSupported(); }### Answer:
@Test public void testMarkSupported() throws Exception { final InputStream r = new CharSequenceInputStream("test", "UTF-8"); try { assertTrue(r.markSupported()); } finally { r.close(); } } |
### Question:
Elements extends ArrayList<Element> { public List<FormElement> forms() { ArrayList<FormElement> forms = new ArrayList<>(); for (Element el: this) if (el instanceof FormElement) forms.add((FormElement) el); return forms; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void forms() { Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>"); Elements els = doc.select("*"); assertEquals(9, els.size()); List<FormElement> forms = els.forms(); assertEquals(2, forms.size()); assertTrue(forms.get(0) != null); assertTrue(forms.get(1) != null); assertEquals("1", forms.get(0).id()); assertEquals("2", forms.get(1).id()); } |
### Question:
CharSequenceInputStream extends InputStream { @Override public int available() throws IOException { return this.bbuf.remaining() + this.cbuf.remaining(); } CharSequenceInputStream(final CharSequence cs, final Charset charset, final int bufferSize); CharSequenceInputStream(final CharSequence cs, final String charset, final int bufferSize); CharSequenceInputStream(final CharSequence cs, final Charset charset); CharSequenceInputStream(final CharSequence cs, final String charset); @Override int read(final byte[] b, int off, int len); @Override int read(); @Override int read(final byte[] b); @Override long skip(long n); @Override int available(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override synchronized void reset(); @Override boolean markSupported(); }### Answer:
@Test public void testAvailable() throws Exception { for (final String csName : Charset.availableCharsets().keySet()) { try { if (isAvailabilityTestableForCharset(csName)) { testAvailableSkip(csName); testAvailableRead(csName); } } catch (UnsupportedOperationException e){ fail("Operation not supported for " + csName); } } } |
### Question:
NullInputStream extends InputStream { @Override public int read() throws IOException { if (eof) { throw new IOException("Read after end of file"); } if (position == size) { return doEndOfFile(); } position++; return processByte(); } NullInputStream(final long size); NullInputStream(final long size, final boolean markSupported, final boolean throwEofException); long getPosition(); long getSize(); @Override int available(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override boolean markSupported(); @Override int read(); @Override int read(final byte[] bytes); @Override int read(final byte[] bytes, final int offset, final int length); @Override synchronized void reset(); @Override long skip(final long numberOfBytes); }### Answer:
@Test public void testRead() throws Exception { final int size = 5; final InputStream input = new TestNullInputStream(size); for (int i = 0; i < size; i++) { assertEquals("Check Size [" + i + "]", size - i, input.available()); assertEquals("Check Value [" + i + "]", i, input.read()); } assertEquals("Available after contents all read", 0, input.available()); assertEquals("End of File", -1, input.read()); assertEquals("Available after End of File", 0, input.available()); try { final int result = input.read(); fail("Should have thrown an IOException, byte=[" + result + "]"); } catch (final IOException e) { assertEquals("Read after end of file", e.getMessage()); } input.close(); assertEquals("Available after close", size, input.available()); } |
### Question:
NullInputStream extends InputStream { @Override public long skip(final long numberOfBytes) throws IOException { if (eof) { throw new IOException("Skip after end of file"); } if (position == size) { return doEndOfFile(); } position += numberOfBytes; long returnLength = numberOfBytes; if (position > size) { returnLength = numberOfBytes - (position - size); position = size; } return returnLength; } NullInputStream(final long size); NullInputStream(final long size, final boolean markSupported, final boolean throwEofException); long getPosition(); long getSize(); @Override int available(); @Override void close(); @Override synchronized void mark(final int readlimit); @Override boolean markSupported(); @Override int read(); @Override int read(final byte[] bytes); @Override int read(final byte[] bytes, final int offset, final int length); @Override synchronized void reset(); @Override long skip(final long numberOfBytes); }### Answer:
@Test public void testSkip() throws Exception { final InputStream input = new TestNullInputStream(10, true, false); assertEquals("Read 1", 0, input.read()); assertEquals("Read 2", 1, input.read()); assertEquals("Skip 1", 5, input.skip(5)); assertEquals("Read 3", 7, input.read()); assertEquals("Skip 2", 2, input.skip(5)); assertEquals("Skip 3 (EOF)", -1, input.skip(5)); try { input.skip(5); fail("Expected IOException for skipping after end of file"); } catch (final IOException e) { assertEquals("Skip after EOF IOException message", "Skip after end of file", e.getMessage()); } input.close(); } |
### Question:
CharSequenceReader extends Reader implements Serializable { @Override public void close() { idx = 0; mark = 0; } CharSequenceReader(final CharSequence charSequence); @Override void close(); @Override void mark(final int readAheadLimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] array, final int offset, final int length); @Override void reset(); @Override long skip(final long n); @Override String toString(); }### Answer:
@Test public void testClose() throws IOException { final Reader reader = new CharSequenceReader("FooBar"); checkRead(reader, "Foo"); reader.close(); checkRead(reader, "Foo"); } |
### Question:
CharSequenceReader extends Reader implements Serializable { @Override public boolean markSupported() { return true; } CharSequenceReader(final CharSequence charSequence); @Override void close(); @Override void mark(final int readAheadLimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] array, final int offset, final int length); @Override void reset(); @Override long skip(final long n); @Override String toString(); }### Answer:
@Test public void testMarkSupported() throws Exception { final Reader reader = new CharSequenceReader("FooBar"); assertTrue(reader.markSupported()); reader.close(); } |
### Question:
CharSequenceReader extends Reader implements Serializable { @Override public void mark(final int readAheadLimit) { mark = idx; } CharSequenceReader(final CharSequence charSequence); @Override void close(); @Override void mark(final int readAheadLimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] array, final int offset, final int length); @Override void reset(); @Override long skip(final long n); @Override String toString(); }### Answer:
@Test public void testMark() throws IOException { final Reader reader = new CharSequenceReader("FooBar"); checkRead(reader, "Foo"); reader.mark(0); checkRead(reader, "Bar"); reader.reset(); checkRead(reader, "Bar"); reader.close(); checkRead(reader, "Foo"); reader.reset(); checkRead(reader, "Foo"); } |
### Question:
CharSequenceReader extends Reader implements Serializable { @Override public long skip(final long n) { if (n < 0) { throw new IllegalArgumentException( "Number of characters to skip is less than zero: " + n); } if (idx >= charSequence.length()) { return EOF; } final int dest = (int)Math.min(charSequence.length(), idx + n); final int count = dest - idx; idx = dest; return count; } CharSequenceReader(final CharSequence charSequence); @Override void close(); @Override void mark(final int readAheadLimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] array, final int offset, final int length); @Override void reset(); @Override long skip(final long n); @Override String toString(); }### Answer:
@Test public void testSkip() throws IOException { final Reader reader = new CharSequenceReader("FooBar"); assertEquals(3, reader.skip(3)); checkRead(reader, "Bar"); assertEquals(-1, reader.skip(3)); reader.reset(); assertEquals(2, reader.skip(2)); assertEquals(4, reader.skip(10)); assertEquals(-1, reader.skip(1)); reader.close(); assertEquals(6, reader.skip(20)); assertEquals(-1, reader.read()); } |
### Question:
CharSequenceReader extends Reader implements Serializable { @Override public int read() { if (idx >= charSequence.length()) { return EOF; } else { return charSequence.charAt(idx++); } } CharSequenceReader(final CharSequence charSequence); @Override void close(); @Override void mark(final int readAheadLimit); @Override boolean markSupported(); @Override int read(); @Override int read(final char[] array, final int offset, final int length); @Override void reset(); @Override long skip(final long n); @Override String toString(); }### Answer:
@Test public void testRead() throws IOException { final Reader reader = new CharSequenceReader("Foo"); assertEquals('F', reader.read()); assertEquals('o', reader.read()); assertEquals('o', reader.read()); assertEquals(-1, reader.read()); assertEquals(-1, reader.read()); reader.close(); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public boolean readBoolean() throws IOException, EOFException { return 0 != readByte(); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadBoolean() throws IOException { bytes = new byte[] { 0x00, 0x01, 0x02, }; final ByteArrayInputStream bais = new ByteArrayInputStream( bytes ); final SwappedDataInputStream sdis = new SwappedDataInputStream( bais ); assertEquals( false, sdis.readBoolean() ); assertEquals( true, sdis.readBoolean() ); assertEquals( true, sdis.readBoolean() ); sdis.close(); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public byte readByte() throws IOException, EOFException { return (byte)in.read(); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadByte() throws IOException { assertEquals( 0x01, this.sdis.readByte() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public char readChar() throws IOException, EOFException { return (char)readShort(); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadChar() throws IOException { assertEquals( (char) 0x0201, this.sdis.readChar() ); } |
### Question:
Elements extends ArrayList<Element> { private Elements siblings(String query, boolean next, boolean all) { Elements els = new Elements(); Evaluator eval = query != null? QueryParser.parse(query) : null; for (Element e : this) { do { Element sib = next ? e.nextElementSibling() : e.previousElementSibling(); if (sib == null) break; if (eval == null) els.add(sib); else if (sib.is(eval)) els.add(sib); e = sib; } while (all); } return els; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void siblings() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12</div>"); Elements els = doc.select("p:eq(3)"); assertEquals(2, els.size()); Elements next = els.next(); assertEquals(2, next.size()); assertEquals("5", next.first().text()); assertEquals("11", next.last().text()); assertEquals(0, els.next("p:contains(6)").size()); final Elements nextF = els.next("p:contains(5)"); assertEquals(1, nextF.size()); assertEquals("5", nextF.first().text()); Elements nextA = els.nextAll(); assertEquals(4, nextA.size()); assertEquals("5", nextA.first().text()); assertEquals("12", nextA.last().text()); Elements nextAF = els.nextAll("p:contains(6)"); assertEquals(1, nextAF.size()); assertEquals("6", nextAF.first().text()); Elements prev = els.prev(); assertEquals(2, prev.size()); assertEquals("3", prev.first().text()); assertEquals("9", prev.last().text()); assertEquals(0, els.prev("p:contains(1)").size()); final Elements prevF = els.prev("p:contains(3)"); assertEquals(1, prevF.size()); assertEquals("3", prevF.first().text()); Elements prevA = els.prevAll(); assertEquals(6, prevA.size()); assertEquals("3", prevA.first().text()); assertEquals("7", prevA.last().text()); Elements prevAF = els.prevAll("p:contains(1)"); assertEquals(1, prevAF.size()); assertEquals("1", prevAF.first().text()); } |
### Question:
ByteObjectArrayTypeHandler extends BaseTypeHandler<Byte[]> { private Byte[] getBytes(byte[] bytes) { Byte[] returnValue = null; if (bytes != null) { returnValue = ByteArrayUtils.convertToObjectArray(bytes); } return returnValue; } @Override void setNonNullParameter(PreparedStatement ps, int index, Byte[] parameter, JdbcType jdbcType); @Override Byte[] getNullableResult(ResultSet rs, int index); @Override JdbcType getJdbcType(); }### Answer:
@Override @Test public void shouldGetResultFromResultSetByPosition() throws Exception { byte[] byteArray = new byte[]{1, 2}; when(rs.getBytes(1)).thenReturn(byteArray); when(rs.wasNull()).thenReturn(false); assertThat(TYPE_HANDLER.getResult(rs, 1), is(new Byte[]{1, 2})); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public double readDouble() throws IOException, EOFException { return EndianUtils.readSwappedDouble( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadDouble() throws IOException { assertEquals( Double.longBitsToDouble(0x0807060504030201L), this.sdis.readDouble(), 0 ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public float readFloat() throws IOException, EOFException { return EndianUtils.readSwappedFloat( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadFloat() throws IOException { assertEquals( Float.intBitsToFloat(0x04030201), this.sdis.readFloat(), 0 ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public void readFully( final byte[] data ) throws IOException, EOFException { readFully( data, 0, data.length ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadFully() throws IOException { final byte[] bytesIn = new byte[8]; this.sdis.readFully(bytesIn); for( int i=0; i<8; i++) { assertEquals( bytes[i], bytesIn[i] ); } } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public int readInt() throws IOException, EOFException { return EndianUtils.readSwappedInteger( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadInt() throws IOException { assertEquals( 0x04030201, this.sdis.readInt() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public String readLine() throws IOException, EOFException { throw new UnsupportedOperationException( "Operation not supported: readLine()" ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testReadLine() throws IOException { this.sdis.readLine(); fail("readLine should be unsupported. "); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public long readLong() throws IOException, EOFException { return EndianUtils.readSwappedLong( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadLong() throws IOException { assertEquals( 0x0807060504030201L, this.sdis.readLong() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public short readShort() throws IOException, EOFException { return EndianUtils.readSwappedShort( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadShort() throws IOException { assertEquals( (short) 0x0201, this.sdis.readShort() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public int readUnsignedByte() throws IOException, EOFException { return in.read(); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadUnsignedByte() throws IOException { assertEquals( 0x01, this.sdis.readUnsignedByte() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public int readUnsignedShort() throws IOException, EOFException { return EndianUtils.readSwappedUnsignedShort( in ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testReadUnsignedShort() throws IOException { assertEquals( (short) 0x0201, this.sdis.readUnsignedShort() ); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public String readUTF() throws IOException, EOFException { throw new UnsupportedOperationException( "Operation not supported: readUTF()" ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test(expected = UnsupportedOperationException.class) public void testReadUTF() throws IOException { this.sdis.readUTF(); fail("readUTF should be unsupported. "); } |
### Question:
Elements extends ArrayList<Element> { public List<String> eachText() { ArrayList<String> texts = new ArrayList<>(size()); for (Element el: this) { if (el.hasText()) texts.add(el.text()); } return texts; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void eachText() { Document doc = Jsoup.parse("<div><p>1<p>2<p>3<p>4<p>5<p>6</div><div><p>7<p>8<p>9<p>10<p>11<p>12<p></p></div>"); List<String> divText = doc.select("div").eachText(); assertEquals(2, divText.size()); assertEquals("1 2 3 4 5 6", divText.get(0)); assertEquals("7 8 9 10 11 12", divText.get(1)); List<String> pText = doc.select("p").eachText(); Elements ps = doc.select("p"); assertEquals(13, ps.size()); assertEquals(12, pText.size()); assertEquals("1", pText.get(0)); assertEquals("2", pText.get(1)); assertEquals("5", pText.get(4)); assertEquals("7", pText.get(6)); assertEquals("12", pText.get(11)); } |
### Question:
SwappedDataInputStream extends ProxyInputStream implements DataInput { public int skipBytes( final int count ) throws IOException, EOFException { return (int)in.skip( count ); } SwappedDataInputStream( final InputStream input ); boolean readBoolean(); byte readByte(); char readChar(); double readDouble(); float readFloat(); void readFully( final byte[] data ); void readFully( final byte[] data, final int offset, final int length ); int readInt(); String readLine(); long readLong(); short readShort(); int readUnsignedByte(); int readUnsignedShort(); String readUTF(); int skipBytes( final int count ); }### Answer:
@Test public void testSkipBytes() throws IOException { this.sdis.skipBytes(4); assertEquals( 0x08070605, this.sdis.readInt() ); } |
### Question:
XmlStreamReader extends Reader { public String getEncoding() { return encoding; } XmlStreamReader(final File file); XmlStreamReader(final InputStream is); XmlStreamReader(final InputStream is, final boolean lenient); XmlStreamReader(final InputStream is, final boolean lenient, final String defaultEncoding); XmlStreamReader(final URL url); XmlStreamReader(final URLConnection conn, final String defaultEncoding); XmlStreamReader(final InputStream is, final String httpContentType); XmlStreamReader(final InputStream is, final String httpContentType,
final boolean lenient, final String defaultEncoding); XmlStreamReader(final InputStream is, final String httpContentType,
final boolean lenient); String getDefaultEncoding(); String getEncoding(); @Override int read(final char[] buf, final int offset, final int len); @Override void close(); static final Pattern ENCODING_PATTERN; }### Answer:
@Test public void testRawContent() throws Exception { final String encoding = "UTF-8"; final String xml = getXML("no-bom", XML3, encoding, encoding); final ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(encoding)); final XmlStreamReader xmlReader = new XmlStreamReader(is); assertEquals("Check encoding", xmlReader.getEncoding(), encoding); assertEquals("Check content", xml, IOUtils.toString(xmlReader)); }
@Test public void testHttpContent() throws Exception { final String encoding = "UTF-8"; final String xml = getXML("no-bom", XML3, encoding, encoding); final ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(encoding)); final XmlStreamReader xmlReader = new XmlStreamReader(is, encoding); assertEquals("Check encoding", xmlReader.getEncoding(), encoding); assertEquals("Check content", xml, IOUtils.toString(xmlReader)); } |
### Question:
BoundedReader extends Reader { @Override public void close() throws IOException { target.close(); } BoundedReader( Reader target, int maxCharsFromTargetReader ); @Override void close(); @Override void reset(); @Override void mark( int readAheadLimit ); @Override int read(); @Override int read( char[] cbuf, int off, int len ); }### Answer:
@Test public void closeTest() throws IOException { final AtomicBoolean closed = new AtomicBoolean( false ); final Reader sr = new BufferedReader( new StringReader( "01234567890" ) ) { @Override public void close() throws IOException { closed.set( true ); super.close(); } }; BoundedReader mr = new BoundedReader( sr, 3 ); mr.close(); assertTrue( closed.get() ); } |
### Question:
BoundedInputStream extends InputStream { @Override public int read() throws IOException { if (max >= 0 && pos >= max) { return EOF; } final int result = in.read(); pos++; return result; } BoundedInputStream(final InputStream in, final long size); BoundedInputStream(final InputStream in); @Override int read(); @Override int read(final byte[] b); @Override int read(final byte[] b, final int off, final int len); @Override long skip(final long n); @Override int available(); @Override String toString(); @Override void close(); @Override synchronized void reset(); @Override synchronized void mark(final int readlimit); @Override boolean markSupported(); boolean isPropagateClose(); void setPropagateClose(final boolean propagateClose); }### Answer:
@Test public void testReadSingle() throws Exception { BoundedInputStream bounded; final byte[] helloWorld = "Hello World".getBytes(); final byte[] hello = "Hello".getBytes(); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length); for (int i = 0; i < helloWorld.length; i++) { assertEquals("limit = length byte[" + i + "]", helloWorld[i], bounded.read()); } assertEquals("limit = length end", -1, bounded.read()); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), helloWorld.length + 1); for (int i = 0; i < helloWorld.length; i++) { assertEquals("limit > length byte[" + i + "]", helloWorld[i], bounded.read()); } assertEquals("limit > length end", -1, bounded.read()); bounded = new BoundedInputStream(new ByteArrayInputStream(helloWorld), hello.length); for (int i = 0; i < hello.length; i++) { assertEquals("limit < length byte[" + i + "]", hello[i], bounded.read()); } assertEquals("limit < length end", -1, bounded.read()); } |
### Question:
Elements extends ArrayList<Element> { public List<String> eachAttr(String attributeKey) { List<String> attrs = new ArrayList<>(size()); for (Element element : this) { if (element.hasAttr(attributeKey)) attrs.add(element.attr(attributeKey)); } return attrs; } Elements(); Elements(int initialCapacity); Elements(Collection<Element> elements); Elements(List<Element> elements); Elements(Element... elements); @Override Elements clone(); String attr(String attributeKey); boolean hasAttr(String attributeKey); List<String> eachAttr(String attributeKey); Elements attr(String attributeKey, String attributeValue); Elements removeAttr(String attributeKey); Elements addClass(String className); Elements removeClass(String className); Elements toggleClass(String className); boolean hasClass(String className); String val(); Elements val(String value); String text(); boolean hasText(); List<String> eachText(); String html(); String outerHtml(); @Override String toString(); Elements tagName(String tagName); Elements html(String html); Elements prepend(String html); Elements append(String html); Elements before(String html); Elements after(String html); Elements wrap(String html); Elements unwrap(); Elements empty(); Elements remove(); Elements select(String query); Elements not(String query); Elements eq(int index); boolean is(String query); Elements next(); Elements next(String query); Elements nextAll(); Elements nextAll(String query); Elements prev(); Elements prev(String query); Elements prevAll(); Elements prevAll(String query); Elements parents(); Element first(); Element last(); Elements traverse(NodeVisitor nodeVisitor); List<FormElement> forms(); }### Answer:
@Test public void eachAttr() { Document doc = Jsoup.parse( "<div><a href='/foo'>1</a><a href='http: "http: List<String> hrefAttrs = doc.select("a").eachAttr("href"); assertEquals(3, hrefAttrs.size()); assertEquals("/foo", hrefAttrs.get(0)); assertEquals("http: assertEquals("", hrefAttrs.get(2)); assertEquals(4, doc.select("a").size()); List<String> absAttrs = doc.select("a").eachAttr("abs:href"); assertEquals(3, absAttrs.size()); assertEquals(3, absAttrs.size()); assertEquals("http: assertEquals("http: assertEquals("http: } |
### Question:
BrokenInputStream extends InputStream { @Override public int read() throws IOException { throw exception; } BrokenInputStream(final IOException exception); BrokenInputStream(); @Override int read(); @Override int available(); @Override long skip(final long n); @Override synchronized void reset(); @Override void close(); }### Answer:
@Test public void testRead() { try { stream.read(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } try { stream.read(new byte[1]); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } try { stream.read(new byte[1], 0, 1); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenInputStream extends InputStream { @Override public int available() throws IOException { throw exception; } BrokenInputStream(final IOException exception); BrokenInputStream(); @Override int read(); @Override int available(); @Override long skip(final long n); @Override synchronized void reset(); @Override void close(); }### Answer:
@Test public void testAvailable() { try { stream.available(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenInputStream extends InputStream { @Override public long skip(final long n) throws IOException { throw exception; } BrokenInputStream(final IOException exception); BrokenInputStream(); @Override int read(); @Override int available(); @Override long skip(final long n); @Override synchronized void reset(); @Override void close(); }### Answer:
@Test public void testSkip() { try { stream.skip(1); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenInputStream extends InputStream { @Override public synchronized void reset() throws IOException { throw exception; } BrokenInputStream(final IOException exception); BrokenInputStream(); @Override int read(); @Override int available(); @Override long skip(final long n); @Override synchronized void reset(); @Override void close(); }### Answer:
@Test public void testReset() { try { stream.reset(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenInputStream extends InputStream { @Override public void close() throws IOException { throw exception; } BrokenInputStream(final IOException exception); BrokenInputStream(); @Override int read(); @Override int available(); @Override long skip(final long n); @Override synchronized void reset(); @Override void close(); }### Answer:
@Test public void testClose() { try { stream.close(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
CountingInputStream extends ProxyInputStream { public int getCount() { final long result = getByteCount(); if (result > Integer.MAX_VALUE) { throw new ArithmeticException("The byte count " + result + " is too large to be converted to an int"); } return (int) result; } CountingInputStream(final InputStream in); @Override synchronized long skip(final long length); int getCount(); int resetCount(); synchronized long getByteCount(); synchronized long resetByteCount(); }### Answer:
@Test public void testCounting() throws Exception { final String text = "A piece of text"; final byte[] bytes = text.getBytes(); final ByteArrayInputStream bais = new ByteArrayInputStream(bytes); final CountingInputStream cis = new CountingInputStream(bais); final byte[] result = new byte[21]; final byte[] ba = new byte[5]; int found = cis.read(ba); System.arraycopy(ba, 0, result, 0, 5); assertEquals( found, cis.getCount() ); final int value = cis.read(); found++; result[5] = (byte)value; assertEquals( found, cis.getCount() ); found += cis.read(result, 6, 5); assertEquals( found, cis.getCount() ); found += cis.read(result, 11, 10); assertEquals( found, cis.getCount() ); final String textResult = new String(result).trim(); assertEquals(textResult, text); cis.close(); }
@Test public void testZeroLength1() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); final CountingInputStream cis = new CountingInputStream(bais); final int found = cis.read(); assertEquals(-1, found); assertEquals(0, cis.getCount()); cis.close(); }
@Test public void testZeroLength2() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); final CountingInputStream cis = new CountingInputStream(bais); final byte[] result = new byte[10]; final int found = cis.read(result); assertEquals(-1, found); assertEquals(0, cis.getCount()); cis.close(); }
@Test public void testZeroLength3() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]); final CountingInputStream cis = new CountingInputStream(bais); final byte[] result = new byte[10]; final int found = cis.read(result, 0, 5); assertEquals(-1, found); assertEquals(0, cis.getCount()); cis.close(); }
@Test public void testEOF1() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); final CountingInputStream cis = new CountingInputStream(bais); int found = cis.read(); assertEquals(0, found); assertEquals(1, cis.getCount()); found = cis.read(); assertEquals(0, found); assertEquals(2, cis.getCount()); found = cis.read(); assertEquals(-1, found); assertEquals(2, cis.getCount()); cis.close(); }
@Test public void testEOF2() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); final CountingInputStream cis = new CountingInputStream(bais); final byte[] result = new byte[10]; final int found = cis.read(result); assertEquals(2, found); assertEquals(2, cis.getCount()); cis.close(); }
@Test public void testEOF3() throws Exception { final ByteArrayInputStream bais = new ByteArrayInputStream(new byte[2]); final CountingInputStream cis = new CountingInputStream(bais); final byte[] result = new byte[10]; final int found = cis.read(result, 0, 5); assertEquals(2, found); assertEquals(2, cis.getCount()); cis.close(); } |
### Question:
AutoCloseInputStream extends ProxyInputStream { @Override public void close() throws IOException { in.close(); in = new ClosedInputStream(); } AutoCloseInputStream(final InputStream in); @Override void close(); }### Answer:
@Test public void testClose() throws IOException { stream.close(); assertTrue("closed", closed); assertEquals("read()", -1, stream.read()); } |
### Question:
DeferredFileOutputStream extends ThresholdingOutputStream { @Override protected void thresholdReached() throws IOException { if (prefix != null) { outputFile = File.createTempFile(prefix, suffix, directory); } final FileOutputStream fos = new FileOutputStream(outputFile); try { memoryOutputStream.writeTo(fos); } catch (IOException e){ fos.close(); throw e; } currentOutputStream = fos; memoryOutputStream = null; } DeferredFileOutputStream(final int threshold, final File outputFile); DeferredFileOutputStream(final int threshold, final String prefix, final String suffix, final File directory); private DeferredFileOutputStream(final int threshold, final File outputFile, final String prefix,
final String suffix, final File directory); boolean isInMemory(); byte[] getData(); File getFile(); @Override void close(); void writeTo(final OutputStream out); }### Answer:
@Test public void testThresholdReached() { final File testFile = new File("testThresholdReached.dat"); testFile.delete(); final DeferredFileOutputStream dfos = new DeferredFileOutputStream(testBytes.length / 2, testFile); final int chunkSize = testBytes.length / 3; try { dfos.write(testBytes, 0, chunkSize); dfos.write(testBytes, chunkSize, chunkSize); dfos.write(testBytes, chunkSize * 2, testBytes.length - chunkSize * 2); dfos.close(); } catch (final IOException e) { fail("Unexpected IOException"); } assertFalse(dfos.isInMemory()); assertNull(dfos.getData()); verifyResultFile(testFile); testFile.delete(); } |
### Question:
DeferredFileOutputStream extends ThresholdingOutputStream { @Override public void close() throws IOException { super.close(); closed = true; } DeferredFileOutputStream(final int threshold, final File outputFile); DeferredFileOutputStream(final int threshold, final String prefix, final String suffix, final File directory); private DeferredFileOutputStream(final int threshold, final File outputFile, final String prefix,
final String suffix, final File directory); boolean isInMemory(); byte[] getData(); File getFile(); @Override void close(); void writeTo(final OutputStream out); }### Answer:
@Test public void testTempFileError() throws Exception { final String prefix = null; final String suffix = ".out"; final File tempDir = new File("."); try { (new DeferredFileOutputStream(testBytes.length - 5, prefix, suffix, tempDir)).close(); fail("Expected IllegalArgumentException "); } catch (final IllegalArgumentException e) { } } |
### Question:
BrokenOutputStream extends OutputStream { @Override public void write(final int b) throws IOException { throw exception; } BrokenOutputStream(final IOException exception); BrokenOutputStream(); @Override void write(final int b); @Override void flush(); @Override void close(); }### Answer:
@Test public void testWrite() { try { stream.write(1); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } try { stream.write(new byte[1]); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } try { stream.write(new byte[1], 0, 1); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenOutputStream extends OutputStream { @Override public void flush() throws IOException { throw exception; } BrokenOutputStream(final IOException exception); BrokenOutputStream(); @Override void write(final int b); @Override void flush(); @Override void close(); }### Answer:
@Test public void testFlush() { try { stream.flush(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
BrokenOutputStream extends OutputStream { @Override public void close() throws IOException { throw exception; } BrokenOutputStream(final IOException exception); BrokenOutputStream(); @Override void write(final int b); @Override void flush(); @Override void close(); }### Answer:
@Test public void testClose() { try { stream.close(); fail("Expected exception not thrown."); } catch (final IOException e) { assertEquals(exception, e); } } |
### Question:
ProxyWriter extends FilterWriter { @Override public void close() throws IOException { try { out.close(); } catch (final IOException e) { handleIOException(e); } } ProxyWriter(final Writer proxy); @Override Writer append(final char c); @Override Writer append(final CharSequence csq, final int start, final int end); @Override Writer append(final CharSequence csq); @Override void write(final int idx); @Override void write(final char[] chr); @Override void write(final char[] chr, final int st, final int len); @Override void write(final String str); @Override void write(final String str, final int st, final int len); @Override void flush(); @Override void close(); }### Answer:
@Test(expected = UnsupportedEncodingException.class) public void exceptions_in_close() throws IOException { OutputStreamWriter osw = new OutputStreamWriter(new ByteArrayOutputStream()) { @Override public void close() throws IOException { throw new UnsupportedEncodingException("Bah"); } }; final ProxyWriter proxy = new ProxyWriter(osw); proxy.close(); } |
### Question:
StringBuilderWriter extends Writer implements Serializable { @Override public void close() { } StringBuilderWriter(); StringBuilderWriter(final int capacity); StringBuilderWriter(final StringBuilder builder); @Override Writer append(final char value); @Override Writer append(final CharSequence value); @Override Writer append(final CharSequence value, final int start, final int end); @Override void close(); @Override void flush(); @Override void write(final String value); @Override void write(final char[] value, final int offset, final int length); StringBuilder getBuilder(); @Override String toString(); }### Answer:
@Test public void testClose() { final Writer writer = new StringBuilderWriter(); try { writer.append("Foo"); writer.close(); writer.append("Bar"); } catch (final Throwable t) { fail("Threw: " + t); } assertEquals("FooBar", writer.toString()); } |
### Question:
ChunkedOutputStream extends FilterOutputStream { @Override public void write(byte[] data, int srcOffset, int length) throws IOException { int bytes = length; int dstOffset = srcOffset; while(bytes > 0) { int chunk = Math.min(bytes, chunkSize); out.write(data, dstOffset, chunk); bytes -= chunk; dstOffset += chunk; } } ChunkedOutputStream(final OutputStream stream, int chunkSize); ChunkedOutputStream(final OutputStream stream); @Override void write(byte[] data, int srcOffset, int length); }### Answer:
@Test public void write_four_chunks() throws Exception { final AtomicInteger numWrites = new AtomicInteger(); ByteArrayOutputStream baos = getByteArrayOutputStream(numWrites); ChunkedOutputStream chunked = new ChunkedOutputStream(baos, 10); chunked.write("0123456789012345678901234567891".getBytes()); assertEquals(4, numWrites.get()); chunked.close(); }
@Test public void defaultConstructor() throws IOException { final AtomicInteger numWrites = new AtomicInteger(); ByteArrayOutputStream baos = getByteArrayOutputStream(numWrites); ChunkedOutputStream chunked = new ChunkedOutputStream(baos); chunked.write(new byte[1024 * 4 + 1]); assertEquals(2, numWrites.get()); chunked.close(); } |
### Question:
CloseShieldOutputStream extends ProxyOutputStream { @Override public void close() { out = new ClosedOutputStream(); } CloseShieldOutputStream(final OutputStream out); @Override void close(); }### Answer:
@Test public void testClose() throws IOException { shielded.close(); assertFalse("closed", closed); try { shielded.write('x'); fail("write(b)"); } catch (final IOException ignore) { } original.write('y'); assertEquals(1, original.size()); assertEquals('y', original.toByteArray()[0]); } |
### Question:
ChunkedWriter extends FilterWriter { @Override public void write(char[] data, int srcOffset, int length) throws IOException { int bytes = length; int dstOffset = srcOffset; while(bytes > 0) { int chunk = Math.min(bytes, chunkSize); out.write(data, dstOffset, chunk); bytes -= chunk; dstOffset += chunk; } } ChunkedWriter(final Writer writer, int chunkSize); ChunkedWriter(final Writer writer); @Override void write(char[] data, int srcOffset, int length); }### Answer:
@Test public void write_four_chunks() throws Exception { final AtomicInteger numWrites = new AtomicInteger(); OutputStreamWriter osw = getOutputStreamWriter(numWrites); ChunkedWriter chunked = new ChunkedWriter(osw, 10); chunked.write("0123456789012345678901234567891".toCharArray()); chunked.flush(); assertEquals(4, numWrites.get()); chunked.close(); }
@Test public void write_two_chunks_default_constructor() throws Exception { final AtomicInteger numWrites = new AtomicInteger(); OutputStreamWriter osw = getOutputStreamWriter(numWrites); ChunkedWriter chunked = new ChunkedWriter(osw); chunked.write(new char[1024 * 4 + 1]); chunked.flush(); assertEquals(2, numWrites.get()); chunked.close(); } |
### Question:
WriterOutputStream extends OutputStream { @Override public void flush() throws IOException { flushOutput(); writer.flush(); } WriterOutputStream(final Writer writer, final CharsetDecoder decoder); WriterOutputStream(final Writer writer, final CharsetDecoder decoder, final int bufferSize,
final boolean writeImmediately); WriterOutputStream(final Writer writer, final Charset charset, final int bufferSize,
final boolean writeImmediately); WriterOutputStream(final Writer writer, final Charset charset); WriterOutputStream(final Writer writer, final String charsetName, final int bufferSize,
final boolean writeImmediately); WriterOutputStream(final Writer writer, final String charsetName); @Deprecated WriterOutputStream(final Writer writer); @Override void write(final byte[] b, int off, int len); @Override void write(final byte[] b); @Override void write(final int b); @Override void flush(); @Override void close(); }### Answer:
@Test public void testFlush() throws IOException { final StringWriter writer = new StringWriter(); final WriterOutputStream out = new WriterOutputStream(writer, "us-ascii", 1024, false); out.write("abc".getBytes("us-ascii")); assertEquals(0, writer.getBuffer().length()); out.flush(); assertEquals("abc", writer.toString()); out.close(); } |
### Question:
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; }### Answer:
@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(); } } |
### Question:
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 write(final byte[] bts); @Override void write(final byte[] bts, final int st, final int end); @Override void flush(); @Override void close(); }### Answer:
@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); } |
### Question:
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, final int off, final int len); @Override synchronized void write(final int b); @Override void flush(); @Override void close(); }### Answer:
@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("Expected " + IOException.class.getName()); } catch (final IOException e) { Assert.assertTrue(goodOs.closed); } }
@Test public void testCloseMainIOException() { final ByteArrayOutputStream badOs = new ExceptionOnCloseByteArrayOutputStream(); final RecordCloseByteArrayOutputStream goodOs = new RecordCloseByteArrayOutputStream(); final TeeOutputStream tos = new TeeOutputStream(badOs, goodOs); try { tos.close(); Assert.fail("Expected " + IOException.class.getName()); } catch (final IOException e) { Assert.assertTrue(goodOs.closed); } } |
### Question:
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; }### Answer:
@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); } |
### Question:
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 void flush(); @Override void close(); int getThreshold(); long getByteCount(); boolean isThresholdExceeded(); }### Answer:
@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 protected void thresholdReached() throws IOException { reached.set( true); } }; tos.write(12); assertFalse( reached.get()); tos.write(12); assertTrue(reached.get()); tos.close(); } |
### Question:
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 Object tag); static void throwCauseIfTaggedWith(final Throwable throwable, final Object tag); Serializable getTag(); @Override IOException getCause(); }### Answer:
@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.isTaggedWith(tagged, UUID.randomUUID())); assertEquals(exception, tagged.getCause()); assertEquals(exception.getMessage(), tagged.getMessage()); } |
### Question:
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(PreparedStatement ps, int i, Byte[] parameter, JdbcType jdbcType); @Override Byte[] getNullableResult(ResultSet rs, int columnIndex); @Override JdbcType getJdbcType(); }### Answer:
@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(TYPE_HANDLER.getResult(rs, 1), is(new Byte[]{1, 2})); } |
### Question:
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, Method method); @Override void invoke(Object object, @Nullable Object parameter); @Override Type getParameterType(); @Override Class<?> getParameterRawType(); }### Answer:
@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 parameterType[class java.lang.String] must be assignable from function's outputType[class java.lang.Integer]"); Method method = E.class.getDeclaredMethod("setX", String.class); FunctionalSetterInvoker.create("x", method); }
@Test public void testException2() throws Exception { thrown.expect(ClassCastException.class); thrown.expectMessage("function[class org.jfaster.mango.invoker.FunctionalSetterInvokerTest$StringToIntegerListFunction] on method[void org.jfaster.mango.invoker.FunctionalSetterInvokerTest$F.setX(java.util.List)] error, method's parameterType[java.util.List<java.lang.String>] must be assignable from function's outputType[java.util.List<java.lang.Integer>]"); Method method = F.class.getDeclaredMethod("setX", List.class); FunctionalSetterInvoker.create("x", method); } |
### Question:
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, Method method); @SuppressWarnings("unchecked") @Override Object invoke(Object obj); @Override Type getReturnType(); @Override Class<?> getReturnRawType(); }### Answer:
@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 inputType[class java.lang.Integer] must be assignable from method's returnType[class java.lang.String]"); Method method = E.class.getDeclaredMethod("getX"); E e = new E(); e.setX("9527"); FunctionalGetterInvoker.create("x", method); }
@Test public void testException2() throws Exception { thrown.expect(ClassCastException.class); thrown.expectMessage("function[class org.jfaster.mango.invoker.FunctionalGetterInvokerTest$IntegerListToStringFunction] on method[java.util.List org.jfaster.mango.invoker.FunctionalGetterInvokerTest$F.getX()] error, function's inputType[java.util.List<java.lang.Integer>] must be assignable from method's returnType[java.util.List<java.lang.String>]"); Method method = F.class.getDeclaredMethod("getX"); F e = new F(); ArrayList<String> x = Lists.newArrayList("xxx"); e.setX(x); FunctionalGetterInvoker.create("x", method); } |
### Question:
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> 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 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)); } |
### Question:
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); }### Answer:
@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 instanceof CombiningEvaluator.And); CombiningEvaluator.And and = (CombiningEvaluator.And) innerEval; assertEquals(2, and.evaluators.size()); assertTrue(and.evaluators.get(0) instanceof Evaluator.Tag); assertTrue(and.evaluators.get(1) instanceof StructuralEvaluator.Parent); } }
@Test public void testParsesMultiCorrectly() { Evaluator eval = QueryParser.parse(".foo > ol, ol > li + li"); assertTrue(eval instanceof CombiningEvaluator.Or); CombiningEvaluator.Or or = (CombiningEvaluator.Or) eval; assertEquals(2, or.evaluators.size()); CombiningEvaluator.And andLeft = (CombiningEvaluator.And) or.evaluators.get(0); CombiningEvaluator.And andRight = (CombiningEvaluator.And) or.evaluators.get(1); assertEquals("ol :ImmediateParent.foo", andLeft.toString()); assertEquals(2, andLeft.evaluators.size()); assertEquals("li :prevli :ImmediateParentol", andRight.toString()); assertEquals(2, andLeft.evaluators.size()); }
@Test(expected = Selector.SelectorParseException.class) public void exceptionOnUncloseAttribute() { Evaluator parse = QueryParser.parse("section > a[href=\"]"); }
@Test(expected = Selector.SelectorParseException.class) public void testParsesSingleQuoteInContains() { Evaluator parse = QueryParser.parse("p:contains(One \" One)"); } |
### Question:
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++) { r[i] = Integer.parseInt(ss[i]); } return r; } @Nullable @Override int[] apply(@Nullable String input); }### Answer:
@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); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new int[]{}))); } |
### Question:
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); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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: assertEquals("http: assertEquals("http: assertEquals("", withBase.absUrl("noval")); Element dodgyBase = new Element(tag, "wtf: assertEquals("http: assertEquals("", dodgyBase.absUrl("relHref")); }
@Test public void handleAbsOnFileUris() { Document doc = Jsoup.parse("<a href='password'>One/a><a href='/var/log/messages'>Two</a>", "file:/etc/"); Element one = doc.select("a").first(); assertEquals("file:/etc/password", one.absUrl("href")); Element two = doc.select("a").get(1); assertEquals("file:/var/log/messages", two.absUrl("href")); }
@Test public void handleAbsOnLocalhostFileUris() { Document doc = Jsoup.parse("<a href='password'>One/a><a href='/var/log/messages'>Two</a>", "file: Element one = doc.select("a").first(); assertEquals("file: }
@Test public void absHandlesRelativeQuery() { Document doc = Jsoup.parse("<a href='?foo'>One</a> <a href='bar.html?foo'>Two</a>", "https: Element a1 = doc.select("a").first(); assertEquals("https: Element a2 = doc.select("a").get(1); assertEquals("https: }
@Test public void absHandlesDotFromIndex() { Document doc = Jsoup.parse("<a href='./one/two.html'>One</a>", "http: Element a1 = doc.select("a").first(); assertEquals("http: } |
### Question:
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(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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())); } |
### Question:
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 attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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()); } |
### Question:
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 attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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"), ""); assertTrue(standAlone.parent() == null); assertTrue(standAlone.root() == standAlone); assertTrue(standAlone.ownerDocument() == null); } |
### Question:
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(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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("<i>five</i>"); assertEquals("<p>One <em>four</em><i>five</i><b>two</b> three</p>", doc.body().html()); } |
### Question:
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 < input.size(); i++) { builder.append(SEPARATOR).append(input.get(i)); } return builder.toString(); } @Nullable @Override String apply(@Nullable List<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(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<String>()); assertThat((String) invoker.invoke(a), is("")); } |
### Question:
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 hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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>five</i>"); assertEquals("<p>One <b>two</b><i>five</i><em>four</em> three</p>", doc.body().html()); } |
### Question:
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(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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())); assertTrue(node instanceof TextNode); assertEquals("Two ", ((TextNode) node).text()); assertEquals(node, twoText); assertEquals(node.parent(), doc.select("div").first()); } |
### Question:
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 Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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, int depth) { accum.append("</" + node.nodeName() + ">"); } }); assertEquals("<div><p><#text></#text></p></div>", accum.toString()); } |
### Question:
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(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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 = (TextNode) div1.childNode(0); TextNode tn2 = (TextNode) divChildren.get(0); tn2.text("Text 1 updated"); assertEquals("Text 1 ", tn1.text()); div2.insertChildren(-1, divChildren); assertEquals("<div id=\"1\">Text 1 <p>One</p> Text 2 <p>Two</p><p>Three</p></div><div id=\"2\">Text 1 updated" +"<p>One</p> Text 2 <p>Two</p><p>Three</p></div>", TextUtil.stripNewlines(doc.body().html())); } |
### Question:
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:".length())); else return ""; } protected Node(); abstract String nodeName(); boolean hasParent(); String attr(String attributeKey); abstract Attributes attributes(); Node attr(String attributeKey, String attributeValue); boolean hasAttr(String attributeKey); Node removeAttr(String attributeKey); Node clearAttributes(); abstract String baseUri(); void setBaseUri(final String baseUri); String absUrl(String attributeKey); Node childNode(int index); List<Node> childNodes(); List<Node> childNodesCopy(); abstract int childNodeSize(); Node parent(); final Node parentNode(); Node root(); Document ownerDocument(); void remove(); Node before(String html); Node before(Node node); Node after(String html); Node after(Node node); Node wrap(String html); Node unwrap(); void replaceWith(Node in); List<Node> siblingNodes(); Node nextSibling(); Node previousSibling(); int siblingIndex(); Node traverse(NodeVisitor nodeVisitor); String outerHtml(); T html(T appendable); String toString(); @Override boolean equals(Object o); boolean hasSameValue(Object o); @Override Node clone(); }### Answer:
@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"), getAttributesCaseInsensitive(inputElement, "value")); } |
### Question:
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(); @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 testXhtmlReferences() { Document doc = Jsoup.parse("< > & " ' ×"); doc.outputSettings().escapeMode(Entities.EscapeMode.xhtml); assertEquals("< > & \" ' ×", doc.body().html()); }
@Test public void testHtmlAndXmlSyntax() { String h = "<!DOCTYPE html><body><img async checked='checked' src='&<>\"'><>&"<foo />bar"; Document doc = Jsoup.parse(h); doc.outputSettings().syntax(Syntax.html); assertEquals("<!doctype html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async checked src=\"&<>"\"><>&\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); doc.outputSettings().syntax(Document.OutputSettings.Syntax.xml); assertEquals("<!DOCTYPE html>\n" + "<html>\n" + " <head></head>\n" + " <body>\n" + " <img async=\"\" checked=\"checked\" src=\"&<>"\" /><>&\"\n" + " <foo />bar\n" + " </body>\n" + "</html>", doc.html()); }
@Test public void htmlParseDefaultsToHtmlOutputSyntax() { Document doc = Jsoup.parse("x"); assertEquals(Syntax.html, doc.outputSettings().syntax()); }
@Test public void testHtmlAppendable() { String htmlContent = "<html><head><title>Hello</title></head><body><p>One</p><p>Two</p></body></html>"; Document document = Jsoup.parse(htmlContent); OutputSettings outputSettings = new OutputSettings(); outputSettings.prettyPrint(false); document.outputSettings(outputSettings); assertEquals(htmlContent, document.html(new StringWriter()).toString()); } |
### Question:
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 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 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().text("One more").attr("id", "1"); assertEquals("<html><head><title>Hello there</title> </head><body><p id=\"1\">One more</p><p>Two</p></body></html>", TextUtil.stripNewlines(clone.html())); assertEquals("<html><head><title>Hello</title> </head><body><p>One</p><p>Two</p></body></html>", TextUtil.stripNewlines(doc.html())); }
@Test public void testClonesDeclarations() { Document doc = Jsoup.parse("<!DOCTYPE html><html><head><title>Doctype test"); Document clone = doc.clone(); assertEquals(doc.html(), clone.html()); assertEquals("<!doctype html><html><head><title>Doctype test</title></head><body></body></html>", TextUtil.stripNewlines(clone.html())); }
@Ignore @Test public void testOverflowClone() { StringBuilder builder = new StringBuilder(); for (int i = 0; i < 100000; i++) { builder.insert(0, "<i>"); builder.append("</i>"); } Document doc = Jsoup.parse(builder.toString()); doc.clone(); } |
### Question:
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 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 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-article-1.html"); doc = Jsoup.parse(in, null, "http: location = doc.location(); baseUri = doc.baseUri(); assertEquals("http: assertEquals("http: } |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.