java.io.InputStream

Here are the examples of the java api class java.io.InputStream taken from open source projects.

1. BOMInputStreamTest#testMarkResetAfterReadWithBOM()

Project: commons-io
Source File: BOMInputStreamTest.java
View license
@Test
public void testMarkResetAfterReadWithBOM() throws Exception {
    final byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    final InputStream in = new BOMInputStream(createUtf8DataStream(data, true));
    assertTrue(in.markSupported());
    in.read();
    in.mark(10);
    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
    in.close();
}

2. BOMInputStreamTest#testMarkResetAfterReadWithoutBOM()

Project: commons-io
Source File: BOMInputStreamTest.java
View license
@Test
public void testMarkResetAfterReadWithoutBOM() throws Exception {
    final byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    final InputStream in = new BOMInputStream(createUtf8DataStream(data, false));
    assertTrue(in.markSupported());
    in.read();
    in.mark(10);
    in.read();
    in.read();
    in.reset();
    assertEquals('B', in.read());
    in.close();
}

3. TestContentLengthInputStream#testSkip()

View license
public void testSkip() throws IOException {
    InputStream in = new ContentLengthInputStream(new SessionInputBufferMockup(new byte[20]), 10L);
    assertEquals(10, in.skip(10));
    assertTrue(in.read() == -1);
    in = new ContentLengthInputStream(new SessionInputBufferMockup(new byte[20]), 10L);
    in.read();
    assertEquals(9, in.skip(10));
    assertTrue(in.read() == -1);
    in = new ContentLengthInputStream(new SessionInputBufferMockup(new byte[20]), 2L);
    in.read();
    in.read();
    assertTrue(in.skip(10) <= 0);
    assertTrue(in.skip(-1) == 0);
    assertTrue(in.read() == -1);
    in = new ContentLengthInputStream(new SessionInputBufferMockup(new byte[2]), 4L);
    in.read();
    assertTrue(in.skip(2) == 1);
    in = new ContentLengthInputStream(new SessionInputBufferMockup(new byte[20]), 10L);
    in.skip(5);
    assertEquals(5, in.read(new byte[20]));
}

4. ByteStreamsTest#testLimit_skip()

Project: guava
Source File: ByteStreamsTest.java
View license
public void testLimit_skip() throws Exception {
    byte[] big = newPreFilledByteArray(5);
    InputStream bin = new ByteArrayInputStream(big);
    InputStream lin = ByteStreams.limit(bin, 2);
    // also test available
    lin.mark(2);
    assertEquals(2, lin.available());
    lin.skip(1);
    assertEquals(1, lin.available());
    lin.reset();
    assertEquals(2, lin.available());
    lin.skip(3);
    assertEquals(0, lin.available());
}

5. StorageFactoryTest#setup()

Project: falcon
Source File: StorageFactoryTest.java
View license
@BeforeClass
public void setup() throws Exception {
    InputStream stream = this.getClass().getResourceAsStream(CLUSTER_XML);
    clusterEntity = clusterParser.parse(stream);
    stream.close();
    Interface registry = ClusterHelper.getInterface(clusterEntity, Interfacetype.REGISTRY);
    registry.setEndpoint("thrift://localhost:9083");
    ConfigurationStore.get().publish(EntityType.CLUSTER, clusterEntity);
    stream = this.getClass().getResourceAsStream(FS_FEED_UNIFORM);
    fsFeedWithUniformStorage = feedParser.parse(stream);
    stream.close();
    stream = this.getClass().getResourceAsStream(FS_FEED_OVERRIDE);
    fsFeedWithOverriddenStorage = feedParser.parse(stream);
    stream.close();
    stream = this.getClass().getResourceAsStream(TABLE_FEED_UNIFORM);
    tableFeedWithUniformStorage = feedParser.parse(stream);
    stream.close();
    stream = this.getClass().getResourceAsStream(TABLE_FEED_OVERRIDE);
    tableFeedWithOverriddenStorage = feedParser.parse(stream);
    stream.close();
}

6. ComponentsXmlResourceTransformerTest#testConfigurationMerging()

View license
public void testConfigurationMerging() throws Exception {
    XMLUnit.setNormalizeWhitespace(true);
    InputStream resourceAsStream = getClass().getResourceAsStream("/components-1.xml");
    transformer.processResource("components-1.xml", resourceAsStream, Collections.<Relocator>emptyList());
    resourceAsStream.close();
    InputStream resourceAsStream1 = getClass().getResourceAsStream("/components-2.xml");
    transformer.processResource("components-1.xml", resourceAsStream1, Collections.<Relocator>emptyList());
    resourceAsStream1.close();
    final InputStream resourceAsStream2 = getClass().getResourceAsStream("/components-expected.xml");
    Diff diff = XMLUnit.compareXML(IOUtil.toString(resourceAsStream2, "UTF-8"), IOUtil.toString(transformer.getTransformedResource(), "UTF-8"));
    //assertEquals( IOUtil.toString( getClass().getResourceAsStream( "/components-expected.xml" ), "UTF-8" ),
    //              IOUtil.toString( transformer.getTransformedResource(), "UTF-8" ).replaceAll("\r\n", "\n") );
    resourceAsStream2.close();
    XMLAssert.assertXMLIdentical(diff, true);
}

7. BOMInputStreamTest#testMarkResetBeforeReadWithoutBOM()

Project: commons-io
Source File: BOMInputStreamTest.java
View license
@Test
public void testMarkResetBeforeReadWithoutBOM() throws Exception {
    final byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    final InputStream in = new BOMInputStream(createUtf8DataStream(data, false));
    assertTrue(in.markSupported());
    in.mark(10);
    in.read();
    in.read();
    in.reset();
    assertEquals('A', in.read());
    in.close();
}

8. BOMInputStreamTest#testMarkResetBeforeReadWithBOM()

Project: commons-io
Source File: BOMInputStreamTest.java
View license
@Test
public void testMarkResetBeforeReadWithBOM() throws Exception {
    final byte[] data = new byte[] { 'A', 'B', 'C', 'D' };
    final InputStream in = new BOMInputStream(createUtf8DataStream(data, true));
    assertTrue(in.markSupported());
    in.mark(10);
    in.read();
    in.read();
    in.reset();
    assertEquals('A', in.read());
    in.close();
}

9. StreamUtilsTests#testNonClosingInputStream()

View license
public void testNonClosingInputStream() throws Exception {
    InputStream source = mock(InputStream.class);
    InputStream nonClosing = StreamUtils.nonClosing(source);
    nonClosing.read();
    nonClosing.read(bytes);
    nonClosing.read(bytes, 1, 2);
    nonClosing.close();
    InOrder ordered = inOrder(source);
    ordered.verify(source).read();
    ordered.verify(source).read(bytes, 0, bytes.length);
    ordered.verify(source).read(bytes, 1, 2);
    ordered.verify(source, never()).close();
}

10. TestFileSystem#testClasspath()

Project: ThriftyPaxos
Source File: TestFileSystem.java
View license
private void testClasspath() throws IOException {
    String resource = "org/h2/test/testSimple.in.txt";
    InputStream in;
    in = getClass().getResourceAsStream("/" + resource);
    assertTrue(in != null);
    in.close();
    in = getClass().getClassLoader().getResourceAsStream(resource);
    assertTrue(in != null);
    in.close();
    in = FileUtils.newInputStream("classpath:" + resource);
    assertTrue(in != null);
    in.close();
    in = FileUtils.newInputStream("classpath:/" + resource);
    assertTrue(in != null);
    in.close();
}

11. VfsStreamsTests#writeRandomAccessRead()

Project: xodus
Source File: VfsStreamsTests.java
View license
@Test
public void writeRandomAccessRead() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    final OutputStream outputStream = vfs.appendFile(txn, file0);
    outputStream.write((HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN).getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    InputStream inputStream = vfs.readFile(txn, file0, 0);
    Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
    inputStream.close();
    inputStream = vfs.readFile(txn, file0, 10);
    Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
    inputStream.close();
    inputStream = vfs.readFile(txn, file0, 20);
    Assert.assertEquals(HOEGAARDEN + HOEGAARDEN, streamAsString(inputStream));
    inputStream.close();
    inputStream = vfs.readFile(txn, file0, 30);
    Assert.assertEquals(HOEGAARDEN, streamAsString(inputStream));
    inputStream.close();
    txn.abort();
}

12. TestDictionary#testInvalidFlags()

Project: lucene-solr
Source File: TestDictionary.java
View license
// malformed flags causes ParseException
public void testInvalidFlags() throws Exception {
    InputStream affixStream = getClass().getResourceAsStream("broken-flags.aff");
    InputStream dictStream = getClass().getResourceAsStream("simple.dic");
    Directory tempDir = getDirectory();
    Exception expected = expectThrows(Exception.class, () -> {
        new Dictionary(tempDir, "dictionary", affixStream, dictStream);
    });
    assertTrue(expected.getMessage().startsWith("expected only one flag"));
    affixStream.close();
    dictStream.close();
    tempDir.close();
}

13. TestDictionary#testInvalidData()

Project: lucene-solr
Source File: TestDictionary.java
View license
// malformed rule causes ParseException
public void testInvalidData() throws Exception {
    InputStream affixStream = getClass().getResourceAsStream("broken.aff");
    InputStream dictStream = getClass().getResourceAsStream("simple.dic");
    Directory tempDir = getDirectory();
    ParseException expected = expectThrows(ParseException.class, () -> {
        new Dictionary(tempDir, "dictionary", affixStream, dictStream);
    });
    assertTrue(expected.getMessage().startsWith("The affix file contains a rule with less than four elements"));
    assertEquals(24, expected.getErrorOffset());
    affixStream.close();
    dictStream.close();
    tempDir.close();
}

14. TestDictionary#testCompressedEmptyAliasDictionary()

Project: lucene-solr
Source File: TestDictionary.java
View license
public void testCompressedEmptyAliasDictionary() throws Exception {
    InputStream affixStream = getClass().getResourceAsStream("compressed-empty-alias.aff");
    InputStream dictStream = getClass().getResourceAsStream("compressed.dic");
    Directory tempDir = getDirectory();
    Dictionary dictionary = new Dictionary(tempDir, "dictionary", affixStream, dictStream);
    assertEquals(3, dictionary.lookupSuffix(new char[] { 'e' }, 0, 1).length);
    assertEquals(1, dictionary.lookupPrefix(new char[] { 's' }, 0, 1).length);
    IntsRef ordList = dictionary.lookupWord(new char[] { 'o', 'l', 'r' }, 0, 3);
    BytesRef ref = new BytesRef();
    dictionary.flagLookup.get(ordList.ints[0], ref);
    char flags[] = Dictionary.decodeFlags(ref);
    assertEquals(1, flags.length);
    affixStream.close();
    dictStream.close();
    tempDir.close();
}

15. TestDictionary#testCompressedBeforeSetDictionary()

Project: lucene-solr
Source File: TestDictionary.java
View license
public void testCompressedBeforeSetDictionary() throws Exception {
    InputStream affixStream = getClass().getResourceAsStream("compressed-before-set.aff");
    InputStream dictStream = getClass().getResourceAsStream("compressed.dic");
    Directory tempDir = getDirectory();
    Dictionary dictionary = new Dictionary(tempDir, "dictionary", affixStream, dictStream);
    assertEquals(3, dictionary.lookupSuffix(new char[] { 'e' }, 0, 1).length);
    assertEquals(1, dictionary.lookupPrefix(new char[] { 's' }, 0, 1).length);
    IntsRef ordList = dictionary.lookupWord(new char[] { 'o', 'l', 'r' }, 0, 3);
    BytesRef ref = new BytesRef();
    dictionary.flagLookup.get(ordList.ints[0], ref);
    char flags[] = Dictionary.decodeFlags(ref);
    assertEquals(1, flags.length);
    affixStream.close();
    dictStream.close();
    tempDir.close();
}

16. TestDictionary#testCompressedDictionary()

Project: lucene-solr
Source File: TestDictionary.java
View license
public void testCompressedDictionary() throws Exception {
    InputStream affixStream = getClass().getResourceAsStream("compressed.aff");
    InputStream dictStream = getClass().getResourceAsStream("compressed.dic");
    Directory tempDir = getDirectory();
    Dictionary dictionary = new Dictionary(tempDir, "dictionary", affixStream, dictStream);
    assertEquals(3, dictionary.lookupSuffix(new char[] { 'e' }, 0, 1).length);
    assertEquals(1, dictionary.lookupPrefix(new char[] { 's' }, 0, 1).length);
    IntsRef ordList = dictionary.lookupWord(new char[] { 'o', 'l', 'r' }, 0, 3);
    BytesRef ref = new BytesRef();
    dictionary.flagLookup.get(ordList.ints[0], ref);
    char flags[] = Dictionary.decodeFlags(ref);
    assertEquals(1, flags.length);
    affixStream.close();
    dictStream.close();
    tempDir.close();
}

17. DataGraphTestCase#setUp()

Project: tuscany-sdo
Source File: DataGraphTestCase.java
View license
protected void setUp() throws Exception {
    super.setUp();
    // Populate the meta data for the Quote type
    URL url = getClass().getResource(SIMPLE_MODEL);
    InputStream inputStream = url.openStream();
    XSDHelper.INSTANCE.define(inputStream, url.toString());
    inputStream.close();
    // Populate the meta data for the Person type
    URL url2 = getClass().getResource(ANYTYPE_MODEL);
    InputStream inputStream2 = url2.openStream();
    XSDHelper.INSTANCE.define(inputStream2, url2.toString());
    inputStream2.close();
}

18. ChangeSummaryOnDataObjectTestCase#setUp()

View license
protected void setUp() throws Exception {
    super.setUp();
    //    uncomment these lines for sending aspect trace to a file
    //    tracing.lib.TraceMyClasses tmc = (TraceMyClasses)Aspects.aspectOf(TraceMyClasses.class);
    //    tmc.initStream(new PrintStream("c:\\temp\\trace.log"));
    // Populate the meta data for the test (Stock Quote) model
    URL url = getClass().getResource("/simple.xsd");
    InputStream inputStream = url.openStream();
    hc = SDOUtil.createHelperContext();
    th = hc.getTypeHelper();
    xh = hc.getXSDHelper();
    xh.define(inputStream, url.toString());
    inputStream.close();
    URL url2 = getClass().getResource("/simpleWithChangeSummary.xsd");
    InputStream inputStream2 = url2.openStream();
    xh.define(inputStream2, url2.toString());
    inputStream.close();
}

19. ReadOnlyTestUtils#areTwoBinaryFilesEqual()

Project: voldemort
Source File: ReadOnlyTestUtils.java
View license
/**
     * Determines if two binary files are equal
     * 
     * @param fileA
     * @param fileB
     * @return
     * @throws IOException
     */
public static boolean areTwoBinaryFilesEqual(File fileA, File fileB) throws IOException {
    // compare file sizes
    if (fileA.length() != fileB.length())
        return false;
    // read and compare bytes pair-wise
    InputStream inputStream1 = new FileInputStream(fileA);
    InputStream inputStream2 = new FileInputStream(fileB);
    int nextByteFromInput1, nextByteFromInput2;
    do {
        nextByteFromInput1 = inputStream1.read();
        nextByteFromInput2 = inputStream2.read();
    } while (nextByteFromInput1 == nextByteFromInput2 && nextByteFromInput1 != -1);
    inputStream1.close();
    inputStream2.close();
    // true only if end of file is reached
    return nextByteFromInput1 == -1;
}

20. AbstractSlingCrudResourceResolverTest#testBinaryData()

View license
@Test
public void testBinaryData() throws IOException {
    Resource resource1 = context.resourceResolver().getResource(getTestRootResource().getPath() + "/node1");
    Resource binaryPropResource = resource1.getChild("binaryProp");
    InputStream is = binaryPropResource.adaptTo(InputStream.class);
    byte[] dataFromResource = IOUtils.toByteArray(is);
    is.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource);
    // read second time to ensure not the original input stream was returned
    // and this time using another syntax
    InputStream is2 = ResourceUtil.getValueMap(resource1).get("binaryProp", InputStream.class);
    byte[] dataFromResource2 = IOUtils.toByteArray(is2);
    is2.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource2);
}

21. SlingCrudResourceResolverTest#testBinaryData()

View license
@Test
public void testBinaryData() throws IOException {
    Resource resource1 = resourceResolver.getResource(testRoot.getPath() + "/node1");
    Resource binaryPropResource = resource1.getChild("binaryProp");
    InputStream is = binaryPropResource.adaptTo(InputStream.class);
    byte[] dataFromResource = IOUtils.toByteArray(is);
    is.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource);
    // read second time to ensure not the original input stream was returned
    // and this time using another syntax
    InputStream is2 = ResourceUtil.getValueMap(resource1).get("binaryProp", InputStream.class);
    byte[] dataFromResource2 = IOUtils.toByteArray(is2);
    is2.close();
    assertArrayEquals(BINARY_VALUE, dataFromResource2);
}

22. BlobTest#testParallelStreams()

Project: pgjdbc
Source File: BlobTest.java
View license
public void testParallelStreams() throws Exception {
    assertTrue(uploadFile("/test-file.xml", NATIVE_STREAM) > 0);
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    Blob lob = rs.getBlob(1);
    InputStream is1 = lob.getBinaryStream();
    InputStream is2 = lob.getBinaryStream();
    while (true) {
        int i1 = is1.read();
        int i2 = is2.read();
        assertEquals(i1, i2);
        if (i1 == -1) {
            break;
        }
    }
    is1.close();
    is2.close();
}

23. DefaultRequestDirectorTest#shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams()

View license
@Test
public void shouldReturnRequestsByRule_KeepsTrackOfOpenContentStreams() throws Exception {
    TestHttpResponse testHttpResponse = new TestHttpResponse(200, "a cheery response body");
    Robolectric.addHttpResponseRule("http://some.uri", testHttpResponse);
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
    HttpResponse getResponse = requestDirector.execute(null, new HttpGet("http://some.uri"), null);
    InputStream getResponseStream = getResponse.getEntity().getContent();
    assertThat(Strings.fromStream(getResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    HttpResponse postResponse = requestDirector.execute(null, new HttpPost("http://some.uri"), null);
    InputStream postResponseStream = postResponse.getEntity().getContent();
    assertThat(Strings.fromStream(postResponseStream), equalTo("a cheery response body"));
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    getResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(false));
    postResponseStream.close();
    assertThat(testHttpResponse.entityContentStreamsHaveBeenClosed(), equalTo(true));
}

24. ReaderToUTF8StreamTest#testMarkResetOverflowInternalBufferKeepBytes()

Project: derby
Source File: ReaderToUTF8StreamTest.java
View license
/**
     * Reads almost enough bytes to read past the read ahead limit, then tests
     * that the reset works. After that, reads past the read ahead limit and
     * tests that the reset fails.
     *
     * @throws IOException if something goes wrong
     */
public void testMarkResetOverflowInternalBufferKeepBytes() throws IOException {
    InputStream is = getStream(128 * 1024);
    is.mark(120 * 1024);
    byte[] buf = new byte[120 * 1024 - 1];
    fillArray(is, buf);
    is.reset();
    checkBeginningOfStream(is);
    // Again, but this time read past the read ahead limit.
    is = getStream(36 * 1024);
    is.mark(4 * 1024);
    buf = new byte[36 * 1024 - 1];
    fillArray(is, buf);
    try {
        is.reset();
        fail("reset-call was expected to throw IOException");
    } catch (IOException ioe) {
    }
}

25. ReaderToUTF8StreamTest#testMarkResetShiftBytesFew_Internal()

Project: derby
Source File: ReaderToUTF8StreamTest.java
View license
/**
     * Tests that shifting of existing bytes works.
     *
     * @throws IOException if something goes wrong
     */
public void testMarkResetShiftBytesFew_Internal() throws IOException {
    InputStream is = getStream(128 * 1024);
    byte[] buf = new byte[DEFAULT_INTERNAL_BUFFER_SIZE - 2 * 1024];
    fillArray(is, buf);
    // The following mark fits within the existing default buffer, but the
    // bytes after the mark have to be shifted to the left.
    is.mark(4 * 1024);
    byte[] readBeforeReset = new byte[3 * 1024];
    byte[] readAfterReset = new byte[3 * 1024];
    fillArray(is, readBeforeReset);
    // Obtain something to compare with.
    InputStream src = getStream(128 * 1024);
    InputStreamUtil.skipFully(src, DEFAULT_INTERNAL_BUFFER_SIZE - 2 * 1024);
    byte[] comparisonRead = new byte[3 * 1024];
    fillArray(src, comparisonRead);
    // Compare
    assertEquals(new ByteArrayInputStream(comparisonRead), new ByteArrayInputStream(readBeforeReset));
    // Reset the stream.
    is.reset();
    fillArray(is, readAfterReset);
    assertEquals(new ByteArrayInputStream(readBeforeReset), new ByteArrayInputStream(readAfterReset));
}

26. NewPostUploadTaskFragment#decodeSampledBitmapFromUri()

View license
public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}

27. OTFFileTestCase#setUp()

Project: fop
Source File: OTFFileTestCase.java
View license
/**
     * Initializes fonts used for the testing of reading OTF CFF
     * @throws java.io.IOException
     */
@Before
public void setUp() throws Exception {
    sourceSansProBold = new OTFFile();
    InputStream sourceSansStream = new FileInputStream("test/resources/fonts/otf/SourceSansProBold.otf");
    sourceSansReader = new FontFileReader(sourceSansStream);
    String sourceSansHeader = OFFontLoader.readHeader(sourceSansReader);
    sourceSansProBold.readFont(sourceSansReader, sourceSansHeader);
    sourceSansStream.close();
    InputStream alexBrushStream = new FileInputStream("test/resources/fonts/otf/AlexBrushRegular.otf");
    alexBrush = new OTFFile();
    alexBrushReader = new FontFileReader(alexBrushStream);
    String carolynaHeader = OFFontLoader.readHeader(alexBrushReader);
    alexBrush.readFont(alexBrushReader, carolynaHeader);
    alexBrushStream.close();
}

28. URLConnectionTest#testEarlyDisconnectDoesntHarmPooling()

Project: okhttp
Source File: URLConnectionTest.java
View license
private void testEarlyDisconnectDoesntHarmPooling(TransferKind transferKind) throws Exception {
    MockResponse response1 = new MockResponse();
    transferKind.setBody(response1, "ABCDEFGHIJK", 1024);
    server.enqueue(response1);
    MockResponse response2 = new MockResponse();
    transferKind.setBody(response2, "LMNOPQRSTUV", 1024);
    server.enqueue(response2);
    HttpURLConnection connection1 = urlFactory.open(server.url("/").url());
    InputStream in1 = connection1.getInputStream();
    assertEquals("ABCDE", readAscii(in1, 5));
    in1.close();
    connection1.disconnect();
    HttpURLConnection connection2 = urlFactory.open(server.url("/").url());
    InputStream in2 = connection2.getInputStream();
    assertEquals("LMNOP", readAscii(in2, 5));
    in2.close();
    connection2.disconnect();
    assertEquals(0, server.takeRequest().getSequenceNumber());
    // Connection is pooled!
    assertEquals(1, server.takeRequest().getSequenceNumber());
}

29. ResponseCacheTest#responseCachingWithoutBody()

Project: okhttp
Source File: ResponseCacheTest.java
View license
@Test
public void responseCachingWithoutBody() throws IOException {
    MockResponse response = new MockResponse().addHeader("Last-Modified: " + formatDate(-1, TimeUnit.HOURS)).addHeader("Expires: " + formatDate(1, TimeUnit.HOURS)).setStatus("HTTP/1.1 200 Fantastic");
    server.enqueue(response);
    HttpURLConnection urlConnection = openConnection(server.url("/").url());
    assertEquals(200, urlConnection.getResponseCode());
    assertEquals("Fantastic", urlConnection.getResponseMessage());
    assertTrue(urlConnection.getDoInput());
    InputStream is = urlConnection.getInputStream();
    assertEquals(-1, is.read());
    is.close();
    // cached!
    urlConnection = openConnection(server.url("/").url());
    assertTrue(urlConnection.getDoInput());
    InputStream cachedIs = urlConnection.getInputStream();
    assertEquals(-1, cachedIs.read());
    cachedIs.close();
    assertEquals(200, urlConnection.getResponseCode());
    assertEquals("Fantastic", urlConnection.getResponseMessage());
}

30. ClassLoaderUtilTest#testStream()

Project: jodd
Source File: ClassLoaderUtilTest.java
View license
@Test
public void testStream() throws IOException {
    InputStream is = ClassLoaderUtil.getClassAsStream(ClassLoaderUtilTest.class);
    assertNotNull(is);
    is.close();
    is = ClassLoaderUtil.getClassAsStream(ClassLoaderUtilTest.class);
    assertNotNull(is);
    is.close();
    URL url;
    final String resourceName = "jodd/util/Bits.class";
    url = ClassLoaderUtil.getResourceUrl(resourceName);
    assertNotNull(url);
    is = ClassLoaderUtil.getResourceAsStream(resourceName);
    assertNotNull(is);
    is.close();
}

31. ByteBufferInputStreamTest#testSkip()

Project: mina
Source File: ByteBufferInputStreamTest.java
View license
@Test
public void testSkip() throws IOException {
    byte[] src = "HELLO MINA!".getBytes();
    ByteBuffer bb = ByteBuffer.wrap(src);
    InputStream is = new ByteBufferInputStream(bb);
    is.skip(6);
    assertEquals(5, is.available());
    assertEquals('M', is.read());
    assertEquals('I', is.read());
    assertEquals('N', is.read());
    assertEquals('A', is.read());
    is.skip((long) Integer.MAX_VALUE + 1);
    assertEquals(-1, is.read());
    is.close();
}

32. ByteBufferInputStreamTest#testReadArray()

Project: mina
Source File: ByteBufferInputStreamTest.java
View license
@Test
public void testReadArray() throws IOException {
    byte[] src = "HELLO MINA".getBytes();
    byte[] dst = new byte[src.length];
    ByteBuffer bb = ByteBuffer.wrap(src);
    InputStream is = new ByteBufferInputStream(bb);
    assertEquals(true, is.markSupported());
    is.mark(src.length);
    assertEquals(dst.length, is.read(dst));
    assertArrayEquals(src, dst);
    assertEquals(-1, is.read());
    is.close();
    is.reset();
    byte[] dstTooBig = new byte[src.length + 1];
    assertEquals(src.length, is.read(dstTooBig));
    assertEquals(-1, is.read(dstTooBig));
}

33. NewPostUploadTaskFragment#decodeSampledBitmapFromUri()

View license
public Bitmap decodeSampledBitmapFromUri(Uri fileUri, int reqWidth, int reqHeight) throws IOException {
    InputStream stream = new BufferedInputStream(mApplicationContext.getContentResolver().openInputStream(fileUri));
    stream.mark(stream.available());
    BitmapFactory.Options options = new BitmapFactory.Options();
    // First decode with inJustDecodeBounds=true to check dimensions
    options.inJustDecodeBounds = true;
    BitmapFactory.decodeStream(stream, null, options);
    stream.reset();
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    options.inJustDecodeBounds = false;
    BitmapFactory.decodeStream(stream, null, options);
    // Decode bitmap with inSampleSize set
    stream.reset();
    return BitmapFactory.decodeStream(stream, null, options);
}

34. JUNGHipsterGraphAdapterTest#setUp()

View license
@BeforeClass
public static void setUp() throws Exception {
    graph = new TinkerGraph();
    // Get the stream associated with the example graph
    InputStream fileStream = JUNGHipsterGraphAdapterTest.class.getClassLoader().getResourceAsStream(GRAPH_FILE);
    // Check if the file was located successfully
    if (fileStream == null) {
        throw new NullPointerException(GRAPH_FILE + " cannot be found");
    }
    // Use a GZip stream
    InputStream ungzippedStream = new GZIPInputStream(fileStream);
    // populate it
    GraphMLReader.inputGraph(graph, ungzippedStream);
    // Close opened streams
    ungzippedStream.close();
    fileStream.close();
}

35. ByteStreamsTest#testLimit_mark()

Project: guava
Source File: ByteStreamsTest.java
View license
public void testLimit_mark() throws Exception {
    byte[] big = newPreFilledByteArray(5);
    InputStream bin = new ByteArrayInputStream(big);
    InputStream lin = ByteStreams.limit(bin, 2);
    int read = lin.read();
    assertEquals(big[0], read);
    lin.mark(2);
    read = lin.read();
    assertEquals(big[1], read);
    read = lin.read();
    assertEquals(-1, read);
    lin.reset();
    read = lin.read();
    assertEquals(big[1], read);
    read = lin.read();
    assertEquals(-1, read);
}

36. DetachedSignatureProcessor#verifySignature()

View license
private static void verifySignature(String fileName, String inputFileName, String keyFileName) throws GeneralSecurityException, IOException, PGPException, SignatureException {
    InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    verifySignature(fileName, in, keyIn);
    keyIn.close();
    in.close();
}

37. KeyBasedLargeFileProcessor#decryptFile()

View license
private static void decryptFile(String inputFileName, String keyFileName, char[] passwd, String defaultFileName) throws IOException, NoSuchProviderException {
    InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    decryptFile(in, keyIn, passwd, defaultFileName);
    keyIn.close();
    in.close();
}

38. KeyBasedFileProcessor#decryptFile()

Project: bc-java
Source File: KeyBasedFileProcessor.java
View license
private static void decryptFile(String inputFileName, String keyFileName, char[] passwd, String defaultFileName) throws IOException, NoSuchProviderException {
    InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    decryptFile(in, keyIn, passwd, defaultFileName);
    keyIn.close();
    in.close();
}

39. DetachedSignatureProcessor#verifySignature()

View license
private static void verifySignature(String fileName, String inputFileName, String keyFileName) throws GeneralSecurityException, IOException, PGPException {
    InputStream in = new BufferedInputStream(new FileInputStream(inputFileName));
    InputStream keyIn = new BufferedInputStream(new FileInputStream(keyFileName));
    verifySignature(fileName, in, keyIn);
    keyIn.close();
    in.close();
}

40. GsonXMLStreamReaderTest#testGsonXMLStreamReader()

View license
@Test
public void testGsonXMLStreamReader() throws Exception {
    String jsonString = "{\"response\":{\"return\":{\"name\":\"kate\",\"age\":\"35\",\"gender\":\"female\"}}}";
    String xmlString = "<response xmlns=\"http://www.w3schools.com\"><return><name>kate</name><age>35</age><gender>female</gender></return></response>";
    InputStream inputStream = new ByteArrayInputStream(jsonString.getBytes());
    JsonReader jsonReader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));
    String fileName = "test-resources/custom_schema/testSchema_1.xsd";
    InputStream is = new FileInputStream(fileName);
    XmlSchemaCollection schemaCol = new XmlSchemaCollection();
    XmlSchema schema = schemaCol.read(new StreamSource(is));
    List<XmlSchema> schemaList = new ArrayList<XmlSchema>();
    schemaList.add(schema);
    QName elementQName = new QName("http://www.w3schools.com", "response");
    ConfigurationContext configCtxt = new ConfigurationContext(new AxisConfiguration());
    GsonXMLStreamReader gsonXMLStreamReader = new GsonXMLStreamReader(jsonReader);
    gsonXMLStreamReader.initXmlStreamReader(elementQName, schemaList, configCtxt);
    OMXMLParserWrapper stAXOMBuilder = OMXMLBuilderFactory.createStAXOMBuilder(gsonXMLStreamReader);
    OMElement omElement = stAXOMBuilder.getDocumentElement();
    String actual = omElement.toString();
    inputStream.close();
    is.close();
    Assert.assertEquals(xmlString, actual);
}

41. GZipUtils#detectCompression()

Project: bnd
Source File: GZipUtils.java
View license
/**
	 * Determines whether the specified stream contains gzipped data, by
	 * checking for the GZIP magic number, and returns a stream capable of
	 * reading those data.
	 * 
	 * @throws IOException
	 */
public static InputStream detectCompression(InputStream stream) throws IOException {
    InputStream buffered;
    if (stream.markSupported())
        buffered = stream;
    else
        buffered = new BufferedInputStream(stream);
    buffered.mark(2);
    int magic = readUShort(buffered);
    buffered.reset();
    InputStream result;
    if (magic == GZIPInputStream.GZIP_MAGIC)
        result = new GZIPInputStream(buffered);
    else
        result = buffered;
    return result;
}

42. Upgrade201004Test#setUp()

Project: bioformats
Source File: Upgrade201004Test.java
View license
@BeforeMethod
public void setUp() throws Exception {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = Upgrade201004Test.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
    metadata = service.createOMEXMLMetadata(xml);
    ome = (OME) metadata.getRoot();
}

43. ExtraDataListTest#testByteStream()

Project: bazel
Source File: ExtraDataListTest.java
View license
@Test
public void testByteStream() throws IOException {
    byte[] buffer = new byte[] { (byte) 0xfe, (byte) 0xca, 0x03, 0x00, 0x00, 0x11, 0x22, (byte) 0xef, (byte) 0xbe, 0x03, 0x00, 0x33, 0x44, 0x55 };
    ExtraDataList extra = new ExtraDataList(buffer);
    byte[] bytes = new byte[7];
    InputStream in = extra.getByteStream();
    in.read(bytes);
    // Expect 0xcafe 0x0003 0x00 0x11 0x22 in little endian
    assertThat(bytes).isEqualTo(new byte[] { (byte) 0xfe, (byte) 0xca, 0x03, 0x00, 0x00, 0x11, 0x22 });
    in.read(bytes);
    // Expect 0xbeef 0x0003 0x33 0x44 0x55 in little endian
    assertThat(bytes).isEqualTo(new byte[] { (byte) 0xef, (byte) 0xbe, 0x03, 0x00, 0x33, 0x44, 0x55 });
    assertThat(in.read(bytes)).isEqualTo(-1);
}

44. OMEXMLServiceTest#setUp()

Project: bioformats
Source File: OMEXMLServiceTest.java
View license
@BeforeMethod
public void setUp() throws DependencyException, IOException {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = OMEXMLServiceTest.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
}

45. Upgrade200809Test#setUp()

Project: bioformats
Source File: Upgrade200809Test.java
View license
@BeforeMethod
public void setUp() throws Exception {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = Upgrade200809Test.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
    metadata = service.createOMEXMLMetadata(xml);
    ome = (OME) metadata.getRoot();
}

46. Upgrade200909Test#setUp()

Project: bioformats
Source File: Upgrade200909Test.java
View license
@BeforeMethod
public void setUp() throws Exception {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = Upgrade200909Test.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
    metadata = service.createOMEXMLMetadata(xml);
    ome = (OME) metadata.getRoot();
}

47. Upgrade201006Test#setUp()

Project: bioformats
Source File: Upgrade201006Test.java
View license
@BeforeMethod
public void setUp() throws Exception {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = Upgrade201006Test.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
    metadata = service.createOMEXMLMetadata(xml);
    ome = (OME) metadata.getRoot();
}

48. Upgrade201106Test#setUp()

Project: bioformats
Source File: Upgrade201106Test.java
View license
@BeforeMethod
public void setUp() throws Exception {
    ServiceFactory sf = new ServiceFactory();
    service = sf.getInstance(OMEXMLService.class);
    InputStream s = Upgrade201106Test.class.getResourceAsStream(XML_FILE);
    byte[] b = new byte[s.available()];
    s.read(b);
    s.close();
    xml = new String(b);
    metadata = service.createOMEXMLMetadata(xml);
    ome = (OME) metadata.getRoot();
}

49. CAFS#verifyEntry()

Project: bnd
Source File: CAFS.java
View license
private SHA1 verifyEntry(RandomAccessFile in) throws IOException, NoSuchAlgorithmException {
    byte[] signature = new byte[4];
    in.readFully(signature);
    if (!Arrays.equals(CAFE, signature))
        throw new IllegalArgumentException("File is corrupted: " + in);
    /* int flags = */
    in.readInt();
    int compressedSize = in.readInt();
    int uncompressedSize = in.readInt();
    byte[] key = new byte[KEYLENGTH];
    in.readFully(key);
    SHA1 sha1 = new SHA1(key);
    byte[] buffer = new byte[compressedSize];
    in.readFully(buffer);
    InputStream xin = getSha1Stream(sha1, buffer, uncompressedSize);
    xin.skip(uncompressedSize);
    xin.close();
    return sha1;
}

50. MediaStorage#cacheThumbnail()

Project: androidclient
Source File: MediaStorage.java
View license
private static void cacheThumbnail(Context context, Uri media, FileOutputStream fout, boolean forNetwork) throws IOException {
    ContentResolver cr = context.getContentResolver();
    InputStream in = cr.openInputStream(media);
    BitmapFactory.Options options = preloadBitmap(in, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
    in.close();
    // open again
    in = cr.openInputStream(media);
    Bitmap bitmap = BitmapFactory.decodeStream(in, null, options);
    in.close();
    Bitmap thumbnail = ThumbnailUtils.extractThumbnail(bitmap, THUMBNAIL_WIDTH, THUMBNAIL_HEIGHT);
    bitmap.recycle();
    thumbnail = bitmapOrientation(context, media, thumbnail);
    // write down to file
    thumbnail.compress(forNetwork ? Bitmap.CompressFormat.JPEG : Bitmap.CompressFormat.PNG, forNetwork ? THUMBNAIL_MIME_COMPRESSION : 0, fout);
    thumbnail.recycle();
}

51. DecoderInputStreamTest#boundingTest()

Project: adbcj
Source File: DecoderInputStreamTest.java
View license
@Test
public void boundingTest() throws IOException {
    InputStream in = new ByteArrayInputStream(new byte[] { 0, 1 });
    InputStream din = new DecoderInputStream(in, 1);
    // Should pass
    din.read();
    try {
        din.read();
        Assert.fail("Should have thrown indicating limit exceeded");
    } catch (IllegalStateException e) {
    }
}

52. CrossScopeCopyTestCase#setUp()

View license
protected void setUp() throws Exception {
    super.setUp();
    // Create Two Scopes
    hca = SDOUtil.createHelperContext();
    hcb = SDOUtil.createHelperContext();
    scopeA = hca.getTypeHelper();
    scopeB = hcb.getTypeHelper();
    // Populate scopes with bank model now
    URL url = getClass().getResource(BANK_MODEL);
    InputStream inputStream = url.openStream();
    hca.getXSDHelper().define(inputStream, url.toString());
    inputStream.close();
    inputStream = url.openStream();
    hcb.getXSDHelper().define(inputStream, url.toString());
    inputStream.close();
    // Now Populate scopeA with some dynamic models
    populateScopeWithDynamicTypes(scopeA);
    // Construct Source Tree
    constructSourceTree(hca.getDataFactory());
}

53. IsManyTestCase#setUp()

Project: tuscany-sdo
Source File: IsManyTestCase.java
View license
protected void setUp() throws Exception {
    super.setUp();
    // Populate the meta data for the test (Stock Quote) model
    URL url = getClass().getResource(TEST_MODEL);
    InputStream inputStream = url.openStream();
    XSDHelper.INSTANCE.define(inputStream, url.toString());
    inputStream.close();
    // Populate the meta data for the test (Stock Quote) model with maxOccurs=1 <any>
    url = getClass().getResource(TEST_MODEL1ANY);
    inputStream = url.openStream();
    XSDHelper.INSTANCE.define(inputStream, url.toString());
    inputStream.close();
}

54. SubstitutionWithExtensionValuesTestCase#setUp()

View license
protected void setUp() throws Exception {
    super.setUp();
    hc = HelperProvider.getDefaultContext();
    registerSEV(hc, true);
    InputStream inputStream = null;
    URL url = getClass().getResource("/substitutionWithExtensionValues2.xsd");
    inputStream = url.openStream();
    List sev2TypeList = hc.getXSDHelper().define(inputStream, url.toString());
    inputStream.close();
    inputStream = getClass().getResourceAsStream("/substitutionWithExtensionValues1.xml");
    dataObject = hc.getXMLHelper().load(inputStream).getRootObject();
    inputStream.close();
    if (sev2NamespaceURI == null) {
        sev2NamespaceURI = ((Type) sev2TypeList.get(0)).getURI();
    }
}

55. LiteralByteStringTest#testNewInput_skip()

View license
public void testNewInput_skip() throws IOException {
    InputStream input = stringUnderTest.newInput();
    int stringSize = stringUnderTest.size();
    int nearEndIndex = stringSize * 2 / 3;
    long skipped1 = input.skip(nearEndIndex);
    assertEquals("InputStream.skip()", skipped1, nearEndIndex);
    assertEquals("InputStream.available()", stringSize - skipped1, input.available());
    assertTrue("InputStream.mark() is available", input.markSupported());
    input.mark(0);
    assertEquals("InputStream.skip(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
    assertEquals("InputStream.available()", stringSize - skipped1 - 1, input.available());
    long skipped2 = input.skip(stringSize);
    assertEquals("InputStream.skip() incomplete", skipped2, stringSize - skipped1 - 1);
    assertEquals("InputStream.skip(), no more input", 0, input.available());
    assertEquals("InputStream.skip(), no more input", -1, input.read());
    input.reset();
    assertEquals("InputStream.reset() succeded", stringSize - skipped1, input.available());
    assertEquals("InputStream.reset(), read()", stringUnderTest.byteAt(nearEndIndex) & 0xFF, input.read());
}

56. FastTempOutputStreamTest#testWriteReadPartialByteArray()

View license
public void testWriteReadPartialByteArray() throws IOException {
    final FastTempOutputStream ftos = new FastTempOutputStream();
    ftos.write(BYTES, 1, 2);
    ftos.close();
    final byte[] result = new byte[2];
    final InputStream is = ftos.getInputStream();
    is.read(result);
    is.close();
    assertTrue("array contents should be equal", Arrays.equals(new //$NON-NLS-1$
    byte[] { BYTES[1], BYTES[2] }, result));
    ftos.dispose();
}

57. FastTempOutputStreamTest#testWriteReadBig()

View license
public void testWriteReadBig() throws IOException {
    final byte[] BIG_BYTES = new byte[1048576];
    final FastTempOutputStream ftos = new FastTempOutputStream(1000, 100);
    ftos.write(BIG_BYTES);
    ftos.close();
    final byte[] result = new byte[BIG_BYTES.length];
    final InputStream is = ftos.getInputStream();
    is.read(result);
    is.close();
    //$NON-NLS-1$
    assertTrue("array contents should be equal", Arrays.equals(result, BIG_BYTES));
    ftos.dispose();
}

58. AbstractSnappyStreamTest#testCloseIsIdempotent()

View license
@Test
public void testCloseIsIdempotent() throws Exception {
    byte[] random = getRandom(0.5, 500000);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputStream snappyOut = createOutputStream(out);
    snappyOut.write(random);
    snappyOut.close();
    snappyOut.close();
    byte[] compressed = out.toByteArray();
    InputStream snappyIn = createInputStream(new ByteArrayInputStream(compressed), true);
    byte[] uncompressed = toByteArray(snappyIn);
    assertEquals(uncompressed, random);
    snappyIn.close();
    snappyIn.close();
}

59. BundleSynchronizedMatcherTest#testRetrieveMissingKeys()

View license
@Test
public void testRetrieveMissingKeys() throws Exception {
    InputStream defaultBundleIS = this.getClass().getResourceAsStream(BundleSynchronizedMatcher.L10N_PATH + "myPlugin.properties");
    InputStream frBundleIS = this.getClass().getResourceAsStream(BundleSynchronizedMatcher.L10N_PATH + "myPlugin_fr.properties");
    InputStream qbBundleIS = this.getClass().getResourceAsStream(BundleSynchronizedMatcher.L10N_PATH + "myPlugin_fr_QB.properties");
    try {
        SortedMap<String, String> diffs = BundleSynchronizedMatcher.retrieveMissingTranslations(frBundleIS, defaultBundleIS);
        assertThat(diffs.size(), is(1));
        assertThat(diffs.keySet(), hasItem("second.prop"));
        diffs = BundleSynchronizedMatcher.retrieveMissingTranslations(qbBundleIS, defaultBundleIS);
        assertThat(diffs.size(), is(0));
    } finally {
        IOUtils.closeQuietly(defaultBundleIS);
        IOUtils.closeQuietly(frBundleIS);
        IOUtils.closeQuietly(qbBundleIS);
    }
}

60. HystrixStreamEndpointTests#hystrixStreamWorks()

View license
@Test
public void hystrixStreamWorks() throws Exception {
    String url = "http://localhost:" + port;
    //you have to hit a Hystrix circuit breaker before the stream sends anything
    ResponseEntity<String> response = new TestRestTemplate().getForEntity(url, String.class);
    assertEquals("bad response code", HttpStatus.OK, response.getStatusCode());
    URL hystrixUrl = new URL(url + "/admin/hystrix.stream");
    InputStream in = hystrixUrl.openStream();
    byte[] buffer = new byte[1024];
    in.read(buffer);
    String contents = new String(buffer);
    assertTrue(contents.contains("ping"));
    in.close();
}

61. VfsStreamsTests#testWriteOverwriteReadWithStrategy()

Project: xodus
Source File: VfsStreamsTests.java
View license
private void testWriteOverwriteReadWithStrategy(@NotNull final ClusteringStrategy strategy) throws IOException {
    vfs.shutdown();
    final VfsConfig config = new VfsConfig();
    config.setClusteringStrategy(strategy);
    vfs = new VirtualFileSystem(getEnvironment(), config);
    Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    OutputStream outputStream = vfs.writeFile(txn, file0);
    outputStream.write(HOEGAARDEN.getBytes(UTF_8));
    outputStream.close();
    InputStream inputStream = vfs.readFile(txn, file0);
    String actualRead = streamAsString(inputStream);
    Assert.assertEquals(HOEGAARDEN, actualRead);
    inputStream.close();
    txn.commit();
    txn = env.beginTransaction();
    outputStream = vfs.writeFile(txn, file0);
    outputStream.write(RENAT_GILFANOV.getBytes(UTF_8));
    outputStream.close();
    inputStream = vfs.readFile(txn, file0);
    actualRead = streamAsString(inputStream);
    Assert.assertEquals(RENAT_GILFANOV, actualRead);
    inputStream.close();
    txn.commit();
}

62. ReadOffset#main()

Project: jdk7u-jdk
Source File: ReadOffset.java
View license
public static void main(String[] args) throws IOException {
    ReadableByteChannel rbc = new ReadableByteChannel() {

        public int read(ByteBuffer dst) {
            dst.put((byte) 0);
            return 1;
        }

        public boolean isOpen() {
            return true;
        }

        public void close() {
        }
    };
    InputStream in = Channels.newInputStream(rbc);
    byte[] b = new byte[3];
    in.read(b, 0, 1);
    // throws IAE
    in.read(b, 2, 1);
}

63. SocksSocketFactory#createSocksConnection()

View license
public static void createSocksConnection(Socket socket, String destination, int port) throws IOException {
    InputStream proxyIs = socket.getInputStream();
    OutputStream proxyOs = socket.getOutputStream();
    proxyOs.write(new byte[] { 0x05, 0x01, 0x00 });
    byte[] response = new byte[2];
    proxyIs.read(response);
    byte[] dest = destination.getBytes();
    ByteBuffer request = ByteBuffer.allocate(7 + dest.length);
    request.put(new byte[] { 0x05, 0x01, 0x00, 0x03 });
    request.put((byte) dest.length);
    request.put(dest);
    request.putShort((short) port);
    proxyOs.write(request.array());
    response = new byte[7 + dest.length];
    proxyIs.read(response);
    if (response[1] != 0x00) {
        throw new SocksConnectionException();
    }
}

64. DelimitedStreamReaderTest#testMultipleStreamReads()

Project: hbc
Source File: DelimitedStreamReaderTest.java
View license
/**
   * This tests the case where we have to call multiple Inputstream.read()s to consume the entire message, as we might
   * have to in real life
   */
@Test
public void testMultipleStreamReads() throws Exception {
    String myMessage = "{this is my message: héÿ}\n";
    byte[] bytes = myMessage.substring(0, myMessage.length() / 2).getBytes(Charsets.UTF_8);
    byte[] bytes2 = myMessage.substring(myMessage.length() / 2, myMessage.length()).getBytes(Charsets.UTF_8);
    InputStream miniStream = new ByteArrayInputStream(bytes);
    InputStream miniStream2 = new ByteArrayInputStream(bytes2);
    InputStream stream = new SplitInputStream(Lists.newArrayList(miniStream, miniStream2));
    DelimitedStreamReader r = new DelimitedStreamReader(stream, Charsets.UTF_8, myMessage.length() / 3);
    // read less bytes than the actual message, but we're lenient so we'll read up to the newline
    String msg = r.read(myMessage.length());
    assertEquals(msg, myMessage);
}

65. WriteWhileReadingTest#test()

View license
public void test() throws Exception {
    Node root = superuser.getRootNode();
    ValueFactory vf = superuser.getValueFactory();
    // store a binary in the data store
    root.setProperty("p1", vf.createBinary(new RandomInputStream(1, STREAM_LENGTH)));
    superuser.save();
    // read from the binary, but don't close the file
    Value v1 = root.getProperty("p1").getValue();
    InputStream in = v1.getBinary().getStream();
    in.read();
    // store the same content at a different place -
    // this will change the last modified date of the file
    root.setProperty("p2", vf.createBinary(new RandomInputStream(1, STREAM_LENGTH)));
    superuser.save();
    in.close();
}

66. BlobTest#testMultipleStreams()

Project: pgjdbc
Source File: BlobTest.java
View license
public void testMultipleStreams() throws Exception {
    assertTrue(uploadFile("/test-file.xml", NATIVE_STREAM) > 0);
    Statement stmt = con.createStatement();
    ResultSet rs = stmt.executeQuery("SELECT lo FROM testblob");
    assertTrue(rs.next());
    Blob lob = rs.getBlob(1);
    byte data[] = new byte[2];
    InputStream is = lob.getBinaryStream();
    assertEquals(data.length, is.read(data));
    assertEquals(data[0], '<');
    assertEquals(data[1], '?');
    is.close();
    is = lob.getBinaryStream();
    assertEquals(data.length, is.read(data));
    assertEquals(data[0], '<');
    assertEquals(data[1], '?');
    is.close();
}

67. InputStreamTest#testInputStream()

Project: Resteasy
Source File: InputStreamTest.java
View license
@Test
public void testInputStream() throws Exception {
    ResteasyClient client = new ResteasyClientBuilder().build();
    InputStream is = client.target(generateURL("/test")).request().get(InputStream.class);
    byte[] buf = new byte[1024];
    int read = is.read(buf);
    String str = new String(buf, 0, read);
    Assert.assertEquals("hello world", str);
    System.out.println(str);
    is.close();
    InputStreamInterface proxy = client.target(generateURL("/")).proxy(InputStreamInterface.class);
    is = proxy.get();
    read = is.read(buf);
    str = new String(buf, 0, read);
    Assert.assertEquals("hello world", str);
    is.close();
    client.close();
}

68. SignedTest#setup()

Project: Resteasy
Source File: SignedTest.java
View license
@BeforeClass
public static void setup() throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    InputStream certIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("mycert.pem");
    cert = PemUtils.decodeCertificate(certIs);
    InputStream privateIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("mycert-private.pem");
    privateKey = PemUtils.decodePrivateKey(privateIs);
    InputStream badIs = Thread.currentThread().getContextClassLoader().getResourceAsStream("private_dkim_key.der");
    badKey = DerUtils.decodePrivateKey(badIs);
}

69. FileUtils#readFile()

Project: PackageTracker
Source File: FileUtils.java
View license
public static String readFile(Context context, String name) throws IOException {
    File file = context.getFileStreamPath(name);
    InputStream is = new FileInputStream(file);
    byte b[] = new byte[(int) file.length()];
    is.read(b);
    is.close();
    String string = new String(b);
    return string;
}

70. URLConnectionTest#testMarkAndReset()

Project: okhttp
Source File: URLConnectionTest.java
View license
private void testMarkAndReset(TransferKind transferKind) throws IOException {
    MockResponse response = new MockResponse();
    transferKind.setBody(response, "ABCDEFGHIJKLMNOPQRSTUVWXYZ", 1024);
    server.enqueue(response);
    server.enqueue(response);
    InputStream in = urlFactory.open(server.url("/").url()).getInputStream();
    assertFalse("This implementation claims to support mark().", in.markSupported());
    in.mark(5);
    assertEquals("ABCDE", readAscii(in, 5));
    try {
        in.reset();
        fail();
    } catch (IOException expected) {
    }
    assertEquals("FGHIJKLMNOPQRSTUVWXYZ", readAscii(in, Integer.MAX_VALUE));
    in.close();
    assertContent("ABCDEFGHIJKLMNOPQRSTUVWXYZ", urlFactory.open(server.url("/").url()));
}

71. Utility#readStringFromFile()

Project: NHentai-android
Source File: Utility.java
View license
public static String readStringFromFile(Context context, String name) throws IOException {
    File file = context.getFileStreamPath(name);
    InputStream is = new FileInputStream(file);
    byte b[] = new byte[(int) file.length()];
    is.read(b);
    is.close();
    String string = new String(b);
    return string;
}

72. ReadOffset#main()

Project: openjdk
Source File: ReadOffset.java
View license
public static void main(String[] args) throws IOException {
    ReadableByteChannel rbc = new ReadableByteChannel() {

        public int read(ByteBuffer dst) {
            dst.put((byte) 0);
            return 1;
        }

        public boolean isOpen() {
            return true;
        }

        public void close() {
        }
    };
    InputStream in = Channels.newInputStream(rbc);
    byte[] b = new byte[3];
    in.read(b, 0, 1);
    // throws IAE
    in.read(b, 2, 1);
}

73. ReaderToUTF8StreamTest#testMarkResetSimplePosNonZero()

Project: derby
Source File: ReaderToUTF8StreamTest.java
View license
/**
     * Tests a very basic use of the mark/reset mechanism.
     *
     * @throws IOException if something goes wrong
     */
public void testMarkResetSimplePosNonZero() throws IOException {
    InputStream is = getStream(200);
    assertEquals(127, is.read(new byte[127]));
    is.mark(10);
    byte[] readBeforeReset = new byte[10];
    byte[] readAfterReset = new byte[10];
    assertEquals(10, is.read(readBeforeReset));
    is.reset();
    assertEquals(10, is.read(readAfterReset));
    assertTrue(Arrays.equals(readBeforeReset, readAfterReset));
}

74. ReaderToUTF8StreamTest#testMarkReadAlmostUntilEOF()

Project: derby
Source File: ReaderToUTF8StreamTest.java
View license
/**
     * Marks the stream with a read ahead limit larger than the stream itself,
     * then reads until just before the end of the stream.
     *
     * @throws IOException if something goes wrong
     */
public void testMarkReadAlmostUntilEOF() throws IOException {
    // Try with a single buffer fill first.
    int limit = 4 * 1024;
    InputStream is = getStream(limit);
    is.mark(8 * 1024);
    byte[] buf = new byte[limit * 2];
    int read = 0;
    while (read < limit - 1) {
        int readNow = is.read(buf, read, (limit - 1) - read);
        if (readNow == -1) {
            break;
        }
        read += readNow;
    }
    // EOF has been reached when filling the internal buffer, but we still
    // havent't read it. Therefore, the reset should succeed.
    is.reset();
    checkBeginningOfStream(is);
}

75. UTF8UtilTest#testSkipFullyOnInvalidStreamCJK()

Project: derby
Source File: UTF8UtilTest.java
View license
/**
     * Tests that <code>skipFully</code> throws exception if there is a UTF-8
     * encoding error in the stream
     * 
     * @throws IOException if the test fails for some unexpected reason
     */
public void testSkipFullyOnInvalidStreamCJK() throws IOException {
    final int charLength = 10;
    InputStream in = new ReaderToUTF8Stream(new LoopingAlphabetReader(charLength, CharAlphabet.cjkSubset()), charLength, 0, TYPENAME, new CharStreamHeaderGenerator());
    // Skip encoded length added by ReaderToUTF8Stream.
    in.skip(HEADER_LENGTH);
    // Skip one more byte to trigger a UTF error.
    in.skip(1L);
    try {
        UTF8Util.skipFully(in, charLength);
        fail("Should have failed because of UTF error.");
    } catch (UTFDataFormatException udfe) {
    }
}

76. DBSource#getContent()

Project: exist
Source File: DBSource.java
View license
/* (non-Javadoc)
     * @see org.exist.source.Source#getContent()
     */
@Override
public String getContent() throws IOException {
    final InputStream raw = broker.getBinaryResource(doc);
    final long binaryLength = broker.getBinaryResourceSize(doc);
    if (binaryLength > (long) Integer.MAX_VALUE) {
        throw new IOException("Resource too big to be read using this method.");
    }
    final byte[] data = new byte[(int) binaryLength];
    raw.read(data);
    raw.close();
    final ByteArrayInputStream is = new ByteArrayInputStream(data);
    checkEncoding(is);
    return new String(data, encoding);
}

77. Utils#readFile()

Project: Kore
Source File: Utils.java
View license
public static String readFile(Context context, String filename) throws IOException {
    InputStream is = context.getAssets().open(filename);
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();
    return new String(buffer, "UTF-8");
}

78. DBSource#isModule()

Project: exist
Source File: DBSource.java
View license
@Override
public QName isModule() throws IOException {
    final InputStream raw = broker.getBinaryResource(doc);
    final long binaryLength = broker.getBinaryResourceSize(doc);
    if (binaryLength > (long) Integer.MAX_VALUE) {
        throw new IOException("Resource too big to be read using this method.");
    }
    final byte[] data = new byte[(int) binaryLength];
    raw.read(data);
    raw.close();
    final ByteArrayInputStream is = new ByteArrayInputStream(data);
    return getModuleDecl(is);
}

79. ByteBufferInputStreamTest#availableAfterRead()

View license
@Test
public void availableAfterRead() throws IOException {
    final byte testData[] = "test data".getBytes();
    final ByteBuffer buf = ByteBuffer.wrap(testData);
    InputStream is = new ByteBufferInputStream(new TestableByteBufferAccessor(buf));
    //read first 2 bytes
    is.read();
    is.read();
    assertEquals(testData.length - 2, is.available());
}

80. GraphIT#shouldCloseStreamsWhenSuccessful()

Project: Gaffer
Source File: GraphIT.java
View license
@Test
public void shouldCloseStreamsWhenSuccessful() throws IOException {
    // Given
    final InputStream storePropertiesStream = StreamUtil.storeProps(getClass());
    final InputStream dataStream = StreamUtil.dataSchema(getClass());
    final InputStream dataTypesStream = StreamUtil.dataTypes(getClass());
    // When
    new Graph.Builder().storeProperties(storePropertiesStream).addSchema(dataStream).addSchema(dataTypesStream).build();
    checkClosed(storePropertiesStream);
    checkClosed(dataStream);
    checkClosed(dataTypesStream);
}

81. UtilTest#testConvertInputStreamToString()

Project: ffmpeg-android-java
Source File: UtilTest.java
View license
public void testConvertInputStreamToString() throws Exception {
    String exampleString1 = "Example to provide source to InputStream";
    String exampleString2 = "";
    String exampleString3 = 1 + "";
    InputStream stream1 = new ByteArrayInputStream(exampleString1.getBytes());
    InputStream stream2 = new ByteArrayInputStream(exampleString2.getBytes());
    InputStream stream3 = new ByteArrayInputStream(exampleString3.getBytes());
    String output1 = Util.convertInputStreamToString(stream1);
    String output2 = Util.convertInputStreamToString(stream2);
    String output3 = Util.convertInputStreamToString(stream3);
    assertEquals(output1, exampleString1);
    assertEquals(output2, exampleString2);
    assertEquals(output3, exampleString3);
}

82. ThumbnailsBuilderInputOutputTest#of_InputStreams_toFiles_Rename()

View license
/**
	 * Test for the {@link Thumbnails.Builder} class where,
	 * <ol>
	 * <li>Thumbnails.of(InputStream, InputStream)</li>
	 * <li>toFiles(Rename)</li>
	 * </ol>
	 * and the expected outcome is,
	 * <ol>
	 * <li>An IllegalStateException occurs.</li>
	 * </ol>
	 * @throws IOException
	 */
@Test(expected = IllegalStateException.class)
public void of_InputStreams_toFiles_Rename() throws IOException {
    // given
    InputStream is1 = new FileInputStream("src/test/resources/Thumbnailator/grid.png");
    InputStream is2 = new FileInputStream("src/test/resources/Thumbnailator/grid.jpg");
    try {
        // when
        Thumbnails.of(is1, is2).size(50, 50).toFiles(Rename.PREFIX_DOT_THUMBNAIL);
    } catch (IllegalStateException e) {
        assertEquals("Cannot create thumbnails to files if original images are not from files.", e.getMessage());
        throw e;
    }
}

83. EncryptedAttachmentInputStreamTest#testReadingValidFile()

View license
@Test
public void testReadingValidFile() throws IOException, InvalidKeyException {
    File encryptedAttachmentBlob = TestUtils.loadFixture("fixture/EncryptedAttachmentTest_cipherText_aes128");
    File expectedPlainText = TestUtils.loadFixture("fixture/EncryptedAttachmentTest_plainText");
    InputStream encryptedInputStream = new EncryptedAttachmentInputStream(new FileInputStream(encryptedAttachmentBlob), EncryptionTestConstants.key16Byte);
    InputStream plainTextInputStream = new FileInputStream(expectedPlainText);
    Assert.assertTrue("Reading encrypted stream didn't give expected plain text", IOUtils.contentEquals(encryptedInputStream, plainTextInputStream));
}

84. ThumbnailatorTest#testCreateThumbnail_IOII_Bmp()

View license
/**
	 * Test for
	 * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
	 * where,
	 * 
	 * 1) Method arguments are correct
	 * 2) Input data is a BMP image
	 * 
	 * Expected outcome is,
	 * 
	 * 1) Processing will complete successfully.
	 * 
	 * @throws IOException
	 */
@Test
public void testCreateThumbnail_IOII_Bmp() throws IOException {
    /*
		 * Actual test
		 */
    byte[] bytes = new byte[40054];
    FileInputStream fis = new FileInputStream("src/test/resources/Thumbnailator/grid.bmp");
    fis.read(bytes);
    fis.close();
    InputStream is = new ByteArrayInputStream(bytes);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Thumbnailator.createThumbnail(is, os, 50, 50);
    /*
		 * Post-test checks
		 */
    InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
    BufferedImage thumb = ImageIO.read(thumbIs);
    assertEquals(50, thumb.getWidth());
    assertEquals(50, thumb.getHeight());
}

85. ThumbnailatorTest#testCreateThumbnail_IOII_Png()

View license
/**
	 * Test for
	 * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
	 * where,
	 * 
	 * 1) Method arguments are correct
	 * 2) Input data is a PNG image
	 * 
	 * Expected outcome is,
	 * 
	 * 1) Processing will complete successfully.
	 * 
	 * @throws IOException
	 */
@Test
public void testCreateThumbnail_IOII_Png() throws IOException {
    /*
		 * Actual test
		 */
    byte[] bytes = makeImageData("png", 200, 200);
    InputStream is = new ByteArrayInputStream(bytes);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Thumbnailator.createThumbnail(is, os, 50, 50);
    /*
		 * Post-test checks
		 */
    InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
    BufferedImage thumb = ImageIO.read(thumbIs);
    assertEquals(50, thumb.getWidth());
    assertEquals(50, thumb.getHeight());
}

86. ThumbnailatorTest#testCreateThumbnail_IOII_Jpg()

View license
/**
	 * Test for
	 * {@link Thumbnailator#createThumbnail(InputStream, OutputStream, int, int)}
	 * where,
	 * 
	 * 1) Method arguments are correct
	 * 2) Input data is a JPEG image
	 * 
	 * Expected outcome is,
	 * 
	 * 1) Processing will complete successfully.
	 * 
	 * @throws IOException
	 */
@Test
public void testCreateThumbnail_IOII_Jpg() throws IOException {
    /*
		 * Actual test
		 */
    byte[] bytes = makeImageData("jpg", 200, 200);
    InputStream is = new ByteArrayInputStream(bytes);
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    Thumbnailator.createThumbnail(is, os, 50, 50);
    /*
		 * Post-test checks
		 */
    InputStream thumbIs = new ByteArrayInputStream(os.toByteArray());
    BufferedImage thumb = ImageIO.read(thumbIs);
    assertEquals(50, thumb.getWidth());
    assertEquals(50, thumb.getHeight());
}

87. ArchiveTool#extract()

Project: ThriftyPaxos
Source File: ArchiveTool.java
View license
private static void extract(String fromFile, String toDir) throws IOException {
    long start = System.currentTimeMillis();
    long size = new File(fromFile).length();
    System.out.println("Extracting " + size / MB + " MB");
    InputStream in = new BufferedInputStream(new FileInputStream(fromFile), 1024 * 1024);
    String temp = fromFile + ".temp";
    Inflater inflater = new Inflater();
    in = new InflaterInputStream(in, inflater, 1024 * 1024);
    OutputStream out = getDirectoryOutputStream(toDir);
    combine(in, out, temp);
    inflater.end();
    in.close();
    out.close();
    System.out.println();
    System.out.println("Extracted in " + (System.currentTimeMillis() - start) / 1000 + " seconds");
}

88. TestFileSystem#testTempFile()

Project: ThriftyPaxos
Source File: TestFileSystem.java
View license
private void testTempFile(String fsBase) throws Exception {
    int len = 10000;
    String s = FileUtils.createTempFile(fsBase + "/tmp", ".tmp", false, false);
    OutputStream out = FileUtils.newOutputStream(s, false);
    byte[] buffer = new byte[len];
    out.write(buffer);
    out.close();
    out = FileUtils.newOutputStream(s, true);
    out.write(1);
    out.close();
    InputStream in = FileUtils.newInputStream(s);
    for (int i = 0; i < len; i++) {
        assertEquals(0, in.read());
    }
    assertEquals(1, in.read());
    assertEquals(-1, in.read());
    in.close();
    out.close();
    FileUtils.delete(s);
}

89. TestConcurrent#readFileSlowly()

Project: ThriftyPaxos
Source File: TestConcurrent.java
View license
private static byte[] readFileSlowly(FileChannel file, long length) throws Exception {
    file.position(0);
    InputStream in = new BufferedInputStream(new FileChannelInputStream(file, false));
    ByteArrayOutputStream buff = new ByteArrayOutputStream();
    for (int j = 0; j < length; j++) {
        int x = in.read();
        if (x < 0) {
            break;
        }
        buff.write(x);
    }
    in.close();
    return buff.toByteArray();
}

90. TestLob#testConcurrentRemoveRead()

Project: ThriftyPaxos
Source File: TestLob.java
View license
private void testConcurrentRemoveRead() throws Exception {
    deleteDb("lob");
    final String url = getURL("lob", true);
    Connection conn = getConnection(url);
    Statement stat = conn.createStatement();
    stat.execute("set max_length_inplace_lob 5");
    stat.execute("create table lob(data clob)");
    stat.execute("insert into lob values(space(100))");
    Connection conn2 = getConnection(url);
    Statement stat2 = conn2.createStatement();
    ResultSet rs = stat2.executeQuery("select data from lob");
    rs.next();
    stat.execute("delete lob");
    InputStream in = rs.getBinaryStream(1);
    in.read();
    conn2.close();
    conn.close();
}

91. Newsfeed#main()

Project: ThriftyPaxos
Source File: Newsfeed.java
View license
/**
     * This method is called when executing this sample application from the
     * command line.
     *
     * @param args the command line parameters
     */
public static void main(String... args) throws Exception {
    String targetDir = args.length == 0 ? "." : args[0];
    Class.forName("org.h2.Driver");
    Connection conn = DriverManager.getConnection("jdbc:h2:mem:", "sa", "");
    InputStream in = Newsfeed.class.getResourceAsStream("newsfeed.sql");
    ResultSet rs = RunScript.execute(conn, new InputStreamReader(in, "ISO-8859-1"));
    in.close();
    while (rs.next()) {
        String file = rs.getString("FILE");
        String content = rs.getString("CONTENT");
        if (file.endsWith(".txt")) {
            content = convertHtml2Text(content);
        }
        new File(targetDir).mkdirs();
        FileOutputStream out = new FileOutputStream(targetDir + "/" + file);
        Writer writer = new OutputStreamWriter(out, "UTF-8");
        writer.write(content);
        writer.close();
        out.close();
    }
    conn.close();
}

92. FileCompare#compare()

Project: uima-uimaj
Source File: FileCompare.java
View license
/**
   * compares two files and return true if the files have the same content.
   * 
   * @param file1
   *          first file
   * @param file2
   *          second file
   * @return - true if the files have the same content
   * 
   * @throws IOException -
   */
public static boolean compare(File file1, File file2) throws IOException {
    InputStream inputStream1 = null;
    InputStream inputStream2 = null;
    try {
        // create file input stream of the two bytes
        inputStream1 = new FileInputStream(file1);
        inputStream2 = new FileInputStream(file2);
        return compare(inputStream1, inputStream2);
    } finally {
        inputStream1.close();
        inputStream2.close();
    }
}

93. FileCompare#compare()

Project: uima-uimaj
Source File: FileCompare.java
View license
/**
   * compares two files and return true if the files have the same content.
   * 
   * @param filename1
   *          filename of the first file
   * @param filename2
   *          filename of the second file
   * @return - true if the files have the same content
   * 
   * @throws IOException -
   */
public static boolean compare(String filename1, String filename2) throws IOException {
    InputStream file1 = null;
    InputStream file2 = null;
    try {
        // create file input stream of the two bytes
        file1 = new FileInputStream(filename1);
        file2 = new FileInputStream(filename2);
        return compare(file1, file2);
    } finally {
        file1.close();
        file2.close();
    }
}

94. ActualityOfDtdTest#checkDtdActuality()

Project: uadetector
Source File: ActualityOfDtdTest.java
View license
@Test
public void checkDtdActuality() throws IOException {
    final String currentDefinition = XmlDataHandler.UASDATA_DEF;
    final URL definitionUrl = new URL(XmlDataHandler.UASDATA_DEF_URL);
    // read DTD online
    final InputStream onlineStream = definitionUrl.openStream();
    final InputStreamReader onlineReader = new InputStreamReader(onlineStream);
    final String onlineDtd = read(onlineReader);
    onlineReader.close();
    onlineStream.close();
    // read DTD local
    final InputStreamReader localReader = new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream(currentDefinition));
    final String localDtd = read(localReader);
    localReader.close();
    assertThat(localDtd).isEqualTo(onlineDtd);
}

95. XPathTestCase#testAtSignProperty()

Project: tuscany-sdo
Source File: XPathTestCase.java
View license
/**
     * The presence or absence of the @ sign in a path has no meaning.
     * Properties are always matched by name independent of their XML representation.
     * @throws IOException
     */
public void testAtSignProperty() throws IOException {
    XSDHelper xsdHelper = hc.getXSDHelper();
    XMLHelper xmlHelper = hc.getXMLHelper();
    URL url = getClass().getResource(TEST_MODEL);
    InputStream inputStream = url.openStream();
    xsdHelper.define(inputStream, url.toString());
    inputStream.close();
    XMLDocument doc = xmlHelper.load(getClass().getResourceAsStream(XPATH_XML));
    DataObject drive = doc.getRootObject();
    DataObject folder1 = (DataObject) drive.get("Folder.1");
    String value = folder1.getString("@creation_date");
    assertEquals(value, "2000-03-23");
}

96. SimpleDynamicTestCase#setUp()

View license
/*
    public void dontTestResolveXSDWithoutSchemaLocation() throws IOException {

        URL url = getClass().getResource(TEST_MODEL2);
        InputStream inputStream = url.openStream();
        hc.getXSDHelper().define(inputStream, null);
        inputStream.close();
    	
    	Type quote2Type = th.getType(TEST_NAMESPACE2, "Quote2");
        DataObject quote2 = hc.getDataFactory().create(quote2Type);
        
        quote2.setString("symbol", "fbnt");
        quote2.setString("companyName", "FlyByNightTechnology");
        quote2.setBigDecimal("price", new BigDecimal("1000.0"));
        quote2.setBigDecimal("open1", new BigDecimal("1000.0"));
        quote2.setBigDecimal("high", new BigDecimal("1000.0"));
        quote2.setBigDecimal("low", new BigDecimal("1000.0"));
        quote2.setDouble("volume", 1000);
        quote2.setDouble("change1", 1000);

        DataObject child = quote2.createDataObject("quotes");
        child.setBigDecimal("price", new BigDecimal("2000.0"));

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        hc.getXMLHelper().save(quote2, TEST_NAMESPACE2, "stockQuote", System.out);
    }
    */
protected void setUp() throws Exception {
    super.setUp();
    hc = SDOUtil.createHelperContext();
    th = hc.getTypeHelper();
    // Populate the meta data for the test (Stock Quote) model
    URL url = getClass().getResource(TEST_MODEL);
    InputStream inputStream = url.openStream();
    hc.getXSDHelper().define(inputStream, url.toString());
    inputStream.close();
}

97. OpenTypeTestCase#setUp()

Project: tuscany-sdo
Source File: OpenTypeTestCase.java
View license
protected void setUp() throws Exception {
    super.setUp();
    // Populate the meta data for the test (Stock Quote) model
    URL url = getClass().getResource(TEST_MODEL);
    InputStream inputStream = url.openStream();
    hc = SDOUtil.createHelperContext();
    th = hc.getTypeHelper();
    xsdh = hc.getXSDHelper();
    df = hc.getDataFactory();
    xmlh = hc.getXMLHelper();
    hc.getXSDHelper().define(inputStream, url.toString());
    inputStream.close();
}

98. MetadataInstancePropertiesTestCase#setUp()

View license
public void setUp() throws Exception {
    super.setUp();
    helperContext = SDOUtil.createHelperContext();
    typeHelper = helperContext.getTypeHelper();
    xsdHelper = helperContext.getXSDHelper();
    dataFactory = helperContext.getDataFactory();
    URL url = getClass().getResource(TEST_MODEL);
    InputStream inputStream = url.openStream();
    xsdHelper.define(inputStream, url.toString());
    inputStream.close();
}

99. ChunkedInputStreamTest#ignoresParameterAfterSemiColon()

Project: takes
Source File: ChunkedInputStreamTest.java
View license
/**
     * RqChunk accepts semi-colon and ignores parameters after semi-colon.
     * @throws IOException If some problem inside
     */
@Test
public void ignoresParameterAfterSemiColon() throws IOException {
    final String data = "Build and Run";
    final String ignored = ";ignored-stuff";
    final String length = Integer.toHexString(data.length());
    final InputStream stream = new ChunkedInputStream(IOUtils.toInputStream(Joiner.on(ChunkedInputStreamTest.CRLF).join(length + ignored, data, ChunkedInputStreamTest.END_OF_CHUNK, "")));
    final byte[] buf = new byte[data.length()];
    MatcherAssert.assertThat(stream.read(buf), Matchers.equalTo(data.length()));
    MatcherAssert.assertThat(buf, Matchers.equalTo(data.getBytes()));
    MatcherAssert.assertThat(stream.available(), Matchers.equalTo(0));
    stream.close();
}

100. MainActivity#saveIndexHtml()

Project: task_1
Source File: MainActivity.java
View license
public void saveIndexHtml() throws IOException {
    String str = doc.html();
    InputStream is = new ByteArrayInputStream(str.getBytes());
    File file = new File(context.getFilesDir().getPath() + "//HTML", "index.html");
    FileOutputStream fos = new FileOutputStream(file);
    byte[] bytes = new byte[2048];
    int len = 0;
    while ((len = is.read(bytes)) != -1) {
        fos.write(bytes, 0, len);
    }
    fos.flush();
    fos.close();
    is.close();
}