java.io.OutputStream

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

1. TestContentLengthOutputStream#testBasics()

Project: httpcore
File: TestContentLengthOutputStream.java
public void testBasics() throws Exception {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    SessionOutputBufferMockup datatransmitter = new SessionOutputBufferMockup(buffer);
    OutputStream out = new ContentLengthOutputStream(datatransmitter, 15L);
    byte[] tmp = new byte[10];
    out.write(tmp, 0, 10);
    out.write(1);
    out.write(tmp, 0, 10);
    out.write(tmp, 0, 10);
    out.write(tmp);
    out.write(1);
    out.write(2);
    out.flush();
    out.close();
    byte[] data = datatransmitter.getData();
    assertEquals(15, data.length);
}

2. SimpleUpgradeTestCase#runTest()

Project: undertow
File: SimpleUpgradeTestCase.java
public void runTest(final String url) throws IOException {
    final Socket socket = new Socket(DefaultServer.getHostAddress("default"), DefaultServer.getHostPort("default"));
    InputStream in = socket.getInputStream();
    OutputStream out = socket.getOutputStream();
    out.write(("GET " + url + " HTTP/1.1\r\nConnection: upgrade\r\nUpgrade: servlet\r\n\r\n").getBytes());
    out.flush();
    Assert.assertTrue(readBytes(in).startsWith("HTTP/1.1 101 Switching Protocols\r\n"));
    out.write("Echo Messages\r\n\r\n".getBytes());
    out.flush();
    Assert.assertEquals("Echo Messages\r\n\r\n", readBytes(in));
    out.write("Echo Messages2\r\n\r\n".getBytes());
    out.flush();
    Assert.assertEquals("Echo Messages2\r\n\r\n", readBytes(in));
    out.write("exit\r\n\r\n".getBytes());
    out.flush();
    out.close();
}

3. ZipOutputStream#writeLong()

Project: jdk7u-jdk
File: ZipOutputStream.java
/*
     * Writes a 64-bit int to the output stream in little-endian byte order.
     */
private void writeLong(long v) throws IOException {
    OutputStream out = this.out;
    out.write((int) ((v >>> 0) & 0xff));
    out.write((int) ((v >>> 8) & 0xff));
    out.write((int) ((v >>> 16) & 0xff));
    out.write((int) ((v >>> 24) & 0xff));
    out.write((int) ((v >>> 32) & 0xff));
    out.write((int) ((v >>> 40) & 0xff));
    out.write((int) ((v >>> 48) & 0xff));
    out.write((int) ((v >>> 56) & 0xff));
    written += 8;
}

4. ZipOutputStream#writeLong()

Project: openjdk
File: ZipOutputStream.java
/*
     * Writes a 64-bit int to the output stream in little-endian byte order.
     */
private void writeLong(long v) throws IOException {
    OutputStream out = this.out;
    out.write((int) ((v >>> 0) & 0xff));
    out.write((int) ((v >>> 8) & 0xff));
    out.write((int) ((v >>> 16) & 0xff));
    out.write((int) ((v >>> 24) & 0xff));
    out.write((int) ((v >>> 32) & 0xff));
    out.write((int) ((v >>> 40) & 0xff));
    out.write((int) ((v >>> 48) & 0xff));
    out.write((int) ((v >>> 56) & 0xff));
    written += 8;
}

5. SCPClient#sendBytes()

Project: connectbot
File: SCPClient.java
private void sendBytes(Session sess, byte[] data, String fileName, String mode) throws IOException {
    OutputStream os = sess.getStdin();
    InputStream is = new BufferedInputStream(sess.getStdout(), 512);
    readResponse(is);
    String cline = "C" + mode + " " + data.length + " " + fileName + "\n";
    os.write(cline.getBytes("ISO-8859-1"));
    os.flush();
    readResponse(is);
    os.write(data, 0, data.length);
    os.write(0);
    os.flush();
    readResponse(is);
    os.write("E\n".getBytes("ISO-8859-1"));
    os.flush();
}

6. RFC6637KDFCalculator#KDF()

Project: bc-java
File: RFC6637KDFCalculator.java
// RFC 6637 - Section 7
//   Implements KDF( X, oBits, Param );
//   Input: point X = (x,y)
//   oBits - the desired size of output
//   hBits - the size of output of hash function Hash
//   Param - octets representing the parameters
//   Assumes that oBits <= hBits
//   Convert the point X to the octet string, see section 6:
//   ZB' = 04 || x || y
//   and extract the x portion from ZB'
//         ZB = x;
//         MB = Hash ( 00 || 00 || 00 || 01 || ZB || Param );
//   return oBits leftmost bits of MB.
private static byte[] KDF(PGPDigestCalculator digCalc, ECPoint s, int keyLen, byte[] param) throws IOException {
    byte[] ZB = s.getXCoord().getEncoded();
    OutputStream dOut = digCalc.getOutputStream();
    dOut.write(0x00);
    dOut.write(0x00);
    dOut.write(0x00);
    dOut.write(0x01);
    dOut.write(ZB);
    dOut.write(param);
    byte[] digest = digCalc.getDigest();
    byte[] key = new byte[keyLen];
    System.arraycopy(digest, 0, key, 0, key.length);
    return key;
}

7. RFC6637KDFCalculator#KDF()

Project: bc-java
File: RFC6637KDFCalculator.java
// RFC 6637 - Section 7
//   Implements KDF( X, oBits, Param );
//   Input: point X = (x,y)
//   oBits - the desired size of output
//   hBits - the size of output of hash function Hash
//   Param - octets representing the parameters
//   Assumes that oBits <= hBits
//   Convert the point X to the octet string, see section 6:
//   ZB' = 04 || x || y
//   and extract the x portion from ZB'
//         ZB = x;
//         MB = Hash ( 00 || 00 || 00 || 01 || ZB || Param );
//   return oBits leftmost bits of MB.
private static byte[] KDF(PGPDigestCalculator digCalc, ECPoint s, int keyLen, byte[] param) throws IOException {
    byte[] ZB = s.getXCoord().getEncoded();
    OutputStream dOut = digCalc.getOutputStream();
    dOut.write(0x00);
    dOut.write(0x00);
    dOut.write(0x00);
    dOut.write(0x01);
    dOut.write(ZB);
    dOut.write(param);
    byte[] digest = digCalc.getDigest();
    byte[] key = new byte[keyLen];
    System.arraycopy(digest, 0, key, 0, key.length);
    return key;
}

8. CustomRamProviderTest#createNonEmptyFile()

Project: commons-vfs
File: CustomRamProviderTest.java
private InputStream createNonEmptyFile() throws FileSystemException, IOException {
    final FileObject root = manager.resolveFile("ram://file");
    root.createFile();
    final FileContent content = root.getContent();
    final OutputStream output = this.closeOnTearDown(content.getOutputStream());
    output.write(1);
    output.write(2);
    output.write(3);
    output.flush();
    output.close();
    return this.closeOnTearDown(content.getInputStream());
}

9. TestIdentityOutputStream#testBasics()

Project: httpcore
File: TestIdentityOutputStream.java
public void testBasics() throws Exception {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    SessionOutputBufferMockup datatransmitter = new SessionOutputBufferMockup(buffer);
    OutputStream out = new IdentityOutputStream(datatransmitter);
    byte[] tmp = new byte[10];
    out.write(tmp, 0, 10);
    out.write(tmp);
    out.write(1);
    out.flush();
    out.close();
    byte[] data = datatransmitter.getData();
    assertEquals(21, data.length);
}

10. TestFileSystem#testTempFile()

Project: ThriftyPaxos
File: TestFileSystem.java
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);
}

11. StreamUtilsTests#testNonClosingOutputStream()

Project: spring-android
File: StreamUtilsTests.java
public void testNonClosingOutputStream() throws Exception {
    OutputStream source = mock(OutputStream.class);
    OutputStream nonClosing = StreamUtils.nonClosing(source);
    nonClosing.write(1);
    nonClosing.write(bytes);
    nonClosing.write(bytes, 1, 2);
    nonClosing.close();
    InOrder ordered = inOrder(source);
    ordered.verify(source).write(1);
    ordered.verify(source).write(bytes, 0, bytes.length);
    ordered.verify(source).write(bytes, 1, 2);
    ordered.verify(source, never()).close();
}

12. SendUsernameServlet#doPost()

Project: keycloak
File: SendUsernameServlet.java
@Override
protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("In SendUsername Servlet doPost()");
    if (checkRoles != null) {
        for (String role : checkRoles) {
            System.out.println("check role: " + role);
            Assert.assertTrue(req.isUserInRole(role));
        }
    }
    resp.setContentType("text/plain");
    OutputStream stream = resp.getOutputStream();
    Principal principal = req.getUserPrincipal();
    stream.write("request-path: ".getBytes());
    stream.write(req.getPathInfo().getBytes());
    stream.write("\n".getBytes());
    stream.write("principal=".getBytes());
    if (principal == null) {
        stream.write("null".getBytes());
        return;
    }
    String name = principal.getName();
    stream.write(name.getBytes());
    sentPrincipal = principal;
}

13. MockFileSystemTestCase#testDirectoryStreamGlobFiltered()

Project: lucene-solr
File: MockFileSystemTestCase.java
/** Tests that newDirectoryStream with globbing works correctly */
public void testDirectoryStreamGlobFiltered() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("foo"));
    file.write(5);
    file.close();
    file = Files.newOutputStream(dir.resolve("bar"));
    file.write(5);
    file.close();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, "f*")) {
        int count = 0;
        for (Path path : stream) {
            assertTrue(path instanceof FilterPath);
            ++count;
        }
        assertEquals(1, count);
    }
    dir.getFileSystem().close();
}

14. VfsStreamsTests#testWriteOverwriteReadWithStrategy()

Project: xodus
File: VfsStreamsTests.java
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();
}

15. VfsStreamsTests#writeRandomAccessOverwriteRead2()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeRandomAccessOverwriteRead2() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    OutputStream outputStream = vfs.appendFile(txn, file0);
    outputStream.write((HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN).getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    outputStream = vfs.writeFile(txn, file0, 1000000);
    outputStream.write("x".getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    final InputStream inputStream = vfs.readFile(txn, file0);
    Assert.assertEquals(HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + HOEGAARDEN + 'x', streamAsString(inputStream));
    inputStream.close();
    txn.abort();
}

16. VfsStreamsTests#writeOverwriteRead()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeOverwriteRead() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    OutputStream outputStream = vfs.appendFile(txn, file0);
    outputStream.write(HOEGAARDEN.getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    outputStream = vfs.writeFile(txn, file0);
    outputStream.write("x".getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    final InputStream inputStream = vfs.readFile(txn, file0);
    Assert.assertEquals('x' + HOEGAARDEN.substring(1), streamAsString(inputStream));
    inputStream.close();
    txn.abort();
}

17. TestUpgrade#testErrorUpgrading()

Project: ThriftyPaxos
File: TestUpgrade.java
private void testErrorUpgrading() throws Exception {
    deleteDb("upgrade");
    OutputStream out;
    out = FileUtils.newOutputStream(getBaseDir() + "/upgrade.data.db", false);
    out.write(new byte[10000]);
    out.close();
    out = FileUtils.newOutputStream(getBaseDir() + "/upgrade.index.db", false);
    out.write(new byte[10000]);
    out.close();
    assertThrows(ErrorCode.FILE_VERSION_ERROR_1, this).getConnection("upgrade");
    assertTrue(FileUtils.exists(getBaseDir() + "/upgrade.data.db"));
    assertTrue(FileUtils.exists(getBaseDir() + "/upgrade.index.db"));
    deleteDb("upgrade");
}

18. TestCsv#testChangeData()

Project: ThriftyPaxos
File: TestCsv.java
private void testChangeData() throws Exception {
    OutputStream out = FileUtils.newOutputStream(getBaseDir() + "/test.tsv", false);
    out.write("a,b,c,d,e,f,g\n1".getBytes());
    out.close();
    Connection conn = getConnection("csv");
    Statement stat = conn.createStatement();
    ResultSet rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv')");
    assertEquals(7, rs.getMetaData().getColumnCount());
    assertEquals("A", rs.getMetaData().getColumnLabel(1));
    rs.next();
    assertEquals(1, rs.getInt(1));
    out = FileUtils.newOutputStream(getBaseDir() + "/test.tsv", false);
    out.write("x".getBytes());
    out.close();
    rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv')");
    assertEquals(1, rs.getMetaData().getColumnCount());
    assertEquals("X", rs.getMetaData().getColumnLabel(1));
    assertFalse(rs.next());
    conn.close();
}

19. SignSafeOutputStreamTest#testSignSafeQuotedPrintableOutputStream()

Project: k-9
File: SignSafeOutputStreamTest.java
@Test
public void testSignSafeQuotedPrintableOutputStream() throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    OutputStream signSafeOutputStream = new SignSafeOutputStream(byteArrayOutputStream);
    OutputStream quotedPrintableOutputStream = new QuotedPrintableOutputStream(signSafeOutputStream, false);
    quotedPrintableOutputStream.write(INPUT_STRING.getBytes("US-ASCII"));
    quotedPrintableOutputStream.close();
    signSafeOutputStream.close();
    assertEquals(EXPECTED_QUOTED_PRINTABLE_SIGNSAFE, new String(byteArrayOutputStream.toByteArray(), "US-ASCII"));
}

20. InBandBytestreamSessionTest#shouldSendNothingOnSuccessiveCallsToFlush()

Project: Smack
File: InBandBytestreamSessionTest.java
/**
     * Test successive calls to the output stream flush() method.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldSendNothingOnSuccessiveCallsToFlush() throws Exception {
    byte[] controlData = new byte[blockSize * 3];
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID);
    // set acknowledgments for the data packets
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ, incrementingSequence);
    protocol.addResponse(resultIQ, incrementingSequence);
    protocol.addResponse(resultIQ, incrementingSequence);
    OutputStream outputStream = session.getOutputStream();
    outputStream.write(controlData);
    outputStream.flush();
    outputStream.flush();
    outputStream.flush();
    protocol.verifyAll();
}

21. InBandBytestreamSessionMessageTest#shouldSendNothingOnSuccessiveCallsToFlush()

Project: Smack
File: InBandBytestreamSessionMessageTest.java
/**
     * Test successive calls to the output stream flush() method.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldSendNothingOnSuccessiveCallsToFlush() throws Exception {
    byte[] controlData = new byte[blockSize * 3];
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID);
    // verify the data packets
    protocol.addResponse(null, incrementingSequence);
    protocol.addResponse(null, incrementingSequence);
    protocol.addResponse(null, incrementingSequence);
    OutputStream outputStream = session.getOutputStream();
    outputStream.write(controlData);
    outputStream.flush();
    outputStream.flush();
    outputStream.flush();
    protocol.verifyAll();
}

22. TestAvatarFailover#testFailoverWithFingerPrintMismatch()

Project: hadoop-20
File: TestAvatarFailover.java
/**
   * This tests a failover when the client and server fingerprints don't match.
   */
@Test
public void testFailoverWithFingerPrintMismatch() throws Exception {
    int blocksize = 1024;
    setUp(false, "testFailoverWithFingerPrintMismatch", blocksize);
    // Write some data.
    OutputStream out = dafs.create(new Path("/test"));
    byte[] buffer = new byte[blocksize];
    out.write(buffer, 0, buffer.length);
    // Perform the failover.
    cluster.failOver();
    TestAvatarFailoverHandler h = new TestAvatarFailoverHandler();
    InjectionHandler.set(h);
    // This should get a new block from the namenode and simulate the finger
    // print mismatch.
    out.write(buffer, 0, buffer.length);
    out.write(buffer, 0, buffer.length);
    out.close();
}

23. TestChunkCoding#testChunkedConsistence()

Project: httpcore
File: TestChunkCoding.java
public void testChunkedConsistence() throws IOException {
    String input = "76126;27823abcd;:q38a-\nkjc\rk%1ad\tkh/asdui\r\njkh+?\\suweb";
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    OutputStream out = new ChunkedOutputStream(new SessionOutputBufferMockup(buffer));
    out.write(EncodingUtils.getBytes(input, CONTENT_CHARSET));
    out.flush();
    out.close();
    out.close();
    buffer.close();
    InputStream in = new ChunkedInputStream(new SessionInputBufferMockup(buffer.toByteArray()));
    byte[] d = new byte[10];
    ByteArrayOutputStream result = new ByteArrayOutputStream();
    int len = 0;
    while ((len = in.read(d)) > 0) {
        result.write(d, 0, len);
    }
    String output = EncodingUtils.getString(result.toByteArray(), CONTENT_CHARSET);
    assertEquals(input, output);
}

24. Base#writeIntent()

Project: APStatus
File: Base.java
@SuppressWarnings("unused")
public static void writeIntent(Socket socket, Intent intent, Key key) throws Exception {
    OutputStream os = socket.getOutputStream();
    ByteBuffer buffer = ByteBuffer.allocate(12);
    byte[] data = getBytes(intent);
    Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
    c.init(Cipher.ENCRYPT_MODE, key);
    buffer.putLong(MAGIC_AES);
    buffer.putInt(c.getOutputSize(data.length));
    os.write(buffer.array());
    os.write(c.doFinal(data));
    os.flush();
    socket.setSoTimeout(ACK_TIMEOUT);
    int ack = socket.getInputStream().read();
    if (ack != ACK)
        throw new Exception("Unexpected ACK = " + ack);
    socket.setSoTimeout(0);
}

25. Base#writeIntent()

Project: APStatus
File: Base.java
public static void writeIntent(Socket socket, Intent intent) throws Exception {
    OutputStream os = socket.getOutputStream();
    ByteBuffer buffer = ByteBuffer.allocate(12);
    byte[] data = getBytes(intent);
    buffer.putLong(MAGIC_RAW);
    buffer.putInt(data.length);
    os.write(buffer.array());
    os.write(data);
    os.flush();
    socket.setSoTimeout(ACK_TIMEOUT);
    int ack = socket.getInputStream().read();
    if (ack != ACK)
        throw new Exception("Unexpected ACK = " + ack);
    socket.setSoTimeout(0);
}

26. CachingPortletOutputHandlerTest#testTooMuchStreamContentThenReset()

Project: uPortal
File: CachingPortletOutputHandlerTest.java
@Test
public void testTooMuchStreamContentThenReset() throws IOException {
    final CachingPortletOutputHandler cachingOutputHandler = new CachingPortletOutputHandler(portletOutputHandler, 100);
    when(portletOutputHandler.getOutputStream()).thenReturn(NullOutputStream.NULL_OUTPUT_STREAM);
    final String output = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    final OutputStream outputStream = cachingOutputHandler.getOutputStream();
    outputStream.write(output.getBytes());
    outputStream.write(output.getBytes());
    CachedPortletData<Long> cachedPortletData = cachingOutputHandler.getCachedPortletData(1l, new CacheControlImpl());
    assertNull(cachedPortletData);
    cachingOutputHandler.reset();
    outputStream.write(output.getBytes());
    cachedPortletData = cachingOutputHandler.getCachedPortletData(1l, new CacheControlImpl());
    assertNotNull(cachedPortletData);
    assertArrayEquals(output.getBytes(), cachedPortletData.getCachedStreamOutput());
}

27. AtomicFileOutputStreamTest#testOverwriteFile()

Project: zookeeper
File: AtomicFileOutputStreamTest.java
/**
     * Test case where there is no existing file
     */
@Test
public void testOverwriteFile() throws IOException {
    assertTrue("Creating empty dst file", dstFile.createNewFile());
    OutputStream fos = new AtomicFileOutputStream(dstFile);
    assertTrue("Empty file still exists", dstFile.exists());
    fos.write(TEST_STRING.getBytes());
    fos.flush();
    // Original contents still in place
    assertEquals("", ClientBase.readFile(dstFile));
    fos.close();
    // New contents replace original file
    String readBackData = ClientBase.readFile(dstFile);
    assertEquals(TEST_STRING, readBackData);
}

28. AtomicFileOutputStreamTest#testWriteNewFile()

Project: zookeeper
File: AtomicFileOutputStreamTest.java
/**
     * Test case where there is no existing file
     */
@Test
public void testWriteNewFile() throws IOException {
    OutputStream fos = new AtomicFileOutputStream(dstFile);
    assertFalse(dstFile.exists());
    fos.write(TEST_STRING.getBytes());
    fos.flush();
    assertFalse(dstFile.exists());
    fos.close();
    assertTrue(dstFile.exists());
    String readBackData = ClientBase.readFile(dstFile);
    assertEquals(TEST_STRING, readBackData);
}

29. DigifitSynchronizer#callDigifitEndpoint()

Project: runnerup
File: DigifitSynchronizer.java
private JSONObject callDigifitEndpoint(String url, JSONObject request) throws IOException, MalformedURLException, ProtocolException, JSONException {
    HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
    conn.setDoOutput(true);
    conn.setRequestMethod(RequestMethod.POST.name());
    conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    addCookies(conn);
    OutputStream out = conn.getOutputStream();
    out.write(request.toString().getBytes());
    out.flush();
    out.close();
    JSONObject response = null;
    if (conn.getResponseCode() == HttpStatus.SC_OK) {
        try {
            response = SyncHelper.parse(conn.getInputStream());
        } finally {
            conn.disconnect();
        }
    }
    return response;
}

30. DefaultSftpClient#send()

Project: mina-sshd
File: DefaultSftpClient.java
@Override
public int send(int cmd, Buffer buffer) throws IOException {
    int id = cmdId.incrementAndGet();
    int len = buffer.available();
    if (log.isTraceEnabled()) {
        log.trace("send({}) cmd={}, len={}, id={}", getClientChannel(), SftpConstants.getCommandMessageName(cmd), len, id);
    }
    OutputStream dos = channel.getInvertedIn();
    BufferUtils.writeInt(dos, 1 + /* cmd */
    (Integer.SIZE / Byte.SIZE) + /* id */
    len, workBuf);
    dos.write(cmd & 0xFF);
    BufferUtils.writeInt(dos, id, workBuf);
    dos.write(buffer.array(), buffer.rpos(), len);
    dos.flush();
    return id;
}

31. QRcode#generateCode()

Project: maven-framework-project
File: QRcode.java
/**
	 * ?????
	 * @param content ??
	 * @param charset ????
	 * @param width ?
	 * @param height ?
	 * @param target ???????
	 * @throws FileNotFoundException
	 * @throws IOException
	 */
private static void generateCode(String content, String charset, int width, int height, File target) throws FileNotFoundException, IOException {
    ByteArrayOutputStream out = QRCode.from(content).withCharset(charset).withSize(width, height).to(ImageType.PNG).stream();
    OutputStream outStream = new FileOutputStream(target);
    outStream.write(out.toByteArray());
    outStream.flush();
    outStream.close();
}

32. AbstractLoggerWriterTest#testFlush()

Project: logging-log4j2
File: AbstractLoggerWriterTest.java
@Test
public void testFlush() throws IOException {
    final OutputStream out = EasyMock.createMock(OutputStream.class);
    // expect the flush to come through to the mocked OutputStream
    out.flush();
    out.close();
    replay(out);
    try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()).filter(out).setLevel(LEVEL).buildOutputStream()) {
        filteredOut.flush();
    }
    verify(out);
}

33. AbstractLoggerOutputStreamTest#testFlush()

Project: logging-log4j2
File: AbstractLoggerOutputStreamTest.java
@Test
public void testFlush() throws IOException {
    final OutputStream os = EasyMock.createMock("out", OutputStream.class);
    // expect the flush to come through to the mocked OutputStream
    os.flush();
    os.close();
    replay(os);
    try (final OutputStream filteredOut = IoBuilder.forLogger(getExtendedLogger()).filter(os).setLevel(LEVEL).buildOutputStream()) {
        filteredOut.flush();
    }
    verify(os);
}

34. PerformanceRun#testRawPerformance()

Project: logging-log4j2
File: PerformanceRun.java
@Test
@Ignore("Why was this test disabled?")
public void testRawPerformance() throws Exception {
    final OutputStream os = new FileOutputStream("target/testos.log", true);
    final long result1 = writeToStream(COUNT, os);
    os.close();
    final OutputStream bos = new BufferedOutputStream(new FileOutputStream("target/testbuffer.log", true));
    final long result2 = writeToStream(COUNT, bos);
    bos.close();
    final Writer w = new FileWriter("target/testwriter.log", true);
    final long result3 = writeToWriter(COUNT, w);
    w.close();
    final FileOutputStream cos = new FileOutputStream("target/testchannel.log", true);
    final FileChannel channel = cos.getChannel();
    final long result4 = writeToChannel(COUNT, channel);
    cos.close();
    System.out.println("###############################################");
    System.out.println("FileOutputStream: " + result1);
    System.out.println("BufferedOutputStream: " + result2);
    System.out.println("FileWriter: " + result3);
    System.out.println("FileChannel: " + result4);
    System.out.println("###############################################");
}

35. PerformanceComparison#testRawPerformance()

Project: logging-log4j2
File: PerformanceComparison.java
//@Test
public void testRawPerformance() throws Exception {
    final OutputStream os = new FileOutputStream("target/testos.log", true);
    final long result1 = writeToStream(COUNT, os);
    os.close();
    final OutputStream bos = new BufferedOutputStream(new FileOutputStream("target/testbuffer.log", true));
    final long result2 = writeToStream(COUNT, bos);
    bos.close();
    final Writer w = new FileWriter("target/testwriter.log", true);
    final long result3 = writeToWriter(COUNT, w);
    w.close();
    final FileOutputStream cos = new FileOutputStream("target/testchannel.log", true);
    final FileChannel channel = cos.getChannel();
    final long result4 = writeToChannel(COUNT, channel);
    cos.close();
    System.out.println("###############################################");
    System.out.println("FileOutputStream: " + result1);
    System.out.println("BufferedOutputStream: " + result2);
    System.out.println("FileWriter: " + result3);
    System.out.println("FileChannel: " + result4);
    System.out.println("###############################################");
}

36. AbstractSnappyStreamTest#testCloseIsIdempotent()

Project: snappy
File: AbstractSnappyStreamTest.java
@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();
}

37. SocketTest#testWriteAfterClose()

Project: j2objc
File: SocketTest.java
public void testWriteAfterClose() throws Exception {
    MockServer server = new MockServer();
    server.enqueue(new byte[0], 3);
    Socket socket = new Socket("localhost", server.port);
    OutputStream out = socket.getOutputStream();
    out.write(5);
    out.write(3);
    socket.close();
    out.close();
    try {
        out.write(9);
        fail();
    } catch (IOException expected) {
    }
    server.shutdown();
}

38. URLConnectionTest#fullyBufferedPostIsTooLong()

Project: okhttp
File: URLConnectionTest.java
@Test
public void fullyBufferedPostIsTooLong() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    connection = urlFactory.open(server.url("/b").url());
    connection.setRequestProperty("Content-Length", "3");
    connection.setRequestMethod("POST");
    OutputStream out = connection.getOutputStream();
    out.write('a');
    out.write('b');
    out.write('c');
    try {
        out.write('d');
        out.flush();
        fail();
    } catch (IOException expected) {
    }
}

39. URLConnectionTest#fullyBufferedPostIsTooShort()

Project: okhttp
File: URLConnectionTest.java
@Test
public void fullyBufferedPostIsTooShort() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    connection = urlFactory.open(server.url("/b").url());
    connection.setRequestProperty("Content-Length", "4");
    connection.setRequestMethod("POST");
    OutputStream out = connection.getOutputStream();
    out.write('a');
    out.write('b');
    out.write('c');
    try {
        out.close();
        fail();
    } catch (IOException expected) {
    }
}

40. ByteArrayHandler#compress()

Project: bc-java
File: ByteArrayHandler.java
private static byte[] compress(byte[] clearData, String fileName, int algorithm) throws IOException {
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    PGPCompressedDataGenerator comData = new PGPCompressedDataGenerator(algorithm);
    // open it with the final destination
    OutputStream cos = comData.open(bOut);
    PGPLiteralDataGenerator lData = new PGPLiteralDataGenerator();
    // we want to generate compressed data. This might be a user option later,
    // in which case we would pass in bOut.
    OutputStream pOut = // the compressed output stream
    lData.open(// the compressed output stream
    cos, PGPLiteralData.BINARY, // "filename" to store
    fileName, // length of clear data
    clearData.length, // current time
    new Date());
    pOut.write(clearData);
    pOut.close();
    comData.close();
    return bOut.toByteArray();
}

41. StreamMultiplexerTest#testByteEncoding()

Project: bazel
File: StreamMultiplexerTest.java
@Test
public void testByteEncoding() throws IOException {
    OutputStream devNull = ByteStreams.nullOutputStream();
    StreamDemultiplexer demux = new StreamDemultiplexer((byte) 1, devNull);
    StreamMultiplexer mux = new StreamMultiplexer(demux);
    OutputStream out = mux.createStdout();
    // When we cast 266 to a byte, we get 10. So basically, we ended up
    // comparing 266 with 10 as an integer (because out.write takes an int),
    // and then later cast it to 10. This way we'd end up with a control
    // character \n in the middle of the payload which would then screw things
    // up when the real control character arrived. The fixed version of the
    // StreamMultiplexer avoids this problem by always casting to a byte before
    // carrying out any comparisons.
    out.write(266);
    out.write(10);
}

42. PositionedCryptoInputStreamTest#prepareData()

Project: commons-crypto
File: PositionedCryptoInputStreamTest.java
private void prepareData() throws IOException {
    CryptoCipher cipher = null;
    try {
        cipher = (CryptoCipher) ReflectionUtils.newInstance(ReflectionUtils.getClassByName(AbstractCipherTest.JCE_CIPHER_CLASSNAME), props, transformation);
    } catch (ClassNotFoundException cnfe) {
        throw new IOException("Illegal crypto cipher!");
    }
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    // encryption data
    OutputStream out = new CryptoOutputStream(baos, cipher, bufferSize, new SecretKeySpec(key, "AES"), new IvParameterSpec(iv));
    out.write(testData);
    out.flush();
    out.close();
    encData = baos.toByteArray();
}

43. TestAtomicFileOutputStream#testOverwriteFile()

Project: hadoop-20
File: TestAtomicFileOutputStream.java
/**
   * Test case where there is no existing file
   */
@Test
public void testOverwriteFile() throws IOException {
    assertTrue("Creating empty dst file", DST_FILE.createNewFile());
    OutputStream fos = new AtomicFileOutputStream(DST_FILE);
    assertTrue("Empty file still exists", DST_FILE.exists());
    fos.write(TEST_STRING.getBytes());
    fos.flush();
    // Original contents still in place
    assertEquals("", DFSTestUtil.readFile(DST_FILE));
    fos.close();
    // New contents replace original file
    String readBackData = DFSTestUtil.readFile(DST_FILE);
    assertEquals(TEST_STRING, readBackData);
}

44. TestAtomicFileOutputStream#testWriteNewFile()

Project: hadoop-20
File: TestAtomicFileOutputStream.java
/**
   * Test case where there is no existing file
   */
@Test
public void testWriteNewFile() throws IOException {
    OutputStream fos = new AtomicFileOutputStream(DST_FILE);
    assertFalse(DST_FILE.exists());
    fos.write(TEST_STRING.getBytes());
    fos.flush();
    assertFalse(DST_FILE.exists());
    fos.close();
    assertTrue(DST_FILE.exists());
    String readBackData = DFSTestUtil.readFile(DST_FILE);
    assertEquals(TEST_STRING, readBackData);
}

45. CanonTestCase#dumpForFail()

Project: derby
File: CanonTestCase.java
/**
     * Dump the output that did not compare correctly into the failure folder
     * with the name this.getName() + ".out".
     * 
     * @param rawOutput
     * @throws IOException
     * @throws PrivilegedActionException
     */
private void dumpForFail(byte[] rawOutput) throws IOException, PrivilegedActionException {
    File folder = getFailureFolder();
    final File outFile = new File(folder, getName() + ".out");
    OutputStream outStream = AccessController.doPrivileged(new PrivilegedExceptionAction<OutputStream>() {

        public OutputStream run() throws IOException {
            return new FileOutputStream(outFile);
        }
    });
    outStream.write(rawOutput);
    outStream.flush();
    outStream.close();
}

46. NativeGCMCipherOutputStreamTest#testWriteDataUsingOffsetsAndPreallocatedBuffer()

Project: conceal
File: NativeGCMCipherOutputStreamTest.java
private void testWriteDataUsingOffsetsAndPreallocatedBuffer(int bufferSize) throws Exception {
    OutputStream outputStream = mCrypto.getCipherOutputStream(mCipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME), new byte[bufferSize]);
    outputStream.write(mData, 0, mData.length / 2);
    outputStream.write(mData, mData.length / 2, mData.length / 2 + mData.length % 2);
    outputStream.close();
    byte[] encryptedData = CryptoSerializerHelper.cipherText(mCipherOutputStream.toByteArray());
    assertTrue(CryptoTestUtils.ENCRYPTED_DATA_NULL, encryptedData != null);
    assertTrue(CryptoTestUtils.ENCRYPTED_DATA_OF_DIFFERENT_LENGTH, encryptedData.length == mData.length);
    assertTrue(CryptoTestUtils.DATA_IS_NOT_ENCRYPTED, !Arrays.equals(mData, encryptedData));
}

47. NativeGCMCipherOutputStreamTest#testWriteDataUsingOffsets()

Project: conceal
File: NativeGCMCipherOutputStreamTest.java
public void testWriteDataUsingOffsets() throws Exception {
    OutputStream outputStream = mCrypto.getCipherOutputStream(mCipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(mData, 0, mData.length / 2);
    outputStream.write(mData, mData.length / 2, mData.length / 2 + mData.length % 2);
    outputStream.close();
    byte[] encryptedData = CryptoSerializerHelper.cipherText(mCipherOutputStream.toByteArray());
    assertTrue(CryptoTestUtils.ENCRYPTED_DATA_NULL, encryptedData != null);
    assertTrue(CryptoTestUtils.ENCRYPTED_DATA_OF_DIFFERENT_LENGTH, encryptedData.length == mData.length);
    assertTrue(CryptoTestUtils.DATA_IS_NOT_ENCRYPTED, !Arrays.equals(mData, encryptedData));
}

48. UIInitHandler#commitJsonResponse()

Project: vaadin
File: UIInitHandler.java
/**
     * Commit the JSON response. We can't write immediately to the output stream
     * as we want to write only a critical notification if something goes wrong
     * during the response handling.
     * 
     * @param request
     *            The request that resulted in this response
     * @param response
     *            The response to write to
     * @param json
     *            The JSON to write
     * @return true if the JSON was written successfully, false otherwise
     * @throws IOException
     *             If there was an exception while writing to the output
     */
static boolean commitJsonResponse(VaadinRequest request, VaadinResponse response, String json) throws IOException {
    // The response was produced without errors so write it to the client
    response.setContentType(JsonConstants.JSON_CONTENT_TYPE);
    // Ensure that the browser does not cache UIDL responses.
    // iOS 6 Safari requires this (#9732)
    response.setHeader("Cache-Control", "no-cache");
    byte[] b = json.getBytes("UTF-8");
    response.setContentLength(b.length);
    OutputStream outputStream = response.getOutputStream();
    outputStream.write(b);
    // NOTE GateIn requires the buffers to be flushed to work
    outputStream.flush();
    return true;
}

49. SassLinker#writeFromInputStream()

Project: vaadin
File: SassLinker.java
/**
     * Writes the contents of an InputStream out to a file.
     * 
     * @param contents
     * @param tempfile
     * @throws IOException
     */
private void writeFromInputStream(InputStream contents, File tempfile) throws IOException {
    // write the inputStream to a FileOutputStream
    OutputStream out = new FileOutputStream(tempfile);
    int read = 0;
    byte[] bytes = new byte[1024];
    while ((read = contents.read(bytes)) != -1) {
        out.write(bytes, 0, read);
    }
    contents.close();
    out.flush();
    out.close();
}

50. CachingPortletOutputHandlerTest#testTooMuchStreamContent()

Project: uPortal
File: CachingPortletOutputHandlerTest.java
@Test
public void testTooMuchStreamContent() throws IOException {
    final CachingPortletOutputHandler cachingOutputHandler = new CachingPortletOutputHandler(portletOutputHandler, 100);
    when(portletOutputHandler.getOutputStream()).thenReturn(NullOutputStream.NULL_OUTPUT_STREAM);
    final String output = "1234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890";
    final OutputStream outputStream = cachingOutputHandler.getOutputStream();
    outputStream.write(output.getBytes());
    outputStream.write(output.getBytes());
    final CachedPortletData<Long> cachedPortletData = cachingOutputHandler.getCachedPortletData(1l, new CacheControlImpl());
    assertNull(cachedPortletData);
}

51. ReceiverTestCase#testAsyncReceiveWholeBytesFailed()

Project: undertow
File: ReceiverTestCase.java
@Test
public void testAsyncReceiveWholeBytesFailed() throws Exception {
    EXCEPTIONS.clear();
    Socket socket = new Socket();
    socket.connect(DefaultServer.getDefaultServerAddress());
    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < 10000; ++i) {
        sb.append("hello world\r\n");
    }
    //send a large request that is too small, then kill the socket
    String request = "POST /fullbytes HTTP/1.1\r\nHost:localhost\r\nContent-Length:" + sb.length() + 100 + "\r\n\r\n" + sb.toString();
    OutputStream outputStream = socket.getOutputStream();
    outputStream.write(request.getBytes("US-ASCII"));
    socket.getInputStream().close();
    outputStream.close();
    IOException e = EXCEPTIONS.poll(2, TimeUnit.SECONDS);
    Assert.assertNotNull(e);
}

52. TestCsv#testPreserveWhitespace()

Project: ThriftyPaxos
File: TestCsv.java
private void testPreserveWhitespace() throws Exception {
    OutputStream out = FileUtils.newOutputStream(getBaseDir() + "/test.tsv", false);
    out.write("a,b\n 1 , 2 \n".getBytes());
    out.close();
    Connection conn = getConnection("csv");
    Statement stat = conn.createStatement();
    ResultSet rs;
    rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv')");
    rs.next();
    assertEquals("1", rs.getString(1));
    assertEquals("2", rs.getString(2));
    rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv', null, 'preserveWhitespace=true')");
    rs.next();
    assertEquals(" 1 ", rs.getString(1));
    assertEquals(" 2 ", rs.getString(2));
    conn.close();
}

53. TestCsv#testCaseSensitiveColumnNames()

Project: ThriftyPaxos
File: TestCsv.java
private void testCaseSensitiveColumnNames() throws Exception {
    OutputStream out = FileUtils.newOutputStream(getBaseDir() + "/test.tsv", false);
    out.write("lower,Mixed,UPPER\n 1 , 2, 3 \n".getBytes());
    out.close();
    Connection conn = getConnection("csv");
    Statement stat = conn.createStatement();
    ResultSet rs;
    rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv')");
    rs.next();
    assertEquals("LOWER", rs.getMetaData().getColumnName(1));
    assertEquals("MIXED", rs.getMetaData().getColumnName(2));
    assertEquals("UPPER", rs.getMetaData().getColumnName(3));
    rs = stat.executeQuery("select * from csvread('" + getBaseDir() + "/test.tsv', null, 'caseSensitiveColumnNames=true')");
    rs.next();
    assertEquals("lower", rs.getMetaData().getColumnName(1));
    assertEquals("Mixed", rs.getMetaData().getColumnName(2));
    assertEquals("UPPER", rs.getMetaData().getColumnName(3));
    conn.close();
}

54. TestGroupedSplits#writeFile()

Project: tez
File: TestGroupedSplits.java
private static void writeFile(FileSystem fs, Path name, CompressionCodec codec, String contents) throws IOException {
    OutputStream stm;
    if (codec == null) {
        stm = fs.create(name);
    } else {
        stm = codec.createOutputStream(fs.create(name));
    }
    stm.write(contents.getBytes());
    stm.close();
}

55. ClassCreationHelper#writeFile()

Project: tapestry-5
File: ClassCreationHelper.java
public void writeFile(ClassWriter writer, String className) throws Exception {
    File classFile = toFile(className);
    classFile.getParentFile().mkdirs();
    OutputStream os = new BufferedOutputStream(new FileOutputStream(classFile));
    os.write(writer.toByteArray());
    os.close();
}

56. TestWindowsFS#testRenameOpenFile()

Project: lucene-solr
File: TestWindowsFS.java
/** Test Files.rename fails if a file has an open inputstream against it */
// TODO: what does windows do here?
public void testRenameOpenFile() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    InputStream is = Files.newInputStream(dir.resolve("stillopen"));
    try {
        Files.move(dir.resolve("stillopen"), dir.resolve("target"), StandardCopyOption.ATOMIC_MOVE);
        fail("should have gotten exception");
    } catch (IOException e) {
        assertTrue(e.getMessage().contains("access denied"));
    }
    is.close();
}

57. TestWindowsFS#testDeleteIfExistsOpenFile()

Project: lucene-solr
File: TestWindowsFS.java
/** Test Files.deleteIfExists fails if a file has an open inputstream against it */
public void testDeleteIfExistsOpenFile() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    InputStream is = Files.newInputStream(dir.resolve("stillopen"));
    try {
        Files.deleteIfExists(dir.resolve("stillopen"));
        fail("should have gotten exception");
    } catch (IOException e) {
        assertTrue(e.getMessage().contains("access denied"));
    }
    is.close();
}

58. TestWindowsFS#testDeleteOpenFile()

Project: lucene-solr
File: TestWindowsFS.java
/** Test Files.delete fails if a file has an open inputstream against it */
public void testDeleteOpenFile() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    InputStream is = Files.newInputStream(dir.resolve("stillopen"));
    try {
        Files.delete(dir.resolve("stillopen"));
        fail("should have gotten exception");
    } catch (IOException e) {
        assertTrue(e.getMessage().contains("access denied"));
    }
    is.close();
}

59. TestLeakFS#testLeakByteChannel()

Project: lucene-solr
File: TestLeakFS.java
/** Test leaks via Files.newByteChannel */
public void testLeakByteChannel() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    SeekableByteChannel leak = Files.newByteChannel(dir.resolve("stillopen"));
    try {
        dir.getFileSystem().close();
        fail("should have gotten exception");
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("file handle leaks"));
    }
    leak.close();
}

60. TestLeakFS#testLeakAsyncFileChannel()

Project: lucene-solr
File: TestLeakFS.java
/** Test leaks via AsynchronousFileChannel.open */
public void testLeakAsyncFileChannel() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    AsynchronousFileChannel leak = AsynchronousFileChannel.open(dir.resolve("stillopen"));
    try {
        dir.getFileSystem().close();
        fail("should have gotten exception");
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("file handle leaks"));
    }
    leak.close();
}

61. TestLeakFS#testLeakFileChannel()

Project: lucene-solr
File: TestLeakFS.java
/** Test leaks via FileChannel.open */
public void testLeakFileChannel() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    FileChannel leak = FileChannel.open(dir.resolve("stillopen"));
    try {
        dir.getFileSystem().close();
        fail("should have gotten exception");
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("file handle leaks"));
    }
    leak.close();
}

62. TestLeakFS#testLeakInputStream()

Project: lucene-solr
File: TestLeakFS.java
/** Test leaks via Files.newInputStream */
public void testLeakInputStream() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("stillopen"));
    file.write(5);
    file.close();
    InputStream leak = Files.newInputStream(dir.resolve("stillopen"));
    try {
        dir.getFileSystem().close();
        fail("should have gotten exception");
    } catch (Exception e) {
        assertTrue(e.getMessage().contains("file handle leaks"));
    }
    leak.close();
}

63. MockFileSystemTestCase#testDirectoryStreamFiltered()

Project: lucene-solr
File: MockFileSystemTestCase.java
/** Tests that newDirectoryStream with a filter works correctly */
public void testDirectoryStreamFiltered() throws IOException {
    Path dir = wrap(createTempDir());
    OutputStream file = Files.newOutputStream(dir.resolve("file1"));
    file.write(5);
    file.close();
    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        int count = 0;
        for (Path path : stream) {
            assertTrue(path instanceof FilterPath);
            if (!path.getFileName().toString().startsWith("extra")) {
                count++;
            }
        }
        assertEquals(1, count);
    }
    dir.getFileSystem().close();
}

64. ZabbixRequestHandler#send()

Project: zorka
File: ZabbixRequestHandler.java
/**
     * Translates zabbix query to beanshell call
     *
     * @param query zabbix query
     *
     * @return query ready to be passed to bsh agent
     */
//	public static String translate(String query) {
//		StringBuilder sb = new StringBuilder(query.length());
//		int pos = 0;
//
//		while (pos < query.length() && query.charAt(pos) != '[') {
//			pos++;
//		}
//
//		sb.append(query.substring(0, pos).replace("__", "."));
//
//		if (pos >= query.length()) {
//			return sb.toString();
//		}
//
//		sb.append('(');
//        pos++;
//
//		while (pos < query.length() && query.charAt(pos) != ']') {
//			if (query.charAt(pos) == '"') {
//				int pstart = pos++;
//				while (pos < query.length() && query.charAt(pos) != '"') {
//					pos++;
//				}
//				sb.append(query.substring(pstart, pos+1));
//			} else {
//				sb.append(query.charAt(pos));
//			}
//			pos++;
//		}
//
//		sb.append(')');
//
//		return sb.toString();
//	}
/**
     * Constructs and sends response
     *
     * @param resp response value
     * @throws IOException if I/O error occurs
     */
private void send(String resp) throws IOException {
    byte[] buf = new byte[resp.length() + zbx_hdr.length + 8];
    for (int i = 0; i < zbx_hdr.length; i++) {
        buf[i] = zbx_hdr[i];
    }
    long len = resp.length();
    for (int i = 0; i < 8; i++) {
        buf[i + zbx_hdr.length] = (byte) (len & 0xff);
        len >>= 8;
    }
    for (int i = 0; i < resp.length(); i++) {
        buf[i + zbx_hdr.length + 8] = (byte) resp.charAt(i);
    }
    OutputStream out = socket.getOutputStream();
    out.write(buf);
    out.flush();
}

65. VFSNotebookRepo#save()

Project: zeppelin
File: VFSNotebookRepo.java
@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
    GsonBuilder gsonBuilder = new GsonBuilder();
    gsonBuilder.setPrettyPrinting();
    Gson gson = gsonBuilder.create();
    String json = gson.toJson(note);
    FileObject rootDir = getRootDir();
    FileObject noteDir = rootDir.resolveFile(note.id(), NameScope.CHILD);
    if (!noteDir.exists()) {
        noteDir.createFolder();
    }
    if (!isDirectory(noteDir)) {
        throw new IOException(noteDir.getName().toString() + " is not a directory");
    }
    FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
    // false means not appending. creates file if not exists
    OutputStream out = noteJson.getContent().getOutputStream(false);
    out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
    out.close();
    noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}

66. VfsStreamsTests#testWriteReadWithStrategy()

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

67. VfsStreamsTests#testTimeFieldsOfFiles()

Project: xodus
File: VfsStreamsTests.java
@Test
public void testTimeFieldsOfFiles() throws IOException, InterruptedException {
    final long start = System.currentTimeMillis();
    Thread.sleep(20);
    final Transaction txn = env.beginTransaction();
    File file0 = vfs.createFile(txn, "file0");
    txn.flush();
    Thread.sleep(20);
    final OutputStream outputStream = vfs.appendFile(txn, file0);
    outputStream.write(RENAT_GILFANOV.getBytes(UTF_8));
    outputStream.close();
    txn.flush();
    file0 = vfs.openFile(txn, "file0", false);
    Assert.assertNotNull(file0);
    Assert.assertTrue(file0.getCreated() > start);
    Assert.assertTrue(file0.getCreated() < file0.getLastModified());
    txn.abort();
}

68. VfsStreamsTests#writeRandomAccessRead()

Project: xodus
File: VfsStreamsTests.java
@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();
}

69. VfsStreamsTests#writeRead5()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeRead5() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    final OutputStream outputStream = vfs.writeFile(txn, file0);
    final int count = 0x10000;
    outputStream.write(new byte[count]);
    outputStream.close();
    final InputStream inputStream = vfs.readFile(txn, file0);
    Assert.assertEquals(count, inputStream.read(new byte[100000], 0, 100000));
    Assert.assertEquals(-1, inputStream.read());
    inputStream.close();
    txn.commit();
}

70. VfsStreamsTests#writeRead4()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeRead4() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    final OutputStream outputStream = vfs.writeFile(txn, file0);
    final int count = 0x10000;
    outputStream.write(new byte[count]);
    outputStream.close();
    final InputStream inputStream = vfs.readFile(txn, file0);
    for (int i = 0; i < count; ++i) {
        Assert.assertEquals(0, inputStream.read());
    }
    inputStream.close();
    txn.commit();
}

71. VfsStreamsTests#writeRead3()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeRead3() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    final OutputStream outputStream = vfs.writeFile(txn, file0);
    outputStream.write(0);
    outputStream.close();
    final InputStream inputStream = vfs.readFile(txn, file0);
    Assert.assertEquals(0, inputStream.read());
    inputStream.close();
    txn.commit();
}

72. VfsStreamsTests#writeRead2()

Project: xodus
File: VfsStreamsTests.java
@Test
public void writeRead2() throws IOException {
    final Transaction txn = env.beginTransaction();
    final File file0 = vfs.createFile(txn, "file0");
    final OutputStream outputStream = vfs.appendFile(txn, file0);
    outputStream.write(HOEGAARDEN.getBytes(UTF_8));
    outputStream.close();
    final InputStream inputStream = vfs.readFile(txn, file0);
    Assert.assertEquals(HOEGAARDEN, streamAsString(inputStream));
    inputStream.close();
    txn.commit();
}

73. VfsStreamsTests#writeRead()

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

74. NettyWebServerTest#stopsServerCleanlyAlsoWhenClientsAreConnected()

Project: webbit
File: NettyWebServerTest.java
@Test
public void stopsServerCleanlyAlsoWhenClientsAreConnected() throws Exception {
    final CountDownLatch stopper = new CountDownLatch(1);
    server = new NettyWebServer(Executors.newSingleThreadScheduledExecutor(), 9080).start().get();
    server.add(new HttpHandler() {

        @Override
        public void handleHttpRequest(HttpRequest request, HttpResponse response, HttpControl control) throws Exception {
            server.stop().get();
            stopper.countDown();
        }
    });
    Socket client = new Socket(InetAddress.getLocalHost(), 9080);
    OutputStream http = client.getOutputStream();
    http.write(("" + "GET /index.html HTTP/1.1\r\n" + "Host: www.example.com\r\n\r\n").getBytes("UTF-8"));
    http.flush();
    assertTrue("Server should have stopped by now", stopper.await(1000, TimeUnit.MILLISECONDS));
}

75. HsqlProperties#save()

Project: voltdb
File: HsqlProperties.java
/**
     *  Saves the properties using JDK2 method if present, otherwise JDK1.
     */
public void save(String fileString) throws Exception {
    // [email protected]
    fa.createParentDirs(fileString);
    OutputStream fos = fa.openOutputStreamElement(fileString);
    FileAccess.FileSync outDescriptor = fa.getFileSync(fos);
    JavaSystem.saveProperties(stringProps, HsqlDatabaseProperties.PRODUCT_NAME + " " + HsqlDatabaseProperties.THIS_FULL_VERSION, fos);
    fos.flush();
    outDescriptor.sync();
    fos.close();
    return;
}

76. SocketResourceFactory#negotiateProtocol()

Project: voldemort
File: SocketResourceFactory.java
private void negotiateProtocol(SocketAndStreams socket, RequestFormatType type) throws IOException {
    OutputStream outputStream = socket.getOutputStream();
    byte[] proposal = ByteUtils.getBytes(type.getCode(), "UTF-8");
    outputStream.write(proposal);
    outputStream.flush();
    DataInputStream inputStream = socket.getInputStream();
    byte[] responseBytes = new byte[2];
    inputStream.readFully(responseBytes);
    String response = ByteUtils.getString(responseBytes, "UTF-8");
    if (response.equals("ok"))
        return;
    else if (response.equals("no"))
        throw new VoldemortException(type.getDisplayName() + " is not an acceptable protcol for the server.");
    else
        throw new VoldemortException("Unknown server response: " + response);
}

77. AbstractSnappyStreamTest#testExtraFlushes()

Project: snappy
File: AbstractSnappyStreamTest.java
@Test
public void testExtraFlushes() throws Exception {
    byte[] random = getRandom(0.5, 500000);
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    OutputStream snappyOut = createOutputStream(out);
    snappyOut.write(random);
    for (int i = 0; i < 10; i++) {
        snappyOut.flush();
    }
    snappyOut.close();
    byte[] compressed = out.toByteArray();
    assertTrue(compressed.length < random.length);
    byte[] uncompressed = uncompress(compressed);
    assertEquals(uncompressed, random);
}

78. InBandBytestreamSessionTest#shouldSendThreeDataPackets1()

Project: Smack
File: InBandBytestreamSessionTest.java
/**
     * Test the output stream write(byte[]) method.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldSendThreeDataPackets1() throws Exception {
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID);
    // set acknowledgments for the data packets
    IQ resultIQ = IBBPacketUtils.createResultIQ(initiatorJID, targetJID);
    protocol.addResponse(resultIQ, incrementingSequence);
    protocol.addResponse(resultIQ, incrementingSequence);
    protocol.addResponse(resultIQ, incrementingSequence);
    byte[] controlData = new byte[blockSize * 3];
    OutputStream outputStream = session.getOutputStream();
    outputStream.write(controlData);
    outputStream.flush();
    protocol.verifyAll();
}

79. InBandBytestreamSessionMessageTest#shouldSendThreeDataPackets1()

Project: Smack
File: InBandBytestreamSessionMessageTest.java
/**
     * Test the output stream write(byte[]) method.
     * 
     * @throws Exception should not happen
     */
@Test
public void shouldSendThreeDataPackets1() throws Exception {
    InBandBytestreamSession session = new InBandBytestreamSession(connection, initBytestream, initiatorJID);
    // verify the data packets
    protocol.addResponse(null, incrementingSequence);
    protocol.addResponse(null, incrementingSequence);
    protocol.addResponse(null, incrementingSequence);
    byte[] controlData = new byte[blockSize * 3];
    OutputStream outputStream = session.getOutputStream();
    outputStream.write(controlData);
    outputStream.flush();
    protocol.verifyAll();
}

80. Webserver#process()

Project: scouter
File: Webserver.java
final void process(Socket clnt) throws IOException {
    InputStream in = new BufferedInputStream(clnt.getInputStream());
    String cmd = readLine(in);
    logging(clnt.getInetAddress().getHostName(), new Date().toString(), cmd);
    while (skipLine(in) > 0) {
    }
    OutputStream out = new BufferedOutputStream(clnt.getOutputStream());
    try {
        doReply(in, out, cmd);
    } catch (BadHttpRequest e) {
        replyError(out, e);
    }
    out.flush();
    in.close();
    out.close();
    clnt.close();
}

81. ByteSourceTest#createTempFile()

Project: sanselan
File: ByteSourceTest.java
protected File createTempFile(byte src[]) throws IOException {
    File file = createTempFile("raw_", ".bin");
    // write test bytes to file.
    OutputStream os = new FileOutputStream(file);
    os = new BufferedOutputStream(os);
    os.write(src);
    os.close();
    // test that all bytes written to file.
    assertTrue(src.length == file.length());
    return file;
}

82. FileBlobStore#storeBlock()

Project: jackrabbit-oak
File: FileBlobStore.java
@Override
protected synchronized void storeBlock(byte[] digest, int level, byte[] data) throws IOException {
    File f = getFile(digest, false);
    if (f.exists()) {
        return;
    }
    File parent = f.getParentFile();
    if (!parent.exists()) {
        parent.mkdirs();
    }
    File temp = new File(parent, f.getName() + ".temp");
    OutputStream out = new FileOutputStream(temp, false);
    out.write(data);
    out.close();
    temp.renameTo(f);
}

83. ParserTest#testExternalEntities()

Project: jackrabbit
File: ParserTest.java
public void testExternalEntities() throws IOException {
    String dname = "target";
    String fname = "test.xml";
    File f = new File(dname, fname);
    OutputStream os = new FileOutputStream(f);
    os.write("testdata".getBytes());
    os.close();
    String testBody = "<?xml version='1.0'?>\n<!DOCTYPE foo [" + " <!ENTITY test SYSTEM \"file:" + dname + "/" + fname + "\">" + "]>\n<foo>&test;</foo>";
    InputStream is = new ByteArrayInputStream(testBody.getBytes("UTF-8"));
    try {
        Document d = DomUtil.parseDocument(is);
        Element root = d.getDocumentElement();
        String text = DomUtil.getText(root);
        fail("parsing this document should cause an exception, but the following external content was included: " + text);
    } catch (Exception expected) {
    }
}

84. URLConnectionTest#testClientSendsContentLength()

Project: j2objc
File: URLConnectionTest.java
public void testClientSendsContentLength() throws Exception {
    server.enqueue(new MockResponse().setBody("A"));
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setDoOutput(true);
    OutputStream out = connection.getOutputStream();
    out.write(new byte[] { 'A', 'B', 'C' });
    out.close();
    assertEquals("A", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    RecordedRequest request = server.takeRequest();
    assertContains(request.getHeaders(), "Content-Length: 3");
}

85. URLConnectionTest#testFlushAfterStreamTransmitted()

Project: j2objc
File: URLConnectionTest.java
// TODO(tball): b/28067294
//    public void testFlushAfterStreamTransmittedWithChunkedEncoding() throws IOException {
//        testFlushAfterStreamTransmitted(TransferKind.CHUNKED);
//    }
// TODO(tball): b/28067294
//    public void testFlushAfterStreamTransmittedWithFixedLength() throws IOException {
//        testFlushAfterStreamTransmitted(TransferKind.FIXED_LENGTH);
//    }
//  JVM failure.
//    public void testFlushAfterStreamTransmittedWithNoLengthHeaders() throws IOException {
//        testFlushAfterStreamTransmitted(TransferKind.END_OF_STREAM);
//    }
/**
     * We explicitly permit apps to close the upload stream even after it has
     * been transmitted.  We also permit flush so that buffered streams can
     * do a no-op flush when they are closed. http://b/3038470
     */
private void testFlushAfterStreamTransmitted(TransferKind transferKind) throws IOException {
    server.enqueue(new MockResponse().setBody("abc"));
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/").openConnection();
    connection.setDoOutput(true);
    byte[] upload = "def".getBytes("UTF-8");
    if (transferKind == TransferKind.CHUNKED) {
        connection.setChunkedStreamingMode(0);
    } else if (transferKind == TransferKind.FIXED_LENGTH) {
        connection.setFixedLengthStreamingMode(upload.length);
    }
    OutputStream out = connection.getOutputStream();
    out.write(upload);
    assertEquals("abc", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    // dubious but permitted
    out.flush();
    try {
        out.write("ghi".getBytes("UTF-8"));
        fail();
    } catch (IOException expected) {
    }
}

86. URLConnectionTest#testResponseRedirectedWithPost()

Project: j2objc
File: URLConnectionTest.java
private void testResponseRedirectedWithPost(int redirectCode) throws Exception {
    server.enqueue(new MockResponse().setResponseCode(redirectCode).addHeader("Location: /page2").setBody("This page has moved!"));
    server.enqueue(new MockResponse().setBody("Page 2"));
    server.play();
    HttpURLConnection connection = (HttpURLConnection) server.getUrl("/page1").openConnection();
    connection.setDoOutput(true);
    byte[] requestBody = { 'A', 'B', 'C', 'D' };
    OutputStream outputStream = connection.getOutputStream();
    outputStream.write(requestBody);
    outputStream.close();
    assertEquals("Page 2", readAscii(connection.getInputStream(), Integer.MAX_VALUE));
    assertTrue(connection.getDoOutput());
    RecordedRequest page1 = server.takeRequest();
    assertEquals("POST /page1 HTTP/1.1", page1.getRequestLine());
    assertEquals(Arrays.toString(requestBody), Arrays.toString(page1.getBody()));
    RecordedRequest page2 = server.takeRequest();
    assertEquals("GET /page2 HTTP/1.1", page2.getRequestLine());
}

87. OldBufferedInputStreamTest#setUp()

Project: j2objc
File: OldBufferedInputStreamTest.java
@Override
protected void setUp() throws IOException {
    fileName = System.getProperty("user.dir");
    String separator = System.getProperty("file.separator");
    if (fileName.charAt(fileName.length() - 1) == separator.charAt(0)) {
        fileName = Support_PlatformFile.getNewPlatformFile(fileName, "input.tst");
    } else {
        fileName = Support_PlatformFile.getNewPlatformFile(fileName + separator, "input.tst");
    }
    OutputStream fos = new FileOutputStream(fileName);
    fos.write(fileString.getBytes());
    fos.close();
    isFile = new FileInputStream(fileName);
    is = new BufferedInputStream(isFile);
}

88. TestGroupedSplits#writeFile()

Project: incubator-tez
File: TestGroupedSplits.java
private static void writeFile(FileSystem fs, Path name, CompressionCodec codec, String contents) throws IOException {
    OutputStream stm;
    if (codec == null) {
        stm = fs.create(name);
    } else {
        stm = codec.createOutputStream(fs.create(name));
    }
    stm.write(contents.getBytes());
    stm.close();
}

89. PipeTest#testQuickBurstWrite()

Project: hudson-2.x
File: PipeTest.java
/**
     * Writer end closes even before the remote computation kicks in.
     */
public void testQuickBurstWrite() throws Exception {
    final Pipe p = Pipe.createLocalToRemote();
    Future<Integer> f = channel.callAsync(new Callable<Integer, IOException>() {

        public Integer call() throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            IOUtils.copy(p.getIn(), baos);
            return baos.size();
        }
    });
    OutputStream os = p.getOut();
    os.write(1);
    os.close();
    // at this point the async executable kicks in.
    // TODO: introduce a lock to ensure the ordering.
    assertEquals(1, (int) f.get());
}

90. BinarySafeStreamTest#test1()

Project: hudson-2.x
File: BinarySafeStreamTest.java
public void test1() throws IOException {
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    OutputStream o = BinarySafeStream.wrap(buf);
    byte[] data = "Sending some data to make sure it's encoded".getBytes("UTF-8");
    o.write(data);
    o.close();
    InputStream in = BinarySafeStream.wrap(new ByteArrayInputStream(buf.toByteArray()));
    for (byte b : data) {
        int ch = in.read();
        assertEquals(b, ch);
    }
    assertEquals(-1, in.read());
}

91. DeepStubbingTest#withArguments()

Project: mockito
File: DeepStubbingTest.java
/**
     * Test that stubbing of methods of different arguments don't interfere
     */
@Test
public void withArguments() throws Exception {
    OutputStream out1 = new ByteArrayOutputStream();
    OutputStream out2 = new ByteArrayOutputStream();
    OutputStream out3 = new ByteArrayOutputStream();
    SocketFactory sf = mock(SocketFactory.class, RETURNS_DEEP_STUBS);
    when(sf.createSocket().getOutputStream()).thenReturn(out1);
    when(sf.createSocket("google.com", 80).getOutputStream()).thenReturn(out2);
    when(sf.createSocket("stackoverflow.com", 80).getOutputStream()).thenReturn(out3);
    assertSame(out1, sf.createSocket().getOutputStream());
    assertSame(out2, sf.createSocket("google.com", 80).getOutputStream());
    assertSame(out3, sf.createSocket("stackoverflow.com", 80).getOutputStream());
}

92. DefaultX11ForwardSupport#messageReceived()

Project: mina-sshd
File: DefaultX11ForwardSupport.java
@Override
public void messageReceived(IoSession session, Readable message) throws Exception {
    ChannelForwardedX11 channel = (ChannelForwardedX11) session.getAttribute(ChannelForwardedX11.class);
    Buffer buffer = new ByteArrayBuffer(message.available() + Long.SIZE, false);
    buffer.putBuffer(message);
    if (log.isTraceEnabled()) {
        log.trace("messageReceived({}) channel={}, len={}", session, channel, buffer.available());
    }
    OutputStream outputStream = channel.getInvertedIn();
    outputStream.write(buffer.array(), buffer.rpos(), buffer.available());
    outputStream.flush();
}

93. DatabaseHelper#copyDataBase()

Project: mHealth-App
File: DatabaseHelper.java
private void copyDataBase() throws IOException {
    InputStream inputStream = mContext.getAssets().open(DATABASE_NAME);
    String outFileName = DB_PATH + DATABASE_NAME;
    OutputStream outputStream = new FileOutputStream(outFileName);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = inputStream.read(buffer)) > 0) {
        outputStream.write(buffer, 0, length);
    }
    outputStream.flush();
    outputStream.close();
    inputStream.close();
}

94. Response#sendFile()

Project: LGame
File: Response.java
public void sendFile(File file) throws IOException {
    contentType = getContentType(file.getName());
    if (!file.exists())
        throw new FileNotFoundException();
    OutputStream outputStream = socket.getOutputStream();
    PrintWriter out = new PrintWriter(outputStream);
    out.println(response);
    for (String line : header) {
        out.println(line);
    }
    out.println("Content-type: " + contentType);
    out.println("Content-length: " + file.length());
    out.println();
    out.flush();
    Files.copy(file.toPath(), outputStream);
    outputStream.flush();
    outputStream.close();
}

95. SocketBench#benchmarkLargeRead()

Project: pluotsorbet
File: SocketBench.java
void benchmarkLargeRead() throws IOException {
    SocketConnection client = (SocketConnection) Connector.open("socket://localhost:8000");
    OutputStream os = client.openOutputStream();
    os.write("GET /bench/benchmark.jar HTTP/1.1\r\nHost: localhost\r\n\r\n".getBytes());
    os.close();
    InputStream is = client.openInputStream();
    byte[] data = new byte[1024];
    int len;
    MemorySampler.sampleMemory("Memory before");
    long start = JVM.monotonicTimeMillis();
    do {
        len = is.read(data);
    } while (len != -1);
    System.out.println("large read time: " + (JVM.monotonicTimeMillis() - start));
    MemorySampler.sampleMemory("Memory  after");
    is.close();
    client.close();
}

96. TestPDFunctionType4#createFunction()

Project: pdfbox
File: TestPDFunctionType4.java
private PDFunctionType4 createFunction(String function, float[] domain, float[] range) throws IOException {
    COSStream stream = new COSStream();
    stream.setInt("FunctionType", 4);
    COSArray domainArray = new COSArray();
    domainArray.setFloatArray(domain);
    stream.setItem("Domain", domainArray);
    COSArray rangeArray = new COSArray();
    rangeArray.setFloatArray(range);
    stream.setItem("Range", rangeArray);
    OutputStream out = stream.createOutputStream();
    byte[] data = function.getBytes("US-ASCII");
    out.write(data, 0, data.length);
    out.close();
    return new PDFunctionType4(stream);
}

97. TestCOSStream#testCompressedStream2Decode()

Project: pdfbox
File: TestCOSStream.java
/**
     * Tests decoding of a stream with 2 filters applied.
     *
     * @throws IOException
     */
public void testCompressedStream2Decode() throws IOException {
    byte[] testString = "This is a test string to be used as input for TestCOSStream".getBytes("ASCII");
    byte[] testStringEncoded = encodeData(testString, COSName.FLATE_DECODE);
    testStringEncoded = encodeData(testStringEncoded, COSName.ASCII85_DECODE);
    COSStream stream = new COSStream();
    COSArray filters = new COSArray();
    filters.add(COSName.ASCII85_DECODE);
    filters.add(COSName.FLATE_DECODE);
    stream.setItem(COSName.FILTER, filters);
    OutputStream output = stream.createRawOutputStream();
    output.write(testStringEncoded);
    output.close();
    validateDecoded(stream, testString);
}

98. TestCOSStream#testCompressedStream1Decode()

Project: pdfbox
File: TestCOSStream.java
/**
     * Tests decoding of a stream with one filter applied.
     *
     * @throws IOException
     */
public void testCompressedStream1Decode() throws IOException {
    byte[] testString = "This is a test string to be used as input for TestCOSStream".getBytes("ASCII");
    byte[] testStringEncoded = encodeData(testString, COSName.FLATE_DECODE);
    COSStream stream = new COSStream();
    OutputStream output = stream.createRawOutputStream();
    output.write(testStringEncoded);
    output.close();
    stream.setItem(COSName.FILTER, COSName.FLATE_DECODE);
    validateDecoded(stream, testString);
}

99. AllReplacer#forwardResultToResponse()

Project: orbeon-forms
File: AllReplacer.java
public static void forwardResultToResponse(ConnectionResult cxr, final ExternalContext.Response response) throws IOException {
    if (response == null)
        // can be null for some unit tests only :(
        return;
    response.setStatus(cxr.statusCode());
    if (cxr.content().contentType().isDefined())
        response.setContentType(cxr.content().contentType().get());
    SubmissionUtils.forwardResponseHeaders(cxr, response);
    // Forward content to response
    final OutputStream outputStream = response.getOutputStream();
    try {
        NetUtils.copyStream(cxr.content().inputStream(), outputStream);
    } finally {
        cxr.close();
    }
    // End document and close
    outputStream.flush();
    outputStream.close();
}

100. CachedFile#refreshFromSource()

Project: openwayback
File: CachedFile.java
private void refreshFromSource() throws IOException {
    File tmpFile = new File(targetFile.getParentFile(), targetFile.getName() + ".TMP");
    InputStream is = sourceUrl.openStream();
    OutputStream fos = new BufferedOutputStream(new FileOutputStream(tmpFile));
    int BUF_SIZE = 4096;
    byte[] buffer = new byte[BUF_SIZE];
    for (int r = -1; (r = is.read(buffer, 0, BUF_SIZE)) != -1; ) {
        fos.write(buffer, 0, r);
    }
    fos.flush();
    fos.close();
    tmpFile.renameTo(targetFile);
}