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: 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;
}

4. 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;
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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. PerformanceComparison#testRawPerformance()

View license
[email protected]
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. 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("###############################################");
}

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

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

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

40. 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;
}

41. 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) {
    }
}

42. 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) {
    }
}

43. 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;
}

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

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

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

48. HdfsBlobStoreImplTest#testGetFileLength()

View license
@Test
public void testGetFileLength() throws IOException {
    FileSystem fs = dfscluster.getFileSystem();
    Map conf = new HashMap();
    String validKey = "validkeyBasic";
    String testString = "testingblob";
    TestHdfsBlobStoreImpl hbs = new TestHdfsBlobStoreImpl(blobDir, conf, hadoopConf);
    BlobStoreFile pfile = hbs.write(validKey, false);
    // Adding metadata to avoid null pointer exception
    SettableBlobMeta meta = new SettableBlobMeta();
    meta.set_replication_factor(1);
    pfile.setMetadata(meta);
    OutputStream ios = pfile.getOutputStream();
    ios.write(testString.getBytes(Charset.forName("UTF-8")));
    ios.close();
    assertEquals(testString.getBytes(Charset.forName("UTF-8")).length, pfile.getFileLength());
}

49. Base#readIntent()

Project: APStatus
Source File: Base.java
View license
public static Intent readIntent(Socket socket) throws Exception {
    InputStream is = socket.getInputStream();
    ByteBuffer buffer = ByteBuffer.allocate(12);
    if (is.read(buffer.array()) != 12)
        throw new IOException("Corrupted header");
    long magic = buffer.getLong();
    if (magic == MAGIC_END)
        return null;
    if (magic != MAGIC_RAW)
        throw new IOException("Bad magic " + magic);
    int size = buffer.getInt();
    if (size < 0 || size > MAX_DATA_SIZE)
        throw new IOException("Bad data size " + size);
    byte[] data = new byte[size];
    size = is.read(data);
    if (size == -1)
        throw new IOException("Unexpected EOF");
    if (size != data.length)
        throw new IOException("Read " + size + " bytes, " + data.length + " expected");
    Intent intent = getIntent(data);
    OutputStream os = socket.getOutputStream();
    os.write(ACK);
    os.flush();
    return intent;
}

50. XMLPrettyPrinterTest#testPrettifyStreamClose()

View license
/**
     * This method checks whether the file can be deleted after using PrettyPrinter. 
     * It normally works fine in linux, but if the pretty printer doesn't close the streams properly
     * it will fail in windows. 
     * @throws IOException
     */
public void testPrettifyStreamClose() throws IOException {
    String filePath = new File(".").getAbsolutePath() + File.separator + "target" + File.separator + "test.xml";
    //Create new file
    File outputFile = new File(filePath);
    outputFile.createNewFile();
    OutputStream outStream = new FileOutputStream(outputFile);
    outStream.write("<a><b>test</b></a>".getBytes());
    outStream.close();
    //Prettyfy the output
    XMLPrettyPrinter.prettify(outputFile);
    //Delete file
    assertTrue(outputFile.delete());
}

51. ProtectedPKIMessage#verifySignature()

Project: bc-java
Source File: ProtectedPKIMessage.java
View license
private boolean verifySignature(byte[] signature, ContentVerifier verifier) throws IOException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(pkiMessage.getHeader());
    v.add(pkiMessage.getBody());
    OutputStream sOut = verifier.getOutputStream();
    sOut.write(new DERSequence(v).getEncoded(ASN1Encoding.DER));
    sOut.close();
    return verifier.verify(signature);
}

52. ProtectedPKIMessageBuilder#calculateSignature()

View license
private byte[] calculateSignature(ContentSigner signer, PKIHeader header, PKIBody body) throws IOException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(header);
    v.add(body);
    OutputStream sOut = signer.getOutputStream();
    sOut.write(new DERSequence(v).getEncoded(ASN1Encoding.DER));
    sOut.close();
    return signer.getSignature();
}

53. ProtectedPKIMessageBuilder#calculateMac()

View license
private byte[] calculateMac(MacCalculator macCalculator, PKIHeader header, PKIBody body) throws IOException {
    ASN1EncodableVector v = new ASN1EncodableVector();
    v.add(header);
    v.add(body);
    OutputStream sOut = macCalculator.getOutputStream();
    sOut.write(new DERSequence(v).getEncoded(ASN1Encoding.DER));
    sOut.close();
    return macCalculator.getMac();
}

54. NewCompressedDataStreamTest#testEach()

View license
public void testEach() throws Exception {
    byte[] testData = "Hello world!".getBytes();
    CMSCompressedDataStreamGenerator gen = new CMSCompressedDataStreamGenerator();
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    OutputStream cOut = gen.open(bOut, new ZlibCompressor());
    cOut.write(testData);
    cOut.close();
    CMSCompressedDataParser ed = new CMSCompressedDataParser(bOut.toByteArray());
    assertEquals(true, Arrays.equals(testData, CMSTestUtil.streamToByteArray(ed.getContent(new ZlibExpanderProvider()).getContentStream())));
}

55. JavaInMemoryFileManagerTest#testWriteContent()

View license
@Test
public void testWriteContent() throws Exception {
    JavaFileObject fileObject = inMemoryFileManager.getJavaFileForOutput(locationOf("src"), "JavaFileParser", JavaFileObject.Kind.CLASS, null);
    OutputStream stream = fileObject.openOutputStream();
    stream.write("Hello World!".getBytes());
    stream.close();
    List<String> entries = outputStream.getEntriesContent();
    assertEquals(1, entries.size());
    assertEquals("Hello World!", entries.get(0));
}

56. JavaInMemoryFileObjectTest#testJavaFileContent()

View license
@Test
public void testJavaFileContent() throws Exception {
    JavaInMemoryFileObject inMemoryFileObject = new JavaInMemoryFileObject("com/facebook/buck/java/JavaInMemoryFileObjectTest.class", JavaFileObject.Kind.CLASS, outputStream, semaphore);
    OutputStream out = inMemoryFileObject.openOutputStream();
    out.write("content".getBytes());
    out.close();
    assertEquals(1, outputStream.getZipEntries().size());
    assertEquals(1, outputStream.getEntriesContent().size());
    assertEquals("content", outputStream.getEntriesContent().get(0));
}

57. CamelTransportTestSupport#sendoutMessage()

View license
protected void sendoutMessage(Conduit conduit, Message message, Boolean isOneWay, String content) throws IOException {
    Exchange cxfExchange = message.getExchange();
    if (cxfExchange == null) {
        cxfExchange = new ExchangeImpl();
        cxfExchange.setOneWay(isOneWay);
        message.setExchange(cxfExchange);
        cxfExchange.setInMessage(message);
    }
    try {
        conduit.prepare(message);
    } catch (IOException ex) {
        assertFalse("CamelConduit can't perpare to send out message", false);
        ex.printStackTrace();
    }
    OutputStream os = message.getContent(OutputStream.class);
    assertTrue("The OutputStream should not be null ", os != null);
    os.write(content.getBytes());
    os.close();
}

58. DocTypeSettingByteChannelTest#removeXmlDeclarationTest()

View license
/**
     * XML declaration allowed only at the start of the document
     */
@Test
public void removeXmlDeclarationTest() throws Exception {
    final String someHtml = "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>" + "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" + "<body>\n" + "hello" + "</body>\n" + "</html>";
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final OutputStream channel = createDocTypeFilteringByteChannel(baos);
    channel.write(someHtml.substring(0, 20).getBytes(UTF8));
    channel.write(someHtml.substring(20).getBytes(UTF8));
    final String resultString = new String(baos.toByteArray(), UTF8);
    //Assert.assertEquals(someHtml.length(), bytesWritten);
    Assert.assertTrue(resultString.contains("<!DOCTYPE"));
    /* The test fails iff the ?xml is at another position than 0, not
         * if its removed*/
    if (resultString.contains("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>")) {
        Assert.assertTrue(resultString.startsWith("<?xml"));
    }
}

59. AbstractWritableContentStoreTest#testReadAndWriteStreamByPush()

View license
@Test
public void testReadAndWriteStreamByPush() throws Exception {
    ContentWriter writer = getWriter();
    String content = "Some Random Content";
    // get the content output stream
    OutputStream os = writer.getContentOutputStream();
    os.write(content.getBytes());
    assertFalse("Stream has not been closed", writer.isClosed());
    // close the stream and check again
    os.close();
    assertTrue("Stream close not detected", writer.isClosed());
    // pull the content from a stream
    ContentReader reader = writer.getReader();
    InputStream is = reader.getContentInputStream();
    byte[] buffer = new byte[100];
    int count = is.read(buffer);
    assertEquals("No content read", content.length(), count);
    is.close();
    String check = new String(buffer, 0, count);
    assertEquals("Write out of and read into files failed", content, check);
}

60. FileFolderServiceImplTest#testAlf6560MimetypeSetting()

View license
public void testAlf6560MimetypeSetting() throws Exception {
    FileInfo fileInfo = fileFolderService.create(workingRootNodeRef, "Something.html", ContentModel.TYPE_CONTENT);
    NodeRef fileNodeRef = fileInfo.getNodeRef();
    // Write the content but without setting the mimetype
    ContentWriter writer = fileFolderService.getWriter(fileNodeRef);
    writer.putContent("CONTENT");
    ContentReader reader = fileFolderService.getReader(fileNodeRef);
    assertEquals("Mimetype was not automatically set", MimetypeMap.MIMETYPE_HTML, reader.getMimetype());
    // Now ask for encoding too
    writer = fileFolderService.getWriter(fileNodeRef);
    writer.guessEncoding();
    OutputStream out = writer.getContentOutputStream();
    out.write("<html><body>hallå världen</body></html>".getBytes("UnicodeBig"));
    out.close();
    reader = fileFolderService.getReader(fileNodeRef);
    assertEquals("Mimetype was not automatically set", MimetypeMap.MIMETYPE_HTML, reader.getMimetype());
    assertEquals("Encoding was not automatically set", "UTF-16BE", reader.getEncoding());
}

61. WorkflowDefinitionImageServlet#doGet()

View license
/* (non-Javadoc)
     * @see javax.servlet.http.HttpServlet#doGet(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // retrieve workflow definition id
    String uri = request.getRequestURI();
    uri = uri.substring(request.getContextPath().length());
    StringTokenizer t = new StringTokenizer(uri, "/");
    if (t.countTokens() != 2) {
        throw new WorkflowException("Workflow Definition Image servlet does not contain workflow definition id : " + uri);
    }
    // skip servlet name
    t.nextToken();
    String workflowDefinitionId = t.nextToken();
    // retrieve workflow definition image
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
    WorkflowService workflowService = (WorkflowService) wc.getBean(ServiceRegistry.WORKFLOW_SERVICE.getLocalName());
    byte[] definitionImage = workflowService.getDefinitionImage(workflowDefinitionId);
    // stream out through response
    OutputStream out = response.getOutputStream();
    out.write(definitionImage);
    out.flush();
}

62. NativeGCMCipherInputStreamTest#setUp()

View license
protected void setUp() throws Exception {
    super.setUp();
    mNativeCryptoLibrary = new SystemNativeCryptoLibrary();
    KeyChain keyChain = new FakeKeyChain();
    mCrypto = new Crypto(keyChain, mNativeCryptoLibrary);
    mIV = keyChain.getNewIV();
    mKey = keyChain.getCipherKey();
    // Encrypt some data before each test.
    mData = new byte[CryptoTestUtils.NUM_DATA_BYTES];
    Random random = new Random();
    random.nextBytes(mData);
    ByteArrayOutputStream cipherOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = mCrypto.getCipherOutputStream(cipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(mData);
    outputStream.close();
    mCipheredData = cipherOutputStream.toByteArray();
    mCipherInputStream = new ByteArrayInputStream(mCipheredData);
}

63. NativeGCMCipherOutputStreamTest#testWriteData()

View license
public void testWriteData() throws Exception {
    OutputStream outputStream = mCrypto.getCipherOutputStream(mCipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(mData);
    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));
}

64. NativeGCMCipherOutputStreamTest#testEncryptedDataIsExpected()

View license
public void testEncryptedDataIsExpected() throws Exception {
    String dataToEncrypt = "data to encrypt";
    String expectedEncryptedString = "69VhniqXP+xA0CcKJFx5";
    OutputStream outputStream = mCrypto.getCipherOutputStream(mCipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(dataToEncrypt.getBytes("UTF-8"));
    outputStream.close();
    byte[] encryptedData = CryptoSerializerHelper.cipherText(mCipherOutputStream.toByteArray());
    String encryptedString = Base64.encodeToString(encryptedData, Base64.DEFAULT).trim();
    assertEquals(CryptoTestUtils.ENCRYPTED_DATA_IS_DIFFERENT, expectedEncryptedString, encryptedString);
}

65. NativeMacLayeredInputStreamTest#setUp()

View license
public void setUp() throws Exception {
    mKeyChain = new FakeKeyChain();
    mCrypto = AndroidConceal.get().createCrypto128Bits(mKeyChain);
    mData = new byte[CryptoTestUtils.NUM_DATA_BYTES];
    Random random = new Random();
    random.nextBytes(mData);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    mEntity = new Entity(CryptoTestUtils.ENTITY_NAME);
    OutputStream outputStream = mCrypto.getMacOutputStream(bout, mEntity);
    outputStream.write(mData);
    outputStream.close();
    mDataWithMac = bout.toByteArray();
}

66. NativeMacLayeredOutputStreamTest#testMatchesWithJavaMac()

View license
public void testMatchesWithJavaMac() throws Exception {
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(new SecretKeySpec(mKey, "HmacSHA1"));
    byte[] aadData = CryptoSerializerHelper.computeBytesToAuthenticate(mEntity.getBytes(), VersionCodes.MAC_SERIALIZATION_VERSION, VersionCodes.MAC_ID);
    mac.update(aadData);
    byte[] javaMac = mac.doFinal(mData);
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    OutputStream macStream = mCrypto.getMacOutputStream(bout, mEntity);
    macStream.write(mData);
    macStream.close();
    byte[] dataWithMac = bout.toByteArray();
    int macOffset = dataWithMac.length - javaMac.length;
    Preconditions.checkState(macOffset > 0);
    byte[] originalData = CryptoSerializerHelper.getOriginalDataFromMacData(dataWithMac, javaMac.length);
    byte[] nativeMac = CryptoSerializerHelper.getMacTag(dataWithMac, javaMac.length);
    assertTrue(Arrays.equals(mData, originalData));
    assertTrue(Arrays.equals(javaMac, nativeMac));
}

67. SimpleDecryptTest#setUp()

Project: conceal
Source File: SimpleDecryptTest.java
View license
protected void setUp() throws Exception {
    super.setUp();
    KeyChain keyChain = new FakeKeyChain();
    mCrypto = AndroidConceal.get().createCrypto128Bits(keyChain);
    mIV = keyChain.getNewIV();
    mKey = keyChain.getCipherKey();
    // Encrypt some data before each test.
    mData = new byte[CryptoTestUtils.NUM_DATA_BYTES];
    ByteArrayOutputStream cipherOutputStream = new ByteArrayOutputStream();
    OutputStream outputStream = mCrypto.getCipherOutputStream(cipherOutputStream, new Entity(CryptoTestUtils.ENTITY_NAME));
    outputStream.write(mData);
    outputStream.close();
    mCipheredData = cipherOutputStream.toByteArray();
}

68. SocksSocketFactory#createSocksConnection()

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

69. CameraLauncher#writeUncompressedImage()

View license
/**
     * In the special case where the default width, height and quality are unchanged
     * we just write the file out to disk saving the expensive Bitmap.compress function.
     *
     * @param uri
     * @throws FileNotFoundException
     * @throws IOException
     */
private void writeUncompressedImage(Uri uri) throws FileNotFoundException, IOException {
    FileInputStream fis = new FileInputStream(FileHelper.stripFileProtocol(imageUri.toString()));
    OutputStream os = this.cordova.getActivity().getContentResolver().openOutputStream(uri);
    byte[] buffer = new byte[4096];
    int len;
    while ((len = fis.read(buffer)) != -1) {
        os.write(buffer, 0, len);
    }
    os.flush();
    os.close();
    fis.close();
}

70. TestBootstrapMain#testGetWhiteListNoValues()

View license
@Test
public void testGetWhiteListNoValues() throws Exception {
    File dir = new File("target", UUID.randomUUID().toString()).getAbsoluteFile();
    Assert.assertTrue(dir.mkdirs());
    Properties props = new Properties();
    props.setProperty(BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY, "");
    try (OutputStream os = new FileOutputStream(new File(dir, BootstrapMain.WHITE_LIST_FILE))) {
        props.store(os, "");
    }
    Assert.assertTrue(BootstrapMain.getWhiteList(dir.getAbsolutePath(), BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY).isEmpty());
    props.setProperty(BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY, " ");
    try (OutputStream os = new FileOutputStream(new File(dir, BootstrapMain.WHITE_LIST_FILE))) {
        props.store(os, "");
    }
    Assert.assertTrue(BootstrapMain.getWhiteList(dir.getAbsolutePath(), BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY).isEmpty());
    props.setProperty(BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY, ",,");
    try (OutputStream os = new FileOutputStream(new File(dir, BootstrapMain.WHITE_LIST_FILE))) {
        props.store(os, "");
    }
    Assert.assertTrue(BootstrapMain.getWhiteList(dir.getAbsolutePath(), BootstrapMain.SYSTEM_LIBS_WHITE_LIST_KEY).isEmpty());
}

71. TestRuntimeEL#testHostname()

Project: datacollector
Source File: TestRuntimeEL.java
View license
@Test
public void testHostname() throws IOException {
    // No configuration, fetch hostname dynamically
    OutputStream sdcProps = new FileOutputStream(new File(runtimeInfo.getConfigDir(), "sdc.properties"));
    sdcProps.close();
    RuntimeEL.loadRuntimeConfiguration(runtimeInfo);
    Assert.assertEquals(InetAddress.getLocalHost().getCanonicalHostName(), RuntimeEL.hostname());
    // Hostname in configuration file
    sdcProps = new FileOutputStream(new File(runtimeInfo.getConfigDir(), "sdc.properties"));
    IOUtils.write(WebServerTask.HTTP_BIND_HOST + "=sdc.jarcec.net", sdcProps);
    sdcProps.close();
    RuntimeEL.loadRuntimeConfiguration(runtimeInfo);
    Assert.assertEquals("sdc.jarcec.net", RuntimeEL.hostname());
}

72. DatabaseHelperDelegate#writeDB()

Project: DBFlow
Source File: DatabaseHelperDelegate.java
View license
/**
     * Writes the inputstream of the existing db to the file specified.
     *
     * @param dbPath     The file to write to.
     * @param existingDB The existing databasefile's input stream¬
     * @throws IOException
     */
private void writeDB(File dbPath, InputStream existingDB) throws IOException {
    final OutputStream output = new FileOutputStream(dbPath);
    byte[] buffer = new byte[1024];
    int length;
    while ((length = existingDB.read(buffer)) > 0) {
        output.write(buffer, 0, length);
    }
    output.flush();
    output.close();
    existingDB.close();
}

73. LuceneSupport#writeIndexProperties()

Project: derby
Source File: LuceneSupport.java
View license
/** Write the index properties file */
private static void writeIndexProperties(final StorageFile file, Properties properties) throws IOException {
    if (file == null || properties == null) {
        return;
    }
    OutputStream os;
    try {
        os = AccessController.doPrivileged(new PrivilegedExceptionAction<OutputStream>() {

            public OutputStream run() throws IOException {
                return file.getOutputStream();
            }
        });
    } catch (PrivilegedActionException pae) {
        throw (IOException) pae.getCause();
    }
    properties.store(os, null);
    os.flush();
    os.close();
}

74. PreparedStatementTest#testSetBlobLengthless()

Project: derby
Source File: PreparedStatementTest.java
View license
/**
     * Insert <code>Blob</code> without specifying length and read it back
     * for verification.
     */
public void testSetBlobLengthless() throws IOException, SQLException {
    // Life span of Blob objects are the transaction.  Need autocommit off
    // to have Blob objects survive execution of next statement.
    getConnection().setAutoCommit(false);
    // Create Blob to be inserted
    Blob insertBlob = getConnection().createBlob();
    OutputStream os = insertBlob.setBinaryStream(1);
    os.write(BYTES);
    int secondKey = requestKey();
    psInsertBlob.setInt(1, secondKey);
    psInsertBlob.setBlob(2, insertBlob);
    psInsertBlob.execute();
    os.close();
    psInsertBlob.close();
    // Read back test data from database.
    psFetchBlob.setInt(1, secondKey);
    ResultSet rs = psFetchBlob.executeQuery();
    assertTrue("No results retrieved", rs.next());
    Blob blobRetrieved = rs.getBlob(1);
    // Verify test data.
    assertEquals(insertBlob, blobRetrieved);
}

75. SimplePostConverter#sendRequest()

Project: enroscar
Source File: SimplePostConverter.java
View license
@Override
public void sendRequest(final URLConnection connection) throws IOException {
    Uri.Builder builder = Uri.parse("http://any.com").buildUpon();
    for (final Parameter p : getRequestDescription().getSimpleParameters().getChildren()) {
        if (p instanceof ParameterValue) {
            builder.appendQueryParameter(p.getName(), ((ParameterValue) p).getValue());
        }
    }
    @SuppressWarnings("ConstantConditions") String query = builder.build().getEncodedQuery();
    if (query == null) {
        query = "";
    }
    final byte[] content = query.getBytes(getRequestDescription().getEncoding().name());
    final OutputStream stream = connection.getOutputStream();
    stream.write(content);
    stream.flush();
    if (Utils.isDebugRest(getContext())) {
        Log.d(TAG, "(" + getRequestDescription().getId() + ")" + ": " + query);
    }
}

76. SplitFileInserterStorage#encodeCrossSegmentSettings()

Project: fred
Source File: SplitFileInserterStorage.java
View license
/**
     * This one could actually be rather large, since it includes the listing of
     * which blocks go in which cross-segments ...
     */
private Bucket encodeCrossSegmentSettings(BucketFactory bf) throws IOException {
    if (crossSegments == null)
        return new NullBucket();
    Bucket bucket = bf.makeBucket(-1);
    OutputStream os = bucket.getOutputStream();
    OutputStream cos = checker.checksumWriterWithLength(os, new ArrayBucketFactory());
    DataOutputStream dos = new DataOutputStream(cos);
    for (SplitFileInserterCrossSegmentStorage segment : crossSegments) {
        segment.writeFixedSettings(dos);
    }
    dos.close();
    os.close();
    return bucket;
}

77. TempBucketFactoryRAFBase#testBucketToRAFCallTwiceArray()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFCallTwiceArray() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf.close();
    raf.free();
}

78. TempBucketFactoryRAFBase#testBucketToRAFCallTwiceFile()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFCallTwiceFile() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    assertTrue(bucket.migrateToDisk());
    TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
    assertTrue(raf != null);
    raf.close();
    raf.free();
}

79. TempBucketFactoryRAFBase#testBucketToRAFFreeBucketWhileArray()

Project: fred
Source File: TempBucketFactoryRAFBase.java
View license
public void testBucketToRAFFreeBucketWhileArray() throws IOException {
    int len = 4095;
    Random r = new Random(21162101);
    TempBucket bucket = (TempBucket) factory.makeBucket(1024);
    byte[] buf = new byte[len];
    r.nextBytes(buf);
    OutputStream os = bucket.getOutputStream();
    os.write(buf.clone());
    os.close();
    assertTrue(bucket.isRAMBucket());
    assertEquals(len, bucket.size());
    bucket.getInputStream().close();
    bucket.free();
    try {
        TempRandomAccessBuffer raf = (TempRandomAccessBuffer) bucket.toRandomAccessBuffer();
        fail();
    } catch (IOException e) {
    }
}

80. DataTransferTimeoutTest#testTimeoutForStore()

View license
public void testTimeoutForStore() throws Exception {
    OutputStream os = client.storeFileStream(TEST_FILENAME);
    os.write(1);
    // make sure this take longer than the timeout time, but not timeout between writes...
    for (int i = 0; i < 100; i++) {
        Thread.sleep(20);
        os.write(1);
        os.flush();
    }
    os.close();
    client.completePendingCommand();
    // we should not have been disconnected
    client.noop();
}

81. HsqlProperties#save()

Project: h-store
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;
}

82. TestSlowWritePacketLogging#testSlowWritePacketLogging()

View license
@Test
public /**
   * This test just triggers the codepath and doesn't do any other verification.
   */
void testSlowWritePacketLogging() throws Exception {
    DistributedFileSystem fs = (DistributedFileSystem) cluster.getFileSystem();
    WriteOptions options = new WriteOptions();
    options.setLogSlowWriteProfileDataThreshold(1);
    DFSWriteProfilingData data = new DFSWriteProfilingData();
    DFSClient.setProfileDataForNextOutputStream(data);
    OutputStream out = fs.create(new Path("/test"), null, true, 4096, (short) 3, 1024, 512, null, null, options);
    byte[] buffer = new byte[1024 * 1024];
    out.write(buffer);
    out.close();
}

83. TestTextInputFormat#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();
}

84. TestMRKeyValueTextInputFormat#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();
}

85. PiplelineTest#main()

Project: http-kit
Source File: PiplelineTest.java
View license
public static void main(String[] args) throws UnknownHostException, IOException {
    Socket socket = new Socket("127.0.0.1", 9091);
    InputStream is = socket.getInputStream();
    OutputStream os = socket.getOutputStream();
    String req = "GET / HTTP/1.0\r\n\r\n";
    os.write((req + req + req).getBytes());
    os.flush();
    byte buffer[] = new byte[8096000];
    int read = is.read(buffer);
    System.out.println(new String(buffer, 0, read));
}

86. SpecialHttpClient#get2()

Project: http-kit
Source File: SpecialHttpClient.java
View license
// request + request sent to server, wait for 2 server responses
public static String get2(String url) throws URISyntaxException, IOException {
    URI uri = new URI(url);
    InetSocketAddress addr = HttpUtils.getServerAddr(uri);
    Socket s = new Socket();
    s.connect(addr);
    OutputStream os = s.getOutputStream();
    String request = "GET " + HttpUtils.getPath(uri) + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
    os.write((request + request).getBytes());
    os.flush();
    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8096];
    int read = is.read(buffer);
    s.close();
    return new String(buffer, 0, read);
}

87. SpecialHttpClient#http10()

Project: http-kit
Source File: SpecialHttpClient.java
View license
public static String http10(String url) throws Exception {
    URI uri = new URI(url);
    InetSocketAddress addr = HttpUtils.getServerAddr(uri);
    Socket s = new Socket();
    s.connect(addr);
    OutputStream os = s.getOutputStream();
    String request = "GET " + HttpUtils.getPath(uri) + " HTTP/1.0\r\nHost: localhost\r\nConnection: keep-alive\r\n\r\n";
    os.write((request + request).getBytes());
    os.flush();
    InputStream is = s.getInputStream();
    byte[] buffer = new byte[8096];
    int read = is.read(buffer);
    s.close();
    return new String(buffer, 0, read);
}

88. TestContentLengthOutputStream#testClose()

View license
public void testClose() throws Exception {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    SessionOutputBufferMockup datatransmitter = new SessionOutputBufferMockup(buffer);
    OutputStream out = new ContentLengthOutputStream(datatransmitter, 15L);
    out.close();
    out.close();
    byte[] tmp = new byte[10];
    try {
        out.write(tmp);
        fail("IOException should have been thrown");
    } catch (IOException ex) {
    }
    try {
        out.write(1);
        fail("IOException should have been thrown");
    } catch (IOException ex) {
    }
}

89. TestIdentityOutputStream#testClose()

View license
public void testClose() throws Exception {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    SessionOutputBufferMockup datatransmitter = new SessionOutputBufferMockup(buffer);
    OutputStream out = new IdentityOutputStream(datatransmitter);
    out.close();
    out.close();
    byte[] tmp = new byte[10];
    try {
        out.write(tmp);
        fail("IOException should have been thrown");
    } catch (IOException ex) {
    }
    try {
        out.write(1);
        fail("IOException should have been thrown");
    } catch (IOException ex) {
    }
}

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

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

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

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

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

95. 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) {
    }
}

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

97. 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) {
    }
}

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

99. Rcon#write()

Project: Jcon
Source File: Rcon.java
View license
/**
	 * Internal write method. Used to dump all the payload and other necessary information into the [email protected] OutputStream} that the socket gives us.
	 *
	 * @param type    - The type of request.
	 * @param payload - The data we're sending.
	 * @return - This object, purely for chaining.
	 * @throws IOException
	 */
private Rcon write(int type, byte[] payload) throws IOException {
    int body = payload.length + 10;
    ByteBuffer buffer = ByteBuffer.allocate(body + 4).order(ByteOrder.LITTLE_ENDIAN);
    buffer.putInt(body);
    buffer.putInt(requestId);
    buffer.putInt(type);
    buffer.put(payload);
    buffer.put(TERMINATOR);
    OutputStream out = socket.getOutputStream();
    out.write(buffer.array());
    out.flush();
    return this;
}

100. VtorJsonResult#render()

Project: jodd
Source File: VtorJsonResult.java
View license
public void render(ActionRequest actionRequest, String resultValue) throws Exception {
    HttpServletRequest request = actionRequest.getHttpServletRequest();
    HttpServletResponse response = actionRequest.getHttpServletResponse();
    Object action = actionRequest.getAction();
    AppAction appAction = (AppAction) action;
    List<Violation> list = appAction.violations();
    String result = VtorUtil.createViolationsJsonString(request, list);
    if (jsonResponseContentType != null) {
        response.setContentType(jsonResponseContentType);
    }
    char[] chars = result.toCharArray();
    byte[] data = CharUtil.toByteArray(chars, madvocConfig.getEncoding());
    OutputStream os = response.getOutputStream();
    os.write(data);
    os.flush();
}