method2testcases
stringlengths
118
3.08k
### 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: 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: 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: 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: 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: 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 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 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 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: }
### Question: GsonToObjectFunction implements RuntimeSetterFunction<String, Object> { @Nullable @Override public Object apply(@Nullable String input, Type runtimeOutputType) { return input == null ? null : new Gson().fromJson(input, runtimeOutputType); } @Nullable @Override Object apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); String json = new Gson().toJson(list); Method m = A.class.getDeclaredMethod("setList", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("list", m); invoker.invoke(a, json); assertThat(a.getList().toString(), equalTo(list.toString())); B b = new B(3, 5); String json2 = new Gson().toJson(b); Method m2 = A.class.getDeclaredMethod("setB", B.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("b", m2); invoker2.invoke(a, json2); assertThat(a.getB(), equalTo(b)); }
### Question: Document extends Element { public static Document createShell(String baseUri) { Validate.notNull(baseUri); Document doc = new Document(baseUri); Element html = doc.appendElement("html"); html.appendElement("head"); html.appendElement("body"); return doc; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdateDisabled() { final Document docDisabled = Document.createShell(""); final String htmlNoCharset = "<html>\n" + " <head></head>\n" + " <body></body>\n" + "</html>"; assertEquals(htmlNoCharset, docDisabled.toString()); assertNull(docDisabled.select("meta[charset]").first()); }
### Question: Document extends Element { public void charset(Charset charset) { updateMetaCharsetElement(true); outputSettings.charset(charset); ensureMetaCharsetElement(); } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdateEnabledAfterCharsetChange() { final Document doc = createHtmlDocument("dontTouch"); doc.charset(Charset.forName(charsetUtf8)); Element selectedElement = doc.select("meta[charset]").first(); assertEquals(charsetUtf8, selectedElement.attr("charset")); assertTrue(doc.select("meta[name=charset]").isEmpty()); }
### Question: Document extends Element { public void updateMetaCharsetElement(boolean update) { this.updateMetaCharset = update; } Document(String baseUri); static Document createShell(String baseUri); String location(); Element head(); Element body(); String title(); void title(String title); Element createElement(String tagName); Document normalise(); @Override String outerHtml(); @Override Element text(String text); @Override String nodeName(); void charset(Charset charset); Charset charset(); void updateMetaCharsetElement(boolean update); boolean updateMetaCharsetElement(); @Override Document clone(); OutputSettings outputSettings(); Document outputSettings(OutputSettings outputSettings); QuirksMode quirksMode(); Document quirksMode(QuirksMode quirksMode); }### Answer: @Test public void testMetaCharsetUpdatedDisabledPerDefault() { final Document doc = createHtmlDocument("none"); assertFalse(doc.updateMetaCharsetElement()); }
### Question: FormElement extends Element { public Elements elements() { return elements; } FormElement(Tag tag, String baseUri, Attributes attributes); Elements elements(); FormElement addElement(Element element); Connection submit(); List<Connection.KeyVal> formData(); }### Answer: @Test public void hasAssociatedControls() { String html = "<form id=1><button id=1><fieldset id=2 /><input id=3><keygen id=4><object id=5><output id=6>" + "<select id=7><option></select><textarea id=8><p id=9>"; Document doc = Jsoup.parse(html); FormElement form = (FormElement) doc.select("form").first(); assertEquals(8, form.elements().size()); } @Test public void formsAddedAfterParseAreFormElements() { Document doc = Jsoup.parse("<body />"); doc.body().html("<form action='http: Element formEl = doc.select("form").first(); assertTrue(formEl instanceof FormElement); FormElement form = (FormElement) formEl; assertEquals(1, form.elements().size()); }
### Question: ObjectToGsonFunction implements GetterFunction<Object, String> { @Nullable @Override public String apply(@Nullable Object input) { return input == null ? null : new Gson().toJson(input); } @Nullable @Override String apply(@Nullable Object input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); a.setList(list); Method m = A.class.getDeclaredMethod("getList"); GetterInvoker invoker = FunctionalGetterInvoker.create("list", m); String r = (String) invoker.invoke(a); assertThat(r, is(new Gson().toJson(list))); B b = new B(3, 5); a.setB(b); Method m2 = A.class.getDeclaredMethod("getB"); GetterInvoker invoker2 = FunctionalGetterInvoker.create("b", m2); String r2 = (String) invoker2.invoke(a); assertThat(r2, is(new Gson().toJson(b))); }
### Question: Attribute implements Map.Entry<String, String>, Cloneable { public String html() { StringBuilder accum = new StringBuilder(); try { html(accum, (new Document("")).outputSettings()); } catch(IOException exception) { throw new SerializationException(exception); } return accum.toString(); } Attribute(String key, String value); Attribute(String key, String val, Attributes parent); String getKey(); void setKey(String key); String getValue(); String setValue(String val); String html(); @Override String toString(); static Attribute createFromEncoded(String unencodedKey, String encodedValue); @Override boolean equals(Object o); @Override int hashCode(); @Override Attribute clone(); }### Answer: @Test public void html() { Attribute attr = new Attribute("key", "value &"); assertEquals("key=\"value &amp;\"", attr.html()); assertEquals(attr.html(), attr.toString()); }
### Question: TextNode extends LeafNode { public boolean isBlank() { return StringUtil.isBlank(coreValue()); } TextNode(String text); TextNode(String text, String baseUri); String nodeName(); String text(); TextNode text(String text); String getWholeText(); boolean isBlank(); TextNode splitText(int offset); @Override String toString(); static TextNode createFromEncoded(String encodedText, String baseUri); static TextNode createFromEncoded(String encodedText); }### Answer: @Test public void testBlank() { TextNode one = new TextNode(""); TextNode two = new TextNode(" "); TextNode three = new TextNode(" \n\n "); TextNode four = new TextNode("Hello"); TextNode five = new TextNode(" \nHello "); assertTrue(one.isBlank()); assertTrue(two.isBlank()); assertTrue(three.isBlank()); assertFalse(four.isBlank()); assertFalse(five.isBlank()); }
### Question: TextNode extends LeafNode { public TextNode splitText(int offset) { final String text = coreValue(); Validate.isTrue(offset >= 0, "Split offset must be not be negative"); Validate.isTrue(offset < text.length(), "Split offset must not be greater than current text length"); String head = text.substring(0, offset); String tail = text.substring(offset); text(head); TextNode tailNode = new TextNode(tail, this.baseUri()); if (parent() != null) parent().addChildren(siblingIndex()+1, tailNode); return tailNode; } TextNode(String text); TextNode(String text, String baseUri); String nodeName(); String text(); TextNode text(String text); String getWholeText(); boolean isBlank(); TextNode splitText(int offset); @Override String toString(); static TextNode createFromEncoded(String encodedText, String baseUri); static TextNode createFromEncoded(String encodedText); }### Answer: @Test public void testSplitText() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); assertEquals("Hello ", tn.getWholeText()); assertEquals("there", tail.getWholeText()); tail.text("there!"); assertEquals("Hello there!", div.text()); assertTrue(tn.parent() == tail.parent()); } @Test public void testSplitAnEmbolden() { Document doc = Jsoup.parse("<div>Hello there</div>"); Element div = doc.select("div").first(); TextNode tn = (TextNode) div.childNode(0); TextNode tail = tn.splitText(6); tail.wrap("<b></b>"); assertEquals("Hello <b>there</b>", TextUtil.stripNewlines(div.html())); }
### Question: ObjectToFastjsonFunction implements GetterFunction<Object, String> { @Nullable @Override public String apply(@Nullable Object input) { return input == null ? null : JSON.toJSONString(input); } @Nullable @Override String apply(@Nullable Object input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); a.setList(list); Method m = A.class.getDeclaredMethod("getList"); GetterInvoker invoker = FunctionalGetterInvoker.create("list", m); String r = (String) invoker.invoke(a); assertThat(r, is(JSON.toJSONString(list))); B b = new B(3, 5); a.setB(b); Method m2 = A.class.getDeclaredMethod("getB"); GetterInvoker invoker2 = FunctionalGetterInvoker.create("b", m2); String r2 = (String) invoker2.invoke(a); assertThat(r2, is(JSON.toJSONString(b))); }
### Question: FastjsonToObjectFunction implements RuntimeSetterFunction<String, Object> { @Nullable @Override public Object apply(@Nullable String input, Type runtimeOutputType) { return input == null ? null : JSON.parseObject(input, runtimeOutputType); } @Nullable @Override Object apply(@Nullable String input, Type runtimeOutputType); }### Answer: @Test public void testApply() throws Exception { A a = new A(); List<Integer> list = Lists.newArrayList(1, 2, 3); String json = JSON.toJSONString(list); Method m = A.class.getDeclaredMethod("setList", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("list", m); invoker.invoke(a, json); assertThat(a.getList().toString(), equalTo(list.toString())); B b = new B(3, 5); String json2 = JSON.toJSONString(b); Method m2 = A.class.getDeclaredMethod("setB", B.class); SetterInvoker invoker2 = FunctionalSetterInvoker.create("b", m2); invoker2.invoke(a, json2); assertThat(a.getB(), equalTo(b)); }
### Question: StringToLongArrayFunction implements SetterFunction<String, long[]> { @Nullable @Override public long[] apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new long[0]; } String[] ss = input.split(SEPARATOR); long[] r = new long[ss.length]; for (int i = 0; i < ss.length; i++) { r[i] = Long.parseLong(ss[i]); } return r; } @Nullable @Override long[] apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", long[].class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1000000000000000000,2,3"); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new long[]{1000000000000000000L, 2, 3}))); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new long[]{}))); }
### Question: Entities { public static String getByName(String name) { String val = multipoints.get(name); if (val != null) return val; int codepoint = extended.codepointForName(name); if (codepoint != empty) return new String(new int[]{codepoint}, 0, 1); return emptyName; } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); }### Answer: @Test public void getByName() { assertEquals("≫⃒", Entities.getByName("nGt")); assertEquals("fj", Entities.getByName("fjlig")); assertEquals("≫", Entities.getByName("gg")); assertEquals("©", Entities.getByName("copy")); }
### Question: Entities { static String unescape(String string) { return unescape(string, false); } private Entities(); static boolean isNamedEntity(final String name); static boolean isBaseNamedEntity(final String name); static Character getCharacterByName(String name); static String getByName(String name); static int codepointsForName(final String name, final int[] codepoints); }### Answer: @Test public void notMissingMultis() { String text = "&nparsl;"; String un = "\u2AFD\u20E5"; assertEquals(un, Entities.unescape(text)); } @Test public void notMissingSupplementals() { String text = "&npolint; &qfr;"; String un = "⨔ \uD835\uDD2E"; assertEquals(un, Entities.unescape(text)); } @Test public void unescape() { String text = "Hello &AElig; &amp;&LT&gt; &reg &angst; &angst &#960; &#960 &#x65B0; there &! &frac34; &copy; &COPY;"; assertEquals("Hello Æ &<> ® Å &angst π π 新 there &! ¾ © ©", Entities.unescape(text)); assertEquals("&0987654321; &unknown", Entities.unescape("&0987654321; &unknown")); } @Test public void strictUnescape() { String text = "Hello &amp= &amp;"; assertEquals("Hello &amp= &", Entities.unescape(text, true)); assertEquals("Hello &= &", Entities.unescape(text)); assertEquals("Hello &= &", Entities.unescape(text, false)); } @Test public void quoteReplacements() { String escaped = "&#92; &#36;"; String unescaped = "\\ $"; assertEquals(unescaped, Entities.unescape(escaped)); } @Test public void noSpuriousDecodes() { String string = "http: assertEquals(string, Entities.unescape(string)); }
### Question: StringArrayToStringFunction implements GetterFunction<String[], String> { @Nullable @Override public String apply(@Nullable String[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable String[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new String[]{"1", "2", "3"}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new String[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: StringToStringArrayFunction implements SetterFunction<String, String[]> { @Nullable @Override public String[] apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new String[0]; } return input.split(SEPARATOR); } @Nullable @Override String[] apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", String[].class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new String[]{"1", "2", "3"}))); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(Arrays.toString(a.getX()), is(Arrays.toString(new String[]{}))); }
### Question: IntArrayToStringFunction implements GetterFunction<int[], String> { @Nullable @Override public String apply(@Nullable int[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable int[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new int[]{1, 2, 3}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new int[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: TypeToken extends TypeCapture<T> implements Serializable { public final Class<? super T> getRawType() { Class<?> rawType = getRawType(runtimeType); @SuppressWarnings("unchecked") Class<? super T> result = (Class<? super T>) rawType; return result; } protected TypeToken(); private TypeToken(Type type); static TypeToken<T> of(Class<T> type); static TypeToken<?> of(Type type); final Class<? super T> getRawType(); final Type getType(); final TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg); final TypeToken<?> resolveType(Type type); final boolean isAssignableFrom(TypeToken<?> type); final boolean isAssignableFrom(Type type); final boolean isArray(); final boolean isPrimitive(); final TypeToken<T> wrap(); @Nullable final TypeToken<?> getComponentType(); @Override boolean equals(@Nullable Object o); @Override int hashCode(); @Override String toString(); TypeToken<?> resolveFatherClass(Class<?> clazz); TokenTuple resolveFatherClassTuple(Class<?> clazz); }### Answer: @Test public void testGetRawType() throws Exception { TypeToken<List<String>> token = new TypeToken<List<String>>() { }; assertThat(token.getRawType().equals(List.class), is(true)); TypeToken<String> token2 = new TypeToken<String>() { }; assertThat(token2.getRawType().equals(String.class), is(true)); }
### Question: Cleaner { public boolean isValidBodyHtml(String bodyHtml) { Document clean = Document.createShell(""); Document dirty = Document.createShell(""); ParseErrorList errorList = ParseErrorList.tracking(1); List<Node> nodes = Parser.parseFragment(bodyHtml, dirty.body(), "", errorList); dirty.body().insertChildren(0, nodes); int numDiscarded = copySafeNodes(dirty.body(), clean.body()); return numDiscarded == 0 && errorList.size() == 0; } Cleaner(Whitelist whitelist); Document clean(Document dirtyDocument); boolean isValid(Document dirtyDocument); boolean isValidBodyHtml(String bodyHtml); }### Answer: @Test public void testIsValidBodyHtml() { String ok = "<p>Test <b><a href='http: String ok1 = "<p>Test <b><a href='http: String nok1 = "<p><script></script>Not <b>OK</b></p>"; String nok2 = "<p align=right>Test Not <b>OK</b></p>"; String nok3 = "<!-- comment --><p>Not OK</p>"; String nok4 = "<html><head>Foo</head><body><b>OK</b></body></html>"; String nok5 = "<p>Test <b><a href='http: String nok6 = "<p>Test <b><a href='http: String nok7 = "</div>What"; assertTrue(Jsoup.isValid(ok, Whitelist.basic())); assertTrue(Jsoup.isValid(ok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok1, Whitelist.basic())); assertFalse(Jsoup.isValid(nok2, Whitelist.basic())); assertFalse(Jsoup.isValid(nok3, Whitelist.basic())); assertFalse(Jsoup.isValid(nok4, Whitelist.basic())); assertFalse(Jsoup.isValid(nok5, Whitelist.basic())); assertFalse(Jsoup.isValid(nok6, Whitelist.basic())); assertFalse(Jsoup.isValid(ok, Whitelist.none())); assertFalse(Jsoup.isValid(nok7, Whitelist.basic())); }
### Question: Cleaner { public boolean isValid(Document dirtyDocument) { Validate.notNull(dirtyDocument); Document clean = Document.createShell(dirtyDocument.baseUri()); int numDiscarded = copySafeNodes(dirtyDocument.body(), clean.body()); return numDiscarded == 0 && dirtyDocument.head().childNodes().size() == 0; } Cleaner(Whitelist whitelist); Document clean(Document dirtyDocument); boolean isValid(Document dirtyDocument); boolean isValidBodyHtml(String bodyHtml); }### Answer: @Test public void testIsValidDocument() { String ok = "<html><head></head><body><p>Hello</p></body><html>"; String nok = "<html><head><script>woops</script><title>Hello</title></head><body><p>Hello</p></body><html>"; Whitelist relaxed = Whitelist.relaxed(); Cleaner cleaner = new Cleaner(relaxed); Document okDoc = Jsoup.parse(ok); assertTrue(cleaner.isValid(okDoc)); assertFalse(cleaner.isValid(Jsoup.parse(nok))); assertFalse(new Cleaner(Whitelist.none()).isValid(okDoc)); } @Test public void testScriptTagInWhiteList() { Whitelist whitelist = Whitelist.relaxed(); whitelist.addTags( "script" ); assertTrue( Jsoup.isValid("Hello<script>alert('Doh')</script>World !", whitelist ) ); }
### Question: StringToIntegerListFunction implements SetterFunction<String, List<Integer>> { @Nullable @Override public List<Integer> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<Integer>(); } String[] ss = input.split(SEPARATOR); List<Integer> r = new ArrayList<Integer>(); for (int i = 0; i < ss.length; i++) { r.add(Integer.parseInt(ss[i])); } return r; } @Nullable @Override List<Integer> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); List<Integer> list = Lists.newArrayList(1, 2, 3); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<Integer>().toString())); }
### Question: CharacterReader { char consume() { bufferUp(); char val = isEmpty() ? EOF : charBuf[bufPos]; bufPos++; return val; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consume() { CharacterReader r = new CharacterReader("one"); assertEquals(0, r.pos()); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals(1, r.pos()); assertEquals('n', r.current()); assertEquals(1, r.pos()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); }
### Question: CharacterReader { void unconsume() { bufPos--; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void unconsume() { CharacterReader r = new CharacterReader("one"); assertEquals('o', r.consume()); assertEquals('n', r.current()); r.unconsume(); assertEquals('o', r.current()); assertEquals('o', r.consume()); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.unconsume(); assertFalse(r.isEmpty()); assertEquals('e', r.current()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.consume()); r.unconsume(); assertTrue(r.isEmpty()); assertEquals(CharacterReader.EOF, r.current()); }
### Question: CharacterReader { void mark() { bufMark = bufPos; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void mark() { CharacterReader r = new CharacterReader("one"); r.consume(); r.mark(); assertEquals('n', r.consume()); assertEquals('e', r.consume()); assertTrue(r.isEmpty()); r.rewindToMark(); assertEquals('n', r.consume()); }
### Question: CharacterReader { String consumeToEnd() { bufferUp(); String data = cacheString(charBuf, stringCache, bufPos, bufLength - bufPos); bufPos = bufLength; return data; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeToEnd() { String in = "one two three"; CharacterReader r = new CharacterReader(in); String toEnd = r.consumeToEnd(); assertEquals(in, toEnd); assertTrue(r.isEmpty()); }
### Question: CharacterReader { int nextIndexOf(char c) { bufferUp(); for (int i = bufPos; i < bufLength; i++) { if (c == charBuf[i]) return i - bufPos; } return -1; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void nextIndexOfUnmatched() { CharacterReader r = new CharacterReader("<[[one]]"); assertEquals(-1, r.nextIndexOf("]]>")); }
### Question: StringToLongListFunction implements SetterFunction<String, List<Long>> { @Nullable @Override public List<Long> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<Long>(); } String[] ss = input.split(SEPARATOR); List<Long> r = new ArrayList<Long>(); for (int i = 0; i < ss.length; i++) { r.add(Long.parseLong(ss[i])); } return r; } @Nullable @Override List<Long> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "100000000000000000,2,3"); List<Long> list = Lists.newArrayList(100000000000000000L, 2L, 3L); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<Long>().toString())); }
### Question: CharacterReader { public void advance() { bufPos++; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void advance() { CharacterReader r = new CharacterReader("One Two Three"); assertEquals('O', r.consume()); r.advance(); assertEquals('e', r.consume()); }
### Question: CharacterReader { public String consumeToAny(final char... chars) { bufferUp(); final int start = bufPos; final int remaining = bufLength; final char[] val = charBuf; OUTER: while (bufPos < remaining) { for (char c : chars) { if (val[bufPos] == c) break OUTER; } bufPos++; } return bufPos > start ? cacheString(charBuf, stringCache, start, bufPos -start) : ""; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeToAny() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One ", r.consumeToAny('&', ';')); assertTrue(r.matches('&')); assertTrue(r.matches("&bar;")); assertEquals('&', r.consume()); assertEquals("bar", r.consumeToAny('&', ';')); assertEquals(';', r.consume()); assertEquals(" qux", r.consumeToAny('&', ';')); }
### Question: CharacterReader { String consumeLetterSequence() { bufferUp(); int start = bufPos; while (bufPos < bufLength) { char c = charBuf[bufPos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)) bufPos++; else break; } return cacheString(charBuf, stringCache, start, bufPos - start); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeLetterSequence() { CharacterReader r = new CharacterReader("One &bar; qux"); assertEquals("One", r.consumeLetterSequence()); assertEquals(" &", r.consumeTo("bar;")); assertEquals("bar", r.consumeLetterSequence()); assertEquals("; qux", r.consumeToEnd()); }
### Question: CharacterReader { String consumeLetterThenDigitSequence() { bufferUp(); int start = bufPos; while (bufPos < bufLength) { char c = charBuf[bufPos]; if ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || Character.isLetter(c)) bufPos++; else break; } while (!isEmpty()) { char c = charBuf[bufPos]; if (c >= '0' && c <= '9') bufPos++; else break; } return cacheString(charBuf, stringCache, start, bufPos - start); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void consumeLetterThenDigitSequence() { CharacterReader r = new CharacterReader("One12 Two &bar; qux"); assertEquals("One12", r.consumeLetterThenDigitSequence()); assertEquals(' ', r.consume()); assertEquals("Two", r.consumeLetterThenDigitSequence()); assertEquals(" &bar; qux", r.consumeToEnd()); }
### Question: CharacterReader { boolean matches(char c) { return !isEmpty() && charBuf[bufPos] == c; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matches() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matches('O')); assertTrue(r.matches("One Two Three")); assertTrue(r.matches("One")); assertFalse(r.matches("one")); assertEquals('O', r.consume()); assertFalse(r.matches("One")); assertTrue(r.matches("ne Two Three")); assertFalse(r.matches("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matches("ne")); assertTrue(r.isEmpty()); }
### Question: CharacterReader { boolean matchesIgnoreCase(String seq) { bufferUp(); int scanLength = seq.length(); if (scanLength > bufLength - bufPos) return false; for (int offset = 0; offset < scanLength; offset++) { char upScan = Character.toUpperCase(seq.charAt(offset)); char upTarget = Character.toUpperCase(charBuf[bufPos + offset]); if (upScan != upTarget) return false; } return true; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matchesIgnoreCase() { CharacterReader r = new CharacterReader("One Two Three"); assertTrue(r.matchesIgnoreCase("O")); assertTrue(r.matchesIgnoreCase("o")); assertTrue(r.matches('O')); assertFalse(r.matches('o')); assertTrue(r.matchesIgnoreCase("One Two Three")); assertTrue(r.matchesIgnoreCase("ONE two THREE")); assertTrue(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("one")); assertEquals('O', r.consume()); assertFalse(r.matchesIgnoreCase("One")); assertTrue(r.matchesIgnoreCase("NE Two Three")); assertFalse(r.matchesIgnoreCase("ne Two Three Four")); assertEquals("ne Two Three", r.consumeToEnd()); assertFalse(r.matchesIgnoreCase("ne")); }
### Question: CharacterReader { boolean containsIgnoreCase(String seq) { String loScan = seq.toLowerCase(Locale.ENGLISH); String hiScan = seq.toUpperCase(Locale.ENGLISH); return (nextIndexOf(loScan) > -1) || (nextIndexOf(hiScan) > -1); } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void containsIgnoreCase() { CharacterReader r = new CharacterReader("One TWO three"); assertTrue(r.containsIgnoreCase("two")); assertTrue(r.containsIgnoreCase("three")); assertFalse(r.containsIgnoreCase("one")); }
### Question: CharacterReader { boolean matchesAny(char... seq) { if (isEmpty()) return false; bufferUp(); char c = charBuf[bufPos]; for (char seek : seq) { if (seek == c) return true; } return false; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void matchesAny() { char[] scan = {' ', '\n', '\t'}; CharacterReader r = new CharacterReader("One\nTwo\tThree"); assertFalse(r.matchesAny(scan)); assertEquals("One", r.consumeToAny(scan)); assertTrue(r.matchesAny(scan)); assertEquals('\n', r.consume()); assertFalse(r.matchesAny(scan)); }
### Question: CharacterReader { static boolean rangeEquals(final char[] charBuf, final int start, int count, final String cached) { if (count == cached.length()) { int i = start; int j = 0; while (count-- != 0) { if (charBuf[i++] != cached.charAt(j++)) return false; } return true; } return false; } CharacterReader(Reader input, int sz); CharacterReader(Reader input); CharacterReader(String input); int pos(); boolean isEmpty(); char current(); void advance(); String consumeTo(char c); String consumeToAny(final char... chars); @Override String toString(); }### Answer: @Test public void rangeEquals() { CharacterReader r = new CharacterReader("Check\tCheck\tCheck\tCHOKE"); assertTrue(r.rangeEquals(0, 5, "Check")); assertFalse(r.rangeEquals(0, 5, "CHOKE")); assertFalse(r.rangeEquals(0, 5, "Chec")); assertTrue(r.rangeEquals(6, 5, "Check")); assertFalse(r.rangeEquals(6, 5, "Chuck")); assertTrue(r.rangeEquals(12, 5, "Check")); assertFalse(r.rangeEquals(12, 5, "Cheeky")); assertTrue(r.rangeEquals(18, 5, "CHOKE")); assertFalse(r.rangeEquals(18, 5, "CHIKE")); }
### Question: LongArrayToStringFunction implements GetterFunction<long[], String> { @Nullable @Override public String apply(@Nullable long[] input) { if (input == null) { return null; } if (input.length == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input[0]); for (int i = 1; i < input.length; i++) { builder.append(SEPARATOR).append(input[i]); } return builder.toString(); } @Nullable @Override String apply(@Nullable long[] input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(new long[]{1, 2, 3}); assertThat((String) invoker.invoke(a), is("1,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new long[]{}); assertThat((String) invoker.invoke(a), is("")); }
### Question: TokenQueue { public static String unescape(String in) { StringBuilder out = StringUtil.stringBuilder(); char last = 0; for (char c : in.toCharArray()) { if (c == ESC) { if (last != 0 && last == ESC) out.append(c); } else out.append(c); last = c; } return out.toString(); } TokenQueue(String data); boolean isEmpty(); char peek(); void addFirst(Character c); void addFirst(String seq); boolean matches(String seq); boolean matchesCS(String seq); boolean matchesAny(String... seq); boolean matchesAny(char... seq); boolean matchesStartTag(); boolean matchChomp(String seq); boolean matchesWhitespace(); boolean matchesWord(); void advance(); char consume(); void consume(String seq); String consumeTo(String seq); String consumeToIgnoreCase(String seq); String consumeToAny(String... seq); String chompTo(String seq); String chompToIgnoreCase(String seq); String chompBalanced(char open, char close); static String unescape(String in); boolean consumeWhitespace(); String consumeWord(); String consumeTagName(); String consumeElementSelector(); String consumeCssIdentifier(); String consumeAttributeKey(); String remainder(); @Override String toString(); }### Answer: @Test public void unescape() { assertEquals("one ( ) \\", TokenQueue.unescape("one \\( \\) \\\\")); }
### Question: LongListToStringFunction implements GetterFunction<List<Long>, String> { @Nullable @Override public String apply(@Nullable List<Long> input) { if (input == null) { return null; } if (input.size() == 0) { return ""; } StringBuilder builder = new StringBuilder(); builder.append(input.get(0)); for (int i = 1; i < input.size(); i++) { builder.append(SEPARATOR).append(input.get(i)); } return builder.toString(); } @Nullable @Override String apply(@Nullable List<Long> input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("getX"); GetterInvoker invoker = FunctionalGetterInvoker.create("x", m); a.setX(Lists.newArrayList(1000000000000000L, 2l, 3L)); assertThat((String) invoker.invoke(a), is("1000000000000000,2,3")); a.setX(null); assertThat(invoker.invoke(a), nullValue()); a.setX(new ArrayList<Long>()); assertThat((String) invoker.invoke(a), is("")); }
### Question: Tag { public static Tag valueOf(String tagName, ParseSettings settings) { Validate.notNull(tagName); Tag tag = tags.get(tagName); if (tag == null) { tagName = settings.normalizeTag(tagName); Validate.notEmpty(tagName); tag = tags.get(tagName); if (tag == null) { tag = new Tag(tagName); tag.isBlock = false; } } return tag; } private Tag(String tagName); String getName(); static Tag valueOf(String tagName, ParseSettings settings); static Tag valueOf(String tagName); boolean isBlock(); boolean formatAsBlock(); boolean canContainBlock(); boolean isInline(); boolean isData(); boolean isEmpty(); boolean isSelfClosing(); boolean isKnownTag(); static boolean isKnownTag(String tagName); boolean preserveWhitespace(); boolean isFormListed(); boolean isFormSubmittable(); @Override boolean equals(Object o); @Override int hashCode(); @Override String toString(); }### Answer: @Test @MultiLocaleTest public void canBeInsensitive() { Tag script1 = Tag.valueOf("script", ParseSettings.htmlDefault); Tag script2 = Tag.valueOf("SCRIPT", ParseSettings.htmlDefault); assertSame(script1, script2); } @Test public void trims() { Tag p1 = Tag.valueOf("p"); Tag p2 = Tag.valueOf(" p "); assertEquals(p1, p2); } @Test(expected = IllegalArgumentException.class) public void valueOfChecksNotNull() { Tag.valueOf(null); } @Test(expected = IllegalArgumentException.class) public void valueOfChecksNotEmpty() { Tag.valueOf(" "); }
### Question: StringToStringListFunction implements SetterFunction<String, List<String>> { @Nullable @Override public List<String> apply(@Nullable String input) { if (input == null) { return null; } if (input.length() == 0) { return new ArrayList<String>(); } String[] ss = input.split(SEPARATOR); List<String> r = new ArrayList<String>(); for (int i = 0; i < ss.length; i++) { r.add(ss[i]); } return r; } @Nullable @Override List<String> apply(@Nullable String input); }### Answer: @Test public void testApply() throws Exception { A a = new A(); Method m = A.class.getDeclaredMethod("setX", List.class); SetterInvoker invoker = FunctionalSetterInvoker.create("x", m); invoker.invoke(a, "1,2,3"); List<String> list = Lists.newArrayList("1", "2", "3"); assertThat(a.getX().toString(), is(list.toString())); invoker.invoke(a, null); assertThat(a.getX(), nullValue()); invoker.invoke(a, ""); assertThat(a.getX().toString(), is(new ArrayList<String>().toString())); }
### Question: HttpConnection implements Connection { public Connection headers(Map<String,String> headers) { Validate.notNull(headers, "Header map must not be null"); for (Map.Entry<String,String> entry : headers.entrySet()) { req.header(entry.getKey(),entry.getValue()); } return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void headers() { Connection con = HttpConnection.connect("http: Map<String, String> headers = new HashMap<String, String>(); headers.put("content-type", "text/html"); headers.put("Connection", "keep-alive"); headers.put("Host", "http: con.headers(headers); assertEquals("text/html", con.request().header("content-type")); assertEquals("keep-alive", con.request().header("Connection")); assertEquals("http: }
### Question: HttpConnection implements Connection { public Connection header(String name, String value) { req.header(name, value); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void sameHeadersCombineWithComma() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); List<String> values = new ArrayList<String>(); values.add("no-cache"); values.add("no-store"); headers.put("Cache-Control", values); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals("no-cache, no-store", res.header("Cache-Control")); }
### Question: HttpConnection implements Connection { public Connection cookies(Map<String, String> cookies) { Validate.notNull(cookies, "Cookie map must not be null"); for (Map.Entry<String, String> entry : cookies.entrySet()) { req.cookie(entry.getKey(), entry.getValue()); } return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void ignoresEmptySetCookies() { Map<String, List<String>> headers = new HashMap<String, List<String>>(); headers.put("Set-Cookie", Collections.<String>emptyList()); HttpConnection.Response res = new HttpConnection.Response(); res.processResponseHeaders(headers); assertEquals(0, res.cookies().size()); }
### Question: HttpConnection implements Connection { public static Connection connect(String url) { Connection con = new HttpConnection(); con.url(url); return con; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test(expected=IllegalArgumentException.class) public void throwsOnMalformedUrl() { Connection con = HttpConnection.connect("bzzt"); }
### Question: HttpConnection implements Connection { public Connection userAgent(String userAgent) { Validate.notNull(userAgent, "User agent must not be null"); req.header(USER_AGENT, userAgent); return this; } private HttpConnection(); static Connection connect(String url); static Connection connect(URL url); Connection url(URL url); Connection url(String url); Connection proxy(Proxy proxy); Connection proxy(String host, int port); Connection userAgent(String userAgent); Connection timeout(int millis); Connection maxBodySize(int bytes); Connection followRedirects(boolean followRedirects); Connection referrer(String referrer); Connection method(Method method); Connection ignoreHttpErrors(boolean ignoreHttpErrors); Connection ignoreContentType(boolean ignoreContentType); Connection validateTLSCertificates(boolean value); Connection data(String key, String value); Connection data(String key, String filename, InputStream inputStream); Connection data(Map<String, String> data); Connection data(String... keyvals); Connection data(Collection<Connection.KeyVal> data); Connection.KeyVal data(String key); Connection requestBody(String body); Connection header(String name, String value); Connection headers(Map<String,String> headers); Connection cookie(String name, String value); Connection cookies(Map<String, String> cookies); Connection parser(Parser parser); Document get(); Document post(); Connection.Response execute(); Connection.Request request(); Connection request(Connection.Request request); Connection.Response response(); Connection response(Connection.Response response); Connection postDataCharset(String charset); static final String CONTENT_ENCODING; static final String DEFAULT_UA; }### Answer: @Test public void userAgent() { Connection con = HttpConnection.connect("http: assertEquals(HttpConnection.DEFAULT_UA, con.request().header("User-Agent")); con.userAgent("Mozilla"); assertEquals("Mozilla", con.request().header("User-Agent")); }