java.io.OutputStream

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

1. TestContentLengthOutputStream#testBasics()

View license
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
Source File: SimpleUpgradeTestCase.java
View license
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: openjdk
Source File: ZipOutputStream.java
View license
/*
     * 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: jdk7u-jdk
Source File: ZipOutputStream.java
View license
/*
     * 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
Source File: SCPClient.java
View license
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
Source File: RFC6637KDFCalculator.java
View license
// 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
Source File: RFC6637KDFCalculator.java
View license
// 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. SendUsernameServlet#doPost()

Project: keycloak
Source File: SendUsernameServlet.java
View license
@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;
}

9. StreamUtilsTests#testNonClosingOutputStream()

View license
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();
}

10. 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);
}

11. TestIdentityOutputStream#testBasics()

View license
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);
}

12. CustomRamProviderTest#createNonEmptyFile()

View license
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());
}

13. TestChunkCoding#testChunkedConsistence()

Project: httpcore
Source File: TestChunkCoding.java
View license
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);
}

14. TestAvatarFailover#testFailoverWithFingerPrintMismatch()

Project: hadoop-20
Source File: TestAvatarFailover.java
View license
/**
   * 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();
}

15. InBandBytestreamSessionMessageTest#shouldSendNothingOnSuccessiveCallsToFlush()

View license
/**
     * 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();
}

16. InBandBytestreamSessionTest#shouldSendNothingOnSuccessiveCallsToFlush()

View license
/**
     * 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();
}

17. SignSafeOutputStreamTest#testSignSafeQuotedPrintableOutputStream()

Project: k-9
Source File: SignSafeOutputStreamTest.java
View license
@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"));
}

18. TestCsv#testChangeData()

Project: ThriftyPaxos
Source File: TestCsv.java
View license
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. TestUpgrade#testErrorUpgrading()

Project: ThriftyPaxos
Source File: TestUpgrade.java
View license
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");
}

20. VfsStreamsTests#writeOverwriteRead()

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

21. VfsStreamsTests#writeRandomAccessOverwriteRead2()

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

22. 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();
}

23. MockFileSystemTestCase#testDirectoryStreamGlobFiltered()

View license
/** 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();
}

24. NativeGCMCipherOutputStreamTest#testWriteDataUsingOffsets()

View license
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));
}

25. NativeGCMCipherOutputStreamTest#testWriteDataUsingOffsetsAndPreallocatedBuffer()

View license
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));
}

26. CanonTestCase#dumpForFail()

Project: derby
Source File: CanonTestCase.java
View license
/**
     * 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();
}

27. TestAtomicFileOutputStream#testWriteNewFile()

View license
/**
   * 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);
}

28. TestAtomicFileOutputStream#testOverwriteFile()

View license
/**
   * 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);
}

29. PositionedCryptoInputStreamTest#prepareData()

View license
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();
}

30. StreamMultiplexerTest#testByteEncoding()

Project: bazel
Source File: StreamMultiplexerTest.java
View license
@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);
}

31. ByteArrayHandler#compress()

Project: bc-java
Source File: ByteArrayHandler.java
View license
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();
}

32. URLConnectionTest#fullyBufferedPostIsTooShort()

Project: okhttp
Source File: URLConnectionTest.java
View license
@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) {
    }
}

33. URLConnectionTest#fullyBufferedPostIsTooLong()

Project: okhttp
Source File: URLConnectionTest.java
View license
@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) {
    }
}

34. SocketTest#testWriteAfterClose()

Project: j2objc
Source File: SocketTest.java
View license
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();
}

35. 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();
}

36. PerformanceComparison#testRawPerformance()

View license
//@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("###############################################");
}

37. PerformanceRun#testRawPerformance()

Project: logging-log4j2
Source File: PerformanceRun.java
View license
@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("###############################################");
}

38. AbstractLoggerOutputStreamTest#testFlush()

View license
@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);
}

39. AbstractLoggerWriterTest#testFlush()

View license
@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);
}

40. QRcode#generateCode()

Project: maven-framework-project
Source File: QRcode.java
View license
/**
	 * ?????
	 * @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();
}

41. DefaultSftpClient#send()

Project: mina-sshd
Source File: DefaultSftpClient.java
View license
@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;
}

42. DigifitSynchronizer#callDigifitEndpoint()

Project: runnerup
Source File: DigifitSynchronizer.java
View license
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;
}

43. AtomicFileOutputStreamTest#testWriteNewFile()

View license
/**
     * 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);
}

44. AtomicFileOutputStreamTest#testOverwriteFile()

View license
/**
     * 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);
}

45. CachingPortletOutputHandlerTest#testTooMuchStreamContentThenReset()

View license
@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());
}

46. Base#writeIntent()

Project: APStatus
Source File: Base.java
View license
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);
}

47. Base#writeIntent()

Project: APStatus
Source File: Base.java
View license
@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);
}

48. OpenHdfsFileTest#testBasic()

Project: kite
Source File: OpenHdfsFileTest.java
View license
@Test
public void testBasic() throws IOException {
    String msg = "hello world";
    // setup: copy a file to HDFS to prepare inputFile    
    Path inputFile = fileSystem.makeQualified(new Path(testDirectory, "foo.txt.gz"));
    OutputStream out = fileSystem.create(inputFile);
    out = new GZIPOutputStream(out);
    IOUtils.copyBytes(new ByteArrayInputStream(msg.getBytes(Charsets.UTF_8)), out, fileSystem.getConf());
    out.flush();
    out.close();
    Assert.assertTrue(fileSystem.exists(inputFile));
    Command morphline = createMorphline("test-morphlines/openHdfsFile");
    Record record = new Record();
    record.put(Fields.ATTACHMENT_BODY, inputFile.toString());
    Assert.assertTrue(morphline.process(record));
    Record expected = new Record();
    expected.put(Fields.MESSAGE, msg);
    Assert.assertEquals(expected, collector.getFirstRecord());
}

49. MockFileSystemTestCase#testDirectoryStreamFiltered()

View license
/** 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();
}

50. Base64GetEncoderTest#testWrapEncode2()

Project: openjdk
Source File: Base64GetEncoderTest.java
View license
private static void testWrapEncode2(final Base64.Encoder encoder) throws IOException {
    System.err.println("\nEncoder.wrap test II ");
    final byte[] secondTestBuffer = "api/java_util/Base64/index.html#GetEncoderMimeCustom[noLineSeparatorInEncodedString]".getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream secondEncodingStream = new ByteArrayOutputStream();
    OutputStream base64EncodingStream = encoder.wrap(secondEncodingStream);
    base64EncodingStream.write(secondTestBuffer);
    base64EncodingStream.close();
    final byte[] encodedByteArray = secondEncodingStream.toByteArray();
    System.err.print("result = " + new String(encodedByteArray, US_ASCII) + "  after wrap Base64 encoding of string");
    base64EncodedString = new String(encodedByteArray, US_ASCII);
    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException("Base64 encoding contains line separator after wrap 2 invoked  ... \n");
    }
}

51. Base64GetEncoderTest#testWrapEncode1()

Project: openjdk
Source File: Base64GetEncoderTest.java
View license
private static void testWrapEncode1(final Base64.Encoder encoder) throws IOException {
    System.err.println("\nEncoder.wrap test I ");
    final byte[] bytesIn = "fo".getBytes(US_ASCII);
    String base64EncodedString;
    ByteArrayOutputStream encodingStream = new ByteArrayOutputStream();
    OutputStream encoding = encoder.wrap(encodingStream);
    encoding.write(bytesIn);
    encoding.close();
    final byte[] encodedBytes = encodingStream.toByteArray();
    System.err.print("result = " + new String(encodedBytes, US_ASCII) + "  after the Base64 encoding \n");
    base64EncodedString = new String(encodedBytes, US_ASCII);
    if (base64EncodedString.contains("$$$")) {
        throw new RuntimeException("Base64 encoding contains line separator after wrap I test ... \n");
    }
}

52. CachedFile#refreshFromSource()

Project: openwayback
Source File: CachedFile.java
View license
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);
}

53. AllReplacer#forwardResultToResponse()

Project: orbeon-forms
Source File: AllReplacer.java
View license
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();
}

54. TestCOSStream#testCompressedStream1Decode()

Project: pdfbox
Source File: TestCOSStream.java
View license
/**
     * 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);
}

55. TestCOSStream#testCompressedStream2Decode()

Project: pdfbox
Source File: TestCOSStream.java
View license
/**
     * 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);
}

56. TestPDFunctionType4#createFunction()

Project: pdfbox
Source File: TestPDFunctionType4.java
View license
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);
}

57. SocketBench#benchmarkLargeRead()

Project: pluotsorbet
Source File: SocketBench.java
View license
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();
}

58. Response#sendFile()

Project: LGame
Source File: Response.java
View license
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();
}

59. DatabaseHelper#copyDataBase()

Project: mHealth-App
Source File: DatabaseHelper.java
View license
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();
}

60. DefaultX11ForwardSupport#messageReceived()

View license
@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();
}

61. DeepStubbingTest#withArguments()

Project: mockito
Source File: DeepStubbingTest.java
View license
/**
     * 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());
}

62. BinarySafeStreamTest#test1()

View license
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());
}

63. PipeTest#testQuickBurstWrite()

Project: hudson-2.x
Source File: PipeTest.java
View license
/**
     * 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());
}

64. TestGroupedSplits#writeFile()

View license
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();
}

65. OldBufferedInputStreamTest#setUp()

View license
@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);
}

66. URLConnectionTest#testResponseRedirectedWithPost()

Project: j2objc
Source File: URLConnectionTest.java
View license
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());
}

67. URLConnectionTest#testFlushAfterStreamTransmitted()

Project: j2objc
Source File: URLConnectionTest.java
View license
// 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) {
    }
}

68. URLConnectionTest#testClientSendsContentLength()

Project: j2objc
Source File: URLConnectionTest.java
View license
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");
}

69. ParserTest#testExternalEntities()

Project: jackrabbit
Source File: ParserTest.java
View license
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) {
    }
}

70. FileBlobStore#storeBlock()

Project: jackrabbit-oak
Source File: FileBlobStore.java
View license
@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);
}

71. ByteSourceTest#createTempFile()

Project: sanselan
Source File: ByteSourceTest.java
View license
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;
}

72. Webserver#process()

Project: scouter
Source File: Webserver.java
View license
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();
}

73. InBandBytestreamSessionMessageTest#shouldSendThreeDataPackets1()

View license
/**
     * 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();
}

74. InBandBytestreamSessionTest#shouldSendThreeDataPackets1()

View license
/**
     * 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();
}

75. AbstractSnappyStreamTest#testExtraFlushes()

View license
@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);
}

76. TestLeakFS#testLeakFileChannel()

Project: lucene-solr
Source File: TestLeakFS.java
View license
/** 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();
}

77. UIInitHandler#commitJsonResponse()

Project: vaadin
Source File: UIInitHandler.java
View license
/**
     * 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;
}

78. SassLinker#writeFromInputStream()

Project: vaadin
Source File: SassLinker.java
View license
/**
     * 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();
}

79. CachingPortletOutputHandlerTest#testTooMuchStreamContent()

View license
@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);
}

80. ReceiverTestCase#testAsyncReceiveWholeBytesFailed()

Project: undertow
Source File: ReceiverTestCase.java
View license
@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);
}

81. TestCsv#testPreserveWhitespace()

Project: ThriftyPaxos
Source File: TestCsv.java
View license
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();
}

82. TestCsv#testCaseSensitiveColumnNames()

Project: ThriftyPaxos
Source File: TestCsv.java
View license
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();
}

83. TestGroupedSplits#writeFile()

Project: tez
Source File: TestGroupedSplits.java
View license
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();
}

84. ClassCreationHelper#writeFile()

Project: tapestry-5
Source File: ClassCreationHelper.java
View license
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();
}

85. TestWindowsFS#testRenameOpenFile()

Project: lucene-solr
Source File: TestWindowsFS.java
View license
/** 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();
}

86. TestWindowsFS#testDeleteIfExistsOpenFile()

Project: lucene-solr
Source File: TestWindowsFS.java
View license
/** 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();
}

87. TestWindowsFS#testDeleteOpenFile()

Project: lucene-solr
Source File: TestWindowsFS.java
View license
/** 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();
}

88. TestLeakFS#testLeakByteChannel()

Project: lucene-solr
Source File: TestLeakFS.java
View license
/** 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();
}

89. TestLeakFS#testLeakAsyncFileChannel()

Project: lucene-solr
Source File: TestLeakFS.java
View license
/** 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();
}

90. VfsStreamsTests#writeRead5()

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

91. HsqlProperties#save()

Project: voltdb
Source File: HsqlProperties.java
View license
/**
     *  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;
}

92. NettyWebServerTest#stopsServerCleanlyAlsoWhenClientsAreConnected()

Project: webbit
Source File: NettyWebServerTest.java
View license
@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));
}

93. VfsStreamsTests#writeRead()

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

94. VfsStreamsTests#writeRead2()

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

95. VfsStreamsTests#writeRead3()

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

96. VfsStreamsTests#writeRead4()

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

97. ZabbixRequestHandler#send()

Project: zorka
Source File: ZabbixRequestHandler.java
View license
/**
     * 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();
}

98. VFSNotebookRepo#save()

Project: zeppelin
Source File: VFSNotebookRepo.java
View license
@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));
}

99. VfsStreamsTests#testWriteReadWithStrategy()

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

100. TestLeakFS#testLeakInputStream()

Project: lucene-solr
Source File: TestLeakFS.java
View license
/** 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();
}