java.io.ByteArrayInputStream

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

1. Account#toObject()

Project: scouter
File: Account.java
public void toObject(byte[] bytes) throws IOException {
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    int len = in.read();
    byte[] idBytes = new byte[len];
    in.read(idBytes);
    this.id = new String(idBytes);
    len = in.read();
    byte[] passBytes = new byte[len];
    in.read(passBytes);
    this.password = new String(passBytes);
    len = in.read();
    byte[] emailBytes = new byte[len];
    in.read(emailBytes);
    this.email = new String(emailBytes);
    len = in.read();
    byte[] groupBytes = new byte[len];
    in.read(groupBytes);
    this.group = new String(groupBytes);
    in.close();
}

2. PreparedStatementTest#testSetAsciiStream()

Project: pgjdbc-ng
File: PreparedStatementTest.java
@Test
public void testSetAsciiStream() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, "ASCII"));
    pw.println("Hello");
    pw.flush();
    ByteArrayInputStream bais;
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 0);
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 6);
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 100);
}

3. PreparedStatementTest#testSetBinaryStream()

Project: pgjdbc-ng
File: PreparedStatementTest.java
@Test
public void testSetBinaryStream() throws SQLException {
    ByteArrayInputStream bais;
    byte[] buf = new byte[10];
    for (int i = 0; i < buf.length; i++) {
        buf[i] = (byte) i;
    }
    bais = null;
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(new byte[0]);
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(buf);
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(buf);
    doSetBinaryStream(bais, 10);
}

4. PreparedStatementTest#testSetAsciiStream()

Project: pgjdbc
File: PreparedStatementTest.java
public void testSetAsciiStream() throws Exception {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, "ASCII"));
    pw.println("Hello");
    pw.flush();
    ByteArrayInputStream bais;
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 0);
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 6);
    bais = new ByteArrayInputStream(baos.toByteArray());
    doSetAsciiStream(bais, 100);
}

5. PreparedStatementTest#testSetBinaryStream()

Project: pgjdbc
File: PreparedStatementTest.java
public void testSetBinaryStream() throws SQLException {
    ByteArrayInputStream bais;
    byte buf[] = new byte[10];
    for (int i = 0; i < buf.length; i++) {
        buf[i] = (byte) i;
    }
    bais = null;
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(new byte[0]);
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(buf);
    doSetBinaryStream(bais, 0);
    bais = new ByteArrayInputStream(buf);
    doSetBinaryStream(bais, 10);
}

6. ECIESTest#decrypt()

Project: ethereumj
File: ECIESTest.java
public static byte[] decrypt(BigInteger prv, byte[] cipher) throws InvalidCipherTextException, IOException {
    ByteArrayInputStream is = new ByteArrayInputStream(cipher);
    byte[] ephemBytes = new byte[2 * ((curve.getCurve().getFieldSize() + 7) / 8) + 1];
    is.read(ephemBytes);
    ECPoint ephem = curve.getCurve().decodePoint(ephemBytes);
    byte[] IV = new byte[KEY_SIZE / 8];
    is.read(IV);
    byte[] cipherBody = new byte[is.available()];
    is.read(cipherBody);
    EthereumIESEngine iesEngine = makeIESEngine(false, ephem, prv, IV);
    byte[] message = iesEngine.processBlock(cipherBody, 0, cipherBody.length);
    return message;
}

7. ECIESCoder#decrypt()

Project: ethereumj
File: ECIESCoder.java
public static byte[] decrypt(BigInteger privKey, byte[] cipher, byte[] macData) throws IOException, InvalidCipherTextException {
    byte[] plaintext;
    ByteArrayInputStream is = new ByteArrayInputStream(cipher);
    byte[] ephemBytes = new byte[2 * ((CURVE.getCurve().getFieldSize() + 7) / 8) + 1];
    is.read(ephemBytes);
    ECPoint ephem = CURVE.getCurve().decodePoint(ephemBytes);
    byte[] IV = new byte[KEY_SIZE / 8];
    is.read(IV);
    byte[] cipherBody = new byte[is.available()];
    is.read(cipherBody);
    plaintext = decrypt(ephem, privKey, IV, cipherBody, macData);
    return plaintext;
}

8. TestR5Recognition#testAcceptOnCapabilityChildElementNames()

Project: bnd
File: TestR5Recognition.java
public static void testAcceptOnCapabilityChildElementNames() throws Exception {
    String testdata;
    ByteArrayInputStream stream;
    CheckResult result;
    // Must be R5
    testdata = "<repository><resource><capability><attribute/>...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new R5RepoContentProvider().checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
    // Must be R5
    testdata = "<repository><resource><capability><directive/>...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new R5RepoContentProvider().checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
    // Arbitrary elements under repo, resource and capability are allowed
    testdata = "<repository><XXX/><resource><YYY/><capability><ZZZ/><attribute/>...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new R5RepoContentProvider().checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
}

9. TestR5Recognition#testUndecidable()

Project: bnd
File: TestR5Recognition.java
public static void testUndecidable() throws Exception {
    String testdata;
    ByteArrayInputStream stream;
    CheckResult result;
    testdata = "<?xml version='1.0' encoding='utf-8'?><repository name='index1'/>";
    stream = new ByteArrayInputStream(testdata.getBytes());
    assertEquals(undecided, new R5RepoContentProvider().checkStream("xxx", stream).getDecision());
    testdata = "<repository><resource/></repository>";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new R5RepoContentProvider().checkStream("xxx", stream);
    assertEquals(undecided, result.getDecision());
    testdata = "<repository><referral/></repository>";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new R5RepoContentProvider().checkStream("xxx", stream);
    assertEquals(undecided, result.getDecision());
}

10. TestObrRecognition#testRejectOnCapabilityChildElementName()

Project: bnd
File: TestObrRecognition.java
public static void testRejectOnCapabilityChildElementName() throws Exception {
    String testdata;
    ByteArrayInputStream stream;
    CheckResult result;
    // Definitely wrong
    testdata = "<repository><resource><capability><XXX/></capability></resource><repo...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(reject, result.getDecision());
    assertNull(result.getException());
    // Definitely right
    testdata = "<repository><resource><capability><p/></capability></resource><repo...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
    // Arbitrary elements under resource are allowed
    testdata = "<repository><resource><XXX/><YYY/><capability><p/></capability><ZZZ/></resource><repo...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
}

11. TestObrRecognition#testRejectOnRepositoryChildElementName()

Project: bnd
File: TestObrRecognition.java
public static void testRejectOnRepositoryChildElementName() throws Exception {
    String testdata;
    ByteArrayInputStream stream;
    CheckResult result;
    // Definitely wrong
    testdata = "<repository><XXX/><repo...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(reject, result.getDecision());
    assertNull(result.getException());
    // Okay but not enough to decide for sure
    testdata = "<repository><resource/></repository>";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(undecided, result.getDecision());
    // Okay but not enough to decide for sure
    testdata = "<repository><referral/></repository>";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(undecided, result.getDecision());
}

12. OldAndroidByteArrayInputStreamTest#testByteArrayInputStream()

Project: j2objc
File: OldAndroidByteArrayInputStreamTest.java
public void testByteArrayInputStream() throws Exception {
    String str = "AbCdEfGhIjKlMnOpQrStUvWxYz";
    ByteArrayInputStream a = new ByteArrayInputStream(str.getBytes());
    ByteArrayInputStream b = new ByteArrayInputStream(str.getBytes());
    ByteArrayInputStream c = new ByteArrayInputStream(str.getBytes());
    ByteArrayInputStream d = new ByteArrayInputStream(str.getBytes());
    Assert.assertEquals(str, read(a));
    Assert.assertEquals("AbCdEfGhIj", read(b, 10));
    Assert.assertEquals("bdfhjlnprtvxz", skipRead(c));
    Assert.assertEquals("AbCdEfGdEfGhIjKlMnOpQrStUvWxYz", markRead(d, 3, 4));
}

13. DataFormatConcurrentTest#unmarshal()

Project: camel
File: DataFormatConcurrentTest.java
public void unmarshal(final CountDownLatch latch) throws Exception {
    // warm up
    ByteArrayInputStream[] warmUpPayloads = createPayloads(warmupCount);
    for (ByteArrayInputStream payload : warmUpPayloads) {
        template.sendBody(payload);
    }
    final ByteArrayInputStream[] payloads = createPayloads(testCycleCount);
    ExecutorService pool = Executors.newFixedThreadPool(20);
    long start = System.currentTimeMillis();
    for (int i = 0; i < payloads.length; i++) {
        final int finalI = i;
        pool.execute(new Runnable() {

            public void run() {
                template.sendBody(payloads[finalI]);
            }
        });
    }
    latch.await();
    long end = System.currentTimeMillis();
    log.info("Sending {} messages to {} took {} ms", new Object[] { payloads.length, template.getDefaultEndpoint().getEndpointUri(), end - start });
}

14. CompatibilityTest#testByteStringFromInputStream()

Project: j2objc
File: CompatibilityTest.java
public void testByteStringFromInputStream() throws Exception {
    byte[] randomBytes = readStream(getTestData("randombytes"));
    ByteArrayInputStream in = new ByteArrayInputStream(randomBytes);
    ByteString bs = ByteString.readFrom(in, 2, 256);
    checkBytes(randomBytes, bs.toByteArray());
    in = new ByteArrayInputStream(randomBytes);
    bs = ByteString.readFrom(in, 256);
    checkBytes(randomBytes, bs.toByteArray());
    in = new ByteArrayInputStream(randomBytes);
    bs = ByteString.readFrom(in);
    checkBytes(randomBytes, bs.toByteArray());
}

15. Verify#setup()

Project: openjdk
File: Verify.java
private static void setup() throws CertificateException, CRLException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    /* Create CRL */
    ByteArrayInputStream inputStream = new ByteArrayInputStream(crlStr.getBytes());
    crl = (X509CRL) cf.generateCRL(inputStream);
    /* Get public key of the CRL issuer cert */
    inputStream = new ByteArrayInputStream(crlIssuerCertStr.getBytes());
    X509Certificate cert = (X509Certificate) cf.generateCertificate(inputStream);
    crlIssuerCertPubKey = cert.getPublicKey();
    /* Get public key of the self-signed Cert */
    inputStream = new ByteArrayInputStream(selfSignedCertStr.getBytes());
    selfSignedCertPubKey = cf.generateCertificate(inputStream).getPublicKey();
}

16. Filter#unpickle()

Project: bboss
File: Filter.java
/**
     * Reconstitute a serialized object.
     * @param data The pickled object.
     * @return The reconstituted object.
     * @exception IOException If the input stream complains. 
     * @exception ClassNotFoundException If the serialized object class cannot
     * be located.
     */
public static Object unpickle(byte[] data) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis;
    ObjectInputStream ois;
    Object ret;
    bis = new ByteArrayInputStream(data);
    ois = new ObjectInputStream(bis);
    ret = ois.readObject();
    ois.close();
    return (ret);
}

17. ConsumersTest#testAsynchronousRuntimeExceptionInConsumerOutputStream()

Project: bazel
File: ConsumersTest.java
/**
   * Tests that if an RuntimeException occurs in an output stream, the exception
   * will be recorded and thrown when we call waitForCompletion.
   */
@Test
public void testAsynchronousRuntimeExceptionInConsumerOutputStream() throws Exception {
    OutputStream out = new OutputStream() {

        @Override
        public void write(int b) {
            throw new RuntimeException(SECRET_MESSAGE);
        }
    };
    OutErrConsumers outErr = Consumers.createStreamingConsumers(out, out);
    ByteArrayInputStream outInput = new ByteArrayInputStream(new byte[] { 'a' });
    ByteArrayInputStream errInput = new ByteArrayInputStream(new byte[0]);
    outErr.registerInputs(outInput, errInput, false);
    try {
        outErr.waitForCompletion();
        fail();
    } catch (RuntimeException e) {
        assertThat(e).hasMessage(SECRET_MESSAGE);
    }
}

18. ConsumersTest#testAsynchronousErrorInConsumerOutputStream()

Project: bazel
File: ConsumersTest.java
/**
   * Tests that if an Error occurs in an output stream, the error
   * will be recorded and thrown when we call waitForCompletion.
   */
@Test
public void testAsynchronousErrorInConsumerOutputStream() {
    OutputStream out = new OutputStream() {

        @Override
        public void write(int b) throws IOException {
            throw new OutOfMemoryError(SECRET_MESSAGE);
        }
    };
    OutErrConsumers outErr = Consumers.createStreamingConsumers(out, out);
    ByteArrayInputStream outInput = new ByteArrayInputStream(new byte[] { 'a' });
    ByteArrayInputStream errInput = new ByteArrayInputStream(new byte[0]);
    outErr.registerInputs(outInput, errInput, false);
    try {
        outErr.waitForCompletion();
        fail();
    } catch (IOException e) {
        fail();
    } catch (Error e) {
        assertThat(e).hasMessage(SECRET_MESSAGE);
    }
}

19. ConsumersTest#testAsynchronousOutOfMemoryErrorInConsumerOutputStream()

Project: bazel
File: ConsumersTest.java
/**
   * Tests that if an OutOfMemeoryError occurs in an output stream, it
   * will be recorded and thrown when we call waitForCompletion.
   */
@Test
public void testAsynchronousOutOfMemoryErrorInConsumerOutputStream() {
    final OutOfMemoryError error = new OutOfMemoryError(SECRET_MESSAGE);
    OutputStream out = new OutputStream() {

        @Override
        public void write(int b) throws IOException {
            throw error;
        }
    };
    OutErrConsumers outErr = Consumers.createStreamingConsumers(out, out);
    ByteArrayInputStream outInput = new ByteArrayInputStream(new byte[] { 'a' });
    ByteArrayInputStream errInput = new ByteArrayInputStream(new byte[0]);
    outErr.registerInputs(outInput, errInput, false);
    try {
        outErr.waitForCompletion();
        fail();
    } catch (IOException e) {
        fail();
    } catch (OutOfMemoryError e) {
        assertSame("OutOfMemoryError is not masked", error, e);
    }
}

20. ConsumersTest#testAsynchronousIOExceptionInConsumerOutputStream()

Project: bazel
File: ConsumersTest.java
/**
   * Tests that if an IOException occurs in an output stream, the exception
   * will be recorded and thrown when we call waitForCompletion.
   */
@Test
public void testAsynchronousIOExceptionInConsumerOutputStream() {
    OutputStream out = new OutputStream() {

        @Override
        public void write(int b) throws IOException {
            throw new IOException(SECRET_MESSAGE);
        }
    };
    OutErrConsumers outErr = Consumers.createStreamingConsumers(out, out);
    ByteArrayInputStream outInput = new ByteArrayInputStream(new byte[] { 'a' });
    ByteArrayInputStream errInput = new ByteArrayInputStream(new byte[0]);
    outErr.registerInputs(outInput, errInput, false);
    try {
        outErr.waitForCompletion();
        fail();
    } catch (IOException e) {
        assertThat(e).hasMessage(SECRET_MESSAGE);
    }
}

21. StreamSourceDispatchTests#testOneWayPayloadMode()

Project: axis2-java
File: StreamSourceDispatchTests.java
/**
     * Invoke a Dispatch<Source> one-way operation
     */
public void testOneWayPayloadMode() throws Exception {
    TestLogger.logger.debug("---------------------------------------");
    TestLogger.logger.debug("test: " + getName());
    // Initialize the JAX-WS client artifacts
    Service svc = Service.create(DispatchTestConstants.QNAME_SERVICE);
    svc.addPort(DispatchTestConstants.QNAME_PORT, null, DispatchTestConstants.URL);
    Dispatch<Source> dispatch = svc.createDispatch(DispatchTestConstants.QNAME_PORT, Source.class, Service.Mode.PAYLOAD);
    // Create a StreamSource with the desired content
    byte[] bytes = DispatchTestConstants.sampleBodyContent.getBytes();
    ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
    Source srcStream = new StreamSource((InputStream) stream);
    TestLogger.logger.debug(">> Invoking One Way Dispatch");
    dispatch.invokeOneWay(srcStream);
    // Invoke a second time to verify
    stream = new ByteArrayInputStream(bytes);
    srcStream = new StreamSource((InputStream) stream);
    TestLogger.logger.debug(">> Invoking One Way Dispatch");
    dispatch.invokeOneWay(srcStream);
}

22. TTextProtocolTest#tTextProtocolReadWriteTest()

Project: armeria
File: TTextProtocolTest.java
/**
     * Read in (deserialize) a thrift message in TTextProtocol format
     * from a file on disk, then serialize it back out to a string.
     * Finally, deserialize that string and compare to the original
     * message.
     * @throws IOException
     */
@Test
public void tTextProtocolReadWriteTest() throws Exception {
    // Deserialize the file contents into a thrift message.
    ByteArrayInputStream bais1 = new ByteArrayInputStream(fileContents.getBytes());
    TTextProtocolTestMsg msg1 = new TTextProtocolTestMsg();
    msg1.read(new TTextProtocol(new TIOStreamTransport(bais1)));
    assertEquals(testMsg(), msg1);
    // Serialize that thrift message out to a byte array
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    msg1.write(new TTextProtocol(new TIOStreamTransport(baos)));
    byte[] bytes = baos.toByteArray();
    // Deserialize that string back to a thrift message.
    ByteArrayInputStream bais2 = new ByteArrayInputStream(bytes);
    TTextProtocolTestMsg msg2 = new TTextProtocolTestMsg();
    msg2.read(new TTextProtocol(new TIOStreamTransport(bais2)));
    assertEquals(msg1, msg2);
}

23. BitmapUtils#imageBytes2Bitmap()

Project: iBeebo
File: BitmapUtils.java
public static Bitmap imageBytes2Bitmap(Context context, byte[] imageBytes) {
    ByteArrayInputStream isBm = new ByteArrayInputStream(imageBytes);
    BitmapFactory.Options newOpts = new BitmapFactory.Options();
    newOpts.inJustDecodeBounds = true;
    Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    newOpts.inJustDecodeBounds = false;
    // ??????????options.inJustDecodeBounds ??true?
    int oriWidth = newOpts.outWidth;
    int oriHeight = newOpts.outHeight;
    if (oriWidth > oriHeight) {
        newOpts.inSampleSize = oriHeight / context.getResources().getDisplayMetrics().widthPixels;
    } else {
        newOpts.inSampleSize = oriWidth / context.getResources().getDisplayMetrics().widthPixels;
    }
    // ???Bitmap.Config.ARGB_8888
    newOpts.inPreferredConfig = Config.RGB_565;
    newOpts.inPurgeable = true;
    newOpts.inInputShareable = true;
    isBm = new ByteArrayInputStream(imageBytes);
    bitmap = BitmapFactory.decodeStream(isBm, null, newOpts);
    // ???????????????
    return bitmap;
}

24. TestOpenFilesInfo#testSerialize()

Project: hadoop-20
File: TestOpenFilesInfo.java
@Test
public void testSerialize() throws Exception {
    createOpenFiles(10, "testSerialize");
    FSNamesystem ns = cluster.getNameNode().namesystem;
    OpenFilesInfo info = ns.getOpenFiles();
    // Serialize object
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream out = new DataOutputStream(bout);
    info.write(out);
    // Deserialize object.
    ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
    DataInputStream in = new DataInputStream(bin);
    OpenFilesInfo info1 = new OpenFilesInfo();
    info1.readFields(in);
    // Verify and cleanup.
    verifyLease(info);
    assertEquals(info, info1);
    bout.close();
    bin.close();
    out.close();
    in.close();
}

25. ChainingClassLoaderTest#getResourceAsStreamReturnsStreamFromChildClassLoader()

Project: graylog2-server
File: ChainingClassLoaderTest.java
@Test
public void getResourceAsStreamReturnsStreamFromChildClassLoader() throws Exception {
    final ClassLoader parent = getClass().getClassLoader();
    final ClassLoader child = mock(ClassLoader.class);
    final ByteArrayInputStream inputStream = new ByteArrayInputStream("foobar".getBytes(StandardCharsets.UTF_8));
    when(child.getResourceAsStream("name")).thenReturn(inputStream);
    final ChainingClassLoader chainingClassLoader = new ChainingClassLoader(parent);
    chainingClassLoader.addClassLoader(child);
    final InputStream stream = chainingClassLoader.getResourceAsStream("name");
    final ByteArrayInputStream expected = new ByteArrayInputStream("foobar".getBytes(StandardCharsets.UTF_8));
    assertThat(stream).hasSameContentAs(expected);
}

26. ConsoleServiceTest#shouldReturnConsoleUpdates()

Project: gocd
File: ConsoleServiceTest.java
@Test
public void shouldReturnConsoleUpdates() throws IOException {
    String separator = getProperty("line.separator");
    String output = "line1" + separator + "line2" + separator + "line3";
    ByteArrayInputStream stream = new ByteArrayInputStream(output.getBytes());
    ConsoleOut consoleOut = service.getConsoleOut(0, stream);
    assertThat(consoleOut.output(), is(output + separator));
    assertThat(consoleOut.calculateNextStart(), is(3));
    output += separator + "line4" + separator + "line5";
    stream = new ByteArrayInputStream(output.getBytes());
    consoleOut = service.getConsoleOut(3, stream);
    assertThat(consoleOut.output(), is("line4" + separator + "line5" + separator));
    assertThat(consoleOut.calculateNextStart(), is(5));
}

27. LineReadingInputStreamTest#testBothImplementation()

Project: fred
File: LineReadingInputStreamTest.java
public void testBothImplementation() throws Exception {
    ByteArrayInputStream bis1 = new ByteArrayInputStream(BLOCK.getBytes("ISO-8859-1"));
    ByteArrayInputStream bis2 = new ByteArrayInputStream(BLOCK.getBytes("ISO-8859-1"));
    LineReadingInputStream lris1 = new LineReadingInputStream(bis1);
    LineReadingInputStream lris2 = new LineReadingInputStream(bis2);
    while (bis1.available() > 0 || bis2.available() > 0) {
        String stringWithoutMark = lris2.readLineWithoutMarking(MAX_LENGTH * 10, BUFFER_SIZE, true);
        String stringWithMark = lris1.readLine(MAX_LENGTH * 10, BUFFER_SIZE, true);
        assertEquals(stringWithMark, stringWithoutMark);
    }
    assertNull(lris1.readLine(MAX_LENGTH, BUFFER_SIZE, true));
    assertNull(lris2.readLineWithoutMarking(MAX_LENGTH, BUFFER_SIZE, true));
}

28. TTextProtocolTest#tTextProtocolReadWriteTest()

Project: commons
File: TTextProtocolTest.java
/**
   * Read in (deserialize) a thrift message in TTextProtocol format
   * from a file on disk, then serialize it back out to a string.
   * Finally, deserialize that string and compare to the original
   * message.
   * @throws IOException
   */
@Test
public void tTextProtocolReadWriteTest() throws IOException, TException {
    // Deserialize the file contents into a thrift message.
    ByteArrayInputStream bais1 = new ByteArrayInputStream(fileContents.getBytes());
    TTextProtocolTestMsg msg1 = new TTextProtocolTestMsg();
    msg1.read(new TTextProtocol(new TIOStreamTransport(bais1)));
    assertEquals(testMsg(), msg1);
    // Serialize that thrift message out to a byte array
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    msg1.write(new TTextProtocol(new TIOStreamTransport(baos)));
    byte[] bytes = baos.toByteArray();
    // Deserialize that string back to a thrift message.
    ByteArrayInputStream bais2 = new ByteArrayInputStream(bytes);
    TTextProtocolTestMsg msg2 = new TTextProtocolTestMsg();
    msg2.read(new TTextProtocol(new TIOStreamTransport(bais2)));
    assertEquals(msg1, msg2);
}

29. UIManager#parseImage()

Project: CodenameOne
File: UIManager.java
private static Image parseImage(String value) throws IOException {
    int index = 0;
    byte[] imageData = new byte[value.length() / 2];
    int vlen = value.length();
    while (index < vlen) {
        String byteStr = value.substring(index, index + 2);
        imageData[index / 2] = Integer.valueOf(byteStr, 16).byteValue();
        index += 2;
    }
    ByteArrayInputStream in = new ByteArrayInputStream(imageData);
    Image image = Image.createImage(in);
    in.close();
    return image;
}

30. IpAddressTest#testStreamableWithHighPort()

Project: JGroups
File: IpAddressTest.java
public static void testStreamableWithHighPort() throws Exception {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream oos = new DataOutputStream(bos);
    byte[] buf = null;
    ByteArrayInputStream bis = null;
    DataInputStream dis;
    IpAddress x, x2;
    x = createStackConformantAddress(65535);
    x.writeTo(oos);
    buf = bos.toByteArray();
    bis = new ByteArrayInputStream(buf);
    dis = new DataInputStream(bis);
    x2 = new IpAddress();
    x2.readFrom(dis);
    System.out.println("x: " + x + ", x2: " + x2);
    assert x2.getPort() > 0;
    Assert.assertEquals(x.getPort(), x2.getPort());
}

31. IpAddressTest#testIPv6WithStreamable()

Project: JGroups
File: IpAddressTest.java
public static void testIPv6WithStreamable() throws Exception {
    IpAddress ip = new IpAddress("fe80:0:0:0:21b:21ff:fe07:a3b0", 5555);
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(bos);
    byte[] buf = null;
    ByteArrayInputStream bis = null;
    DataInputStream dis;
    System.out.println("-- address is " + ip);
    ip.writeTo(dos);
    buf = bos.toByteArray();
    bis = new ByteArrayInputStream(buf);
    dis = new DataInputStream(bis);
    IpAddress ip2 = new IpAddress();
    ip2.readFrom(dis);
    Assert.assertEquals(ip, ip2);
}

32. TestResultSetIO#test_resultset_01()

Project: jena
File: TestResultSetIO.java
@Test
public void test_resultset_01() {
    // write(data)-read-compare
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    ResultSetMgr.write(out, test_rs, lang);
    test_rs.reset();
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    ResultSet rs = ResultSetMgr.read(in, lang);
    ResultSetRewindable rsw = ResultSetFactory.makeRewindable(rs);
    if (!lang.equals(SPARQLResultSetCSV))
        // CSV is not faithful
        assertTrue(ResultSetCompare.equalsByTerm(test_rs, rsw));
    rsw.reset();
    test_rs.reset();
    out = new ByteArrayOutputStream();
    // Round trip the output from above - write(rsw)-read-compare
    ResultSetMgr.write(out, rsw, lang);
    in = new ByteArrayInputStream(out.toByteArray());
    ResultSet rs2 = ResultSetMgr.read(in, lang);
    // Not test_rs -- CSV round-trips to itself.
    assertTrue(ResultSetCompare.equalsByTerm(rsw, rs2));
}

33. MarshalledObject#get()

Project: jdk7u-jdk
File: MarshalledObject.java
/**
     * Returns a new copy of the contained marshalledobject.  The internal
     * representation is deserialized with the semantics used for
     * unmarshaling paramters for RMI calls.
     *
     * @return a copy of the contained object
     * @exception IOException if an <code>IOException</code> occurs while
     * deserializing the object from its internal representation.
     * @exception ClassNotFoundException if a
     * <code>ClassNotFoundException</code> occurs while deserializing the
     * object from its internal representation.
     * could not be found
     * @since 1.2
     */
public T get() throws IOException, ClassNotFoundException {
    if (// must have been a null object
    objBytes == null)
        return null;
    ByteArrayInputStream bin = new ByteArrayInputStream(objBytes);
    // locBytes is null if no annotations
    ByteArrayInputStream lin = (locBytes == null ? null : new ByteArrayInputStream(locBytes));
    MarshalledObjectInputStream in = new MarshalledObjectInputStream(bin, lin);
    T obj = (T) in.readObject();
    in.close();
    return obj;
}

34. JbpmSerializationHelper#deserializeKnowledgeSession()

Project: jbpm
File: JbpmSerializationHelper.java
public static StatefulKnowledgeSession deserializeKnowledgeSession(Marshaller marshaller, byte[] serializedKsession) throws Exception {
    ByteArrayInputStream bais = new ByteArrayInputStream(serializedKsession);
    StatefulKnowledgeSession deserializedKsession = (StatefulKnowledgeSession) marshaller.unmarshall(bais, SessionConfiguration.newInstance(), EnvironmentFactory.newEnvironment());
    bais.close();
    return deserializedKsession;
}

35. IOUtilsBehaviour#shouldProcessInputStream()

Project: jbehave-core
File: IOUtilsBehaviour.java
// same for InputStream
@Test
public void shouldProcessInputStream() throws IOException {
    assertEquals("", IOUtils.toString(new ByteArrayInputStream("".getBytes("UTF-8")), true));
    assertEquals("a", IOUtils.toString(new ByteArrayInputStream("a".getBytes("UTF-8")), true));
    assertEquals("asdf", IOUtils.toString(new ByteArrayInputStream("asdf".getBytes("UTF-8")), true));
    assertEquals("äöü", IOUtils.toString(new ByteArrayInputStream("äöü".getBytes("UTF-8")), true));
    ByteArrayInputStream input = new ByteArrayInputStream("asdf".getBytes("UTF-8"));
    assertEquals("asdf", IOUtils.toString(input, false));
    input.close();
    String longString = createLongString();
    assertEquals(longString, IOUtils.toString(new ByteArrayInputStream(longString.getBytes("UTF-8")), true));
    assertEquals("##########", IOUtils.toString(new FileInputStream("src/test/resources/testfile"), true));
}

36. DataStoreTextWriterTest#basicOperation()

Project: jackrabbit-oak
File: DataStoreTextWriterTest.java
@Test
public void basicOperation() throws Exception {
    File fdsDir = temporaryFolder.newFolder();
    FileDataStore fds = DataStoreUtils.createFDS(fdsDir, 0);
    ByteArrayInputStream is = new ByteArrayInputStream("hello".getBytes());
    DataRecord dr = fds.addRecord(is);
    File writerDir = temporaryFolder.newFolder();
    TextWriter writer = new DataStoreTextWriter(writerDir, false);
    writer.write(dr.getIdentifier().toString(), "hello");
    FileDataStore fds2 = DataStoreUtils.createFDS(writerDir, 0);
    DataRecord dr2 = fds2.getRecordIfStored(dr.getIdentifier());
    is.reset();
    assertTrue(IOUtils.contentEquals(is, dr2.getStream()));
}

37. SerializationTest#testInvalidXmlThrowsInvalidSerializedDataException()

Project: jackrabbit
File: SerializationTest.java
/**
     * Tests whether importing an invalid XML file throws a InvalidSerializedDataException.
     * The file used here is more or less garbage.
     */
public void testInvalidXmlThrowsInvalidSerializedDataException() throws RepositoryException, IOException {
    String data = "<this is not a <valid> <xml> file/>";
    ByteArrayInputStream in = new ByteArrayInputStream(data.getBytes());
    try {
        session.importXML(treeComparator.targetFolder, in, ImportUUIDBehavior.IMPORT_UUID_CREATE_NEW);
        fail("Importing a invalid XML file should throw a InvalidSerializedDataException.");
    } catch (InvalidSerializedDataException e) {
    }
    in = new ByteArrayInputStream(data.getBytes());
    try {
        workspace.importXML(treeComparator.targetFolder, in, 0);
        fail("Importing a invalid XML file should throw a InvalidSerializedDataException.");
    } catch (InvalidSerializedDataException e) {
    }
}

38. OldInputStreamReaderTest#setUp()

Project: j2objc
File: OldInputStreamReaderTest.java
protected void setUp() throws Exception {
    super.setUp();
    in = new ByteArrayInputStream(source.getBytes("UTF-8"));
    reader = new InputStreamReader(in, "UTF-8");
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    OutputStreamWriter osw = new OutputStreamWriter(bos);
    char[] buf = new char[fileString.length()];
    fileString.getChars(0, fileString.length(), buf, 0);
    osw.write(buf);
    osw.close();
    fis = new ByteArrayInputStream(bos.toByteArray());
    is = new InputStreamReader(fis);
}

39. Bytes#split()

Project: incubator-fluo
File: Bytes.java
/**
   * Splits a bytes object into several bytes objects
   *
   * @param b Original bytes object
   * @return List of bytes objects
   */
public static final List<Bytes> split(Bytes b) {
    ByteArrayInputStream bais;
    bais = new ByteArrayInputStream(b.toArray());
    DataInputStream dis = new DataInputStream(bais);
    ArrayList<Bytes> ret = new ArrayList<>();
    try {
        while (true) {
            int len = writeUtil.readVInt(dis);
            // TODO could get pointers into original byte seq
            byte[] field = new byte[len];
            dis.readFully(field);
            ret.add(of(field));
        }
    } catch (EOFException ee) {
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    return ret;
}

40. ModelBatchTest#testProtoBatchWithoutFactors()

Project: CoreNLP
File: ModelBatchTest.java
@Theory
public void testProtoBatchWithoutFactors(@ForAll(sampleSize = 50) @From(BatchGenerator.class) ModelBatch batch) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    batch.writeToStreamWithoutFactors(byteArrayOutputStream);
    byteArrayOutputStream.close();
    byte[] bytes = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ModelBatch recovered = new ModelBatch(byteArrayInputStream);
    byteArrayInputStream.close();
    assertEquals(batch.size(), recovered.size());
    for (int i = 0; i < batch.size(); i++) {
        assertEquals(0, recovered.get(i).factors.size());
        assertTrue(batch.get(i).getModelMetaDataByReference().equals(recovered.get(i).getModelMetaDataByReference()));
        for (int j = 0; j < batch.get(i).getVariableSizes().length; j++) {
            assertTrue(batch.get(i).getVariableMetaDataByReference(j).equals(recovered.get(i).getVariableMetaDataByReference(j)));
        }
    }
}

41. ModelBatchTest#testProtoBatchModifier()

Project: CoreNLP
File: ModelBatchTest.java
@Theory
public void testProtoBatchModifier(@ForAll(sampleSize = 50) @From(BatchGenerator.class) ModelBatch batch) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    batch.writeToStream(byteArrayOutputStream);
    byteArrayOutputStream.close();
    byte[] bytes = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ModelBatch recovered = new ModelBatch(byteArrayInputStream, ( model) -> {
        model.getModelMetaDataByReference().put("testing", "true");
    });
    byteArrayInputStream.close();
    assertEquals(batch.size(), recovered.size());
    for (int i = 0; i < batch.size(); i++) {
        assertEquals("true", recovered.get(i).getModelMetaDataByReference().get("testing"));
    }
}

42. ModelBatchTest#testProtoBatch()

Project: CoreNLP
File: ModelBatchTest.java
@Theory
public void testProtoBatch(@ForAll(sampleSize = 50) @From(BatchGenerator.class) ModelBatch batch) throws IOException {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    batch.writeToStream(byteArrayOutputStream);
    byteArrayOutputStream.close();
    byte[] bytes = byteArrayOutputStream.toByteArray();
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
    ModelBatch recovered = new ModelBatch(byteArrayInputStream);
    byteArrayInputStream.close();
    assertEquals(batch.size(), recovered.size());
    for (int i = 0; i < batch.size(); i++) {
        assertTrue(batch.get(i).valueEquals(recovered.get(i), 1.0e-5));
    }
}

43. DiffModelTest#testNonIncUpdatePropertiesRemovedFromMandatoryAspect()

Project: community-edition
File: DiffModelTest.java
public void testNonIncUpdatePropertiesRemovedFromMandatoryAspect() {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL7_EXTRA_PROPERTIES_MANDATORY_ASPECTS_XML.getBytes());
    M2Model model = M2Model.createModel(byteArrayInputStream);
    QName modelName = dictionaryDAO.putModel(model);
    CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName);
    byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL7_XML.getBytes());
    model = M2Model.createModel(byteArrayInputStream);
    modelName = dictionaryDAO.putModel(model);
    CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName);
    List<M2ModelDiff> modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion);
    for (M2ModelDiff modelDiff : modelDiffs) {
        System.out.println(modelDiff.toString());
    }
    assertEquals(3, modelDiffs.size());
    assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED));
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_DELETED));
}

44. DiffModelTest#testIncUpdatePropertiesAddedToMandatoryAspect()

Project: community-edition
File: DiffModelTest.java
public void testIncUpdatePropertiesAddedToMandatoryAspect() {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL7_XML.getBytes());
    M2Model model = M2Model.createModel(byteArrayInputStream);
    QName modelName = dictionaryDAO.putModel(model);
    CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName);
    byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL7_EXTRA_PROPERTIES_MANDATORY_ASPECTS_XML.getBytes());
    model = M2Model.createModel(byteArrayInputStream);
    modelName = dictionaryDAO.putModel(model);
    CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName);
    List<M2ModelDiff> modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion);
    for (M2ModelDiff modelDiff : modelDiffs) {
        System.out.println(modelDiff.toString());
    }
    assertEquals(3, modelDiffs.size());
    assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED));
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_CREATED));
}

45. DiffModelTest#testNonIncUpdateDefaultAspectAdded()

Project: community-edition
File: DiffModelTest.java
public void testNonIncUpdateDefaultAspectAdded() {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL4_XML.getBytes());
    M2Model model = M2Model.createModel(byteArrayInputStream);
    QName modelName = dictionaryDAO.putModel(model);
    CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName);
    byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL4_EXTRA_DEFAULT_ASPECT_XML.getBytes());
    model = M2Model.createModel(byteArrayInputStream);
    modelName = dictionaryDAO.putModel(model);
    CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName);
    List<M2ModelDiff> modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion);
    for (M2ModelDiff modelDiff : modelDiffs) {
        System.out.println(modelDiff.toString());
    }
    assertEquals(4, modelDiffs.size());
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED));
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED));
    assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UNCHANGED));
}

46. DiffModelTest#testIncUpdateTitleDescription()

Project: community-edition
File: DiffModelTest.java
public void testIncUpdateTitleDescription() {
    ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL6_XML.getBytes());
    M2Model model = M2Model.createModel(byteArrayInputStream);
    QName modelName = dictionaryDAO.putModel(model);
    CompiledModel previousVersion = dictionaryDAO.getCompiledModel(modelName);
    byteArrayInputStream = new ByteArrayInputStream(AbstractModelTest.MODEL6_UPDATE1_XML.getBytes());
    model = M2Model.createModel(byteArrayInputStream);
    modelName = dictionaryDAO.putModel(model);
    CompiledModel newVersion = dictionaryDAO.getCompiledModel(modelName);
    List<M2ModelDiff> modelDiffs = dictionaryDAO.diffModel(previousVersion, newVersion);
    for (M2ModelDiff modelDiff : modelDiffs) {
        System.out.println(modelDiff.toString());
    }
    assertEquals(4, modelDiffs.size());
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_TYPE, M2ModelDiff.DIFF_UPDATED_INC));
    assertEquals(1, countDiffs(modelDiffs, M2ModelDiff.TYPE_ASPECT, M2ModelDiff.DIFF_UNCHANGED));
    assertEquals(2, countDiffs(modelDiffs, M2ModelDiff.TYPE_PROPERTY, M2ModelDiff.DIFF_UPDATED_INC));
}

47. DiffModelTest#testDuplicateModels()

Project: community-edition
File: DiffModelTest.java
public void testDuplicateModels() {
    ByteArrayInputStream byteArrayInputStream1 = new ByteArrayInputStream(AbstractModelTest.MODEL1_XML.getBytes());
    ByteArrayInputStream byteArrayInputStream2 = new ByteArrayInputStream(MODEL1_DUPLICATED_XML.getBytes());
    M2Model model1 = M2Model.createModel(byteArrayInputStream1);
    dictionaryDAO.putModel(model1);
    M2Model model2 = M2Model.createModel(byteArrayInputStream2);
    try {
        dictionaryDAO.putModel(model2);
        fail("This model with this URI has already been defined");
    } catch (NamespaceException exception) {
    }
}

48. EncryptionKeyTest#testEncode()

Project: bc-java
File: EncryptionKeyTest.java
private void testEncode(NTRUEncryptionKeyGenerationParameters params) throws IOException {
    NTRUEncryptionKeyPairGenerator kpGen = new NTRUEncryptionKeyPairGenerator();
    kpGen.init(params);
    AsymmetricCipherKeyPair kp = kpGen.generateKeyPair();
    byte[] priv = ((NTRUEncryptionPrivateKeyParameters) kp.getPrivate()).getEncoded();
    byte[] pub = ((NTRUEncryptionPublicKeyParameters) kp.getPublic()).getEncoded();
    AsymmetricCipherKeyPair kp2 = new AsymmetricCipherKeyPair(new NTRUEncryptionPublicKeyParameters(pub, params.getEncryptionParameters()), new NTRUEncryptionPrivateKeyParameters(priv, params.getEncryptionParameters()));
    assertEquals(kp.getPublic(), kp2.getPublic());
    assertEquals(kp.getPrivate(), kp2.getPrivate());
    ByteArrayOutputStream bos1 = new ByteArrayOutputStream();
    ByteArrayOutputStream bos2 = new ByteArrayOutputStream();
    ((NTRUEncryptionPrivateKeyParameters) kp.getPrivate()).writeTo(bos1);
    ((NTRUEncryptionPublicKeyParameters) kp.getPublic()).writeTo(bos2);
    ByteArrayInputStream bis1 = new ByteArrayInputStream(bos1.toByteArray());
    ByteArrayInputStream bis2 = new ByteArrayInputStream(bos2.toByteArray());
    AsymmetricCipherKeyPair kp3 = new AsymmetricCipherKeyPair(new NTRUEncryptionPublicKeyParameters(bis2, params.getEncryptionParameters()), new NTRUEncryptionPrivateKeyParameters(bis1, params.getEncryptionParameters()));
    assertEquals(kp.getPublic(), kp3.getPublic());
    assertEquals(kp.getPrivate(), kp3.getPrivate());
}

49. SerializeRoundTrip#roundTrip()

Project: encog-java-core
File: SerializeRoundTrip.java
public static Object roundTrip(Object obj) throws IOException, ClassNotFoundException {
    // first serialize to memory
    ByteArrayOutputStream memory = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(memory);
    out.writeObject(obj);
    out.close();
    memory.close();
    // now reload
    ByteArrayInputStream memory2 = new ByteArrayInputStream(memory.toByteArray());
    ObjectInputStream in = new ObjectInputStream(memory2);
    Object result = in.readObject();
    in.close();
    memory2.close();
    // return the result;
    return result;
}

50. TestXMLRead#testRead()

Project: encog-java-core
File: TestXMLRead.java
public void testRead() throws Throwable {
    ByteArrayInputStream bos = new ByteArrayInputStream(TestXMLRead.XML.getBytes());
    ReadXML read = new ReadXML(bos);
    Assert.assertEquals(0, read.read());
    Assert.assertTrue(read.is("doc", true));
    Assert.assertEquals(0, read.read());
    Assert.assertTrue(read.is("a", true));
    Assert.assertEquals('a', read.read());
    Assert.assertEquals(0, read.read());
    Assert.assertTrue(read.is("a", false));
    bos.close();
}

51. TlvUtilTest#testSearchTagByIdIn()

Project: EMV-NFC-Paycard-Enrollment
File: TlvUtilTest.java
/**
	 * @throws Exception
	 * 
	 */
@Test
public void testSearchTagByIdIn() throws Exception {
    ByteArrayInputStream in = new ByteArrayInputStream(BytesUtils.fromString("9F6B"));
    ITag tag = (ITag) Whitebox.invokeMethod(TlvUtil.class, "searchTagById", in);
    Assertions.assertThat(tag).isEqualTo(EmvTags.TRACK2_DATA);
    in = new ByteArrayInputStream(BytesUtils.fromString("FFFF"));
    tag = (ITag) Whitebox.invokeMethod(TlvUtil.class, "searchTagById", in);
    Assertions.assertThat(tag.getName()).isEqualTo("[UNKNOWN TAG]");
    Assertions.assertThat(tag.getDescription()).isEqualTo("");
    Assertions.assertThat(tag.getTagBytes()).isEqualTo(BytesUtils.fromString("FFFF"));
    Assertions.assertThat(tag.getNumTagBytes()).isEqualTo(2);
    Assertions.assertThat(tag.isConstructed()).isEqualTo(true);
    Assertions.assertThat(tag.getTagValueType()).isEqualTo(TagValueTypeEnum.BINARY);
    Assertions.assertThat(tag.getType()).isEqualTo(TagTypeEnum.CONSTRUCTED);
}

52. SerializerUtilsTest#testChannelWriteString()

Project: druid
File: SerializerUtilsTest.java
@Test
public void testChannelWriteString() throws IOException {
    final int index = 0;
    WritableByteChannel channelOutput = Channels.newChannel(outStream);
    serializerUtils.writeString(channelOutput, strings[index]);
    ByteArrayInputStream inputstream = new ByteArrayInputStream(outStream.toByteArray());
    channelOutput.close();
    inputstream.close();
    String expected = serializerUtils.readString(inputstream);
    String actuals = strings[index];
    Assert.assertEquals(expected, actuals);
}

53. SerializerUtilsTest#testChannelWritelong()

Project: druid
File: SerializerUtilsTest.java
@Test
public void testChannelWritelong() throws IOException {
    final int index = 0;
    WritableByteChannel channelOutput = Channels.newChannel(outStream);
    serializerUtils.writeLong(channelOutput, longs[index]);
    ByteArrayInputStream inputstream = new ByteArrayInputStream(outStream.toByteArray());
    channelOutput.close();
    inputstream.close();
    long expected = serializerUtils.readLong(inputstream);
    long actuals = longs[index];
    Assert.assertEquals(expected, actuals);
}

54. ReportModeller#writeToFile()

Project: drools
File: ReportModeller.java
protected void writeToFile(String fileName, String text) throws IOException {
    zout.putNextEntry(new JarEntry(fileName));
    ByteArrayInputStream i = new ByteArrayInputStream(text.getBytes(IoUtils.UTF8_CHARSET));
    int len = 0;
    byte[] copyBuf = new byte[1024];
    while (len != -1) {
        len = i.read(copyBuf, 0, copyBuf.length);
        if (len > 0) {
            zout.write(copyBuf, 0, len);
        }
    }
    i.close();
    zout.closeEntry();
}

55. Util#main()

Project: directory-kerby
File: Util.java
public static void main(String[] args) throws Exception {
    String s = "line1\n\rline2\n\rline3";
    ByteArrayInputStream in = new ByteArrayInputStream(s.getBytes(Charset.forName("UTF-8")));
    ByteArrayReadLine readLine = new ByteArrayReadLine(in);
    String line = readLine.next();
    while (line != null) {
        System.out.println(line);
        line = readLine.next();
    }
    System.out.println("--------- test 2 ----------");
    s = "line1\n\rline2\n\rline3\n\r\n\r";
    in = new ByteArrayInputStream(s.getBytes());
    readLine = new ByteArrayReadLine(in);
    line = readLine.next();
    while (line != null) {
        System.out.println(line);
        line = readLine.next();
    }
}

56. UtilsTest#testFill()

Project: dfs-datastores
File: UtilsTest.java
public void testFill() throws Exception {
    ByteArrayInputStream is = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
    byte[] buf = new byte[10];
    assertEquals(8, Utils.fill(is, buf));
    for (int i = 1; i <= 8; i++) {
        assertEquals(i, buf[i - 1]);
    }
    is = new ByteArrayInputStream(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 });
    buf = new byte[4];
    assertEquals(4, Utils.fill(is, buf));
    for (int i = 1; i <= 4; i++) {
        assertEquals(i, buf[i - 1]);
    }
}

57. InputStreamUtilTest#testSkipFully()

Project: derby
File: InputStreamUtilTest.java
public void testSkipFully() throws IOException {
    int length = 1024;
    InputStream is = new ByteArrayInputStream(new byte[length]);
    InputStreamUtil.skipFully(is, length);
    assertEquals(0, InputStreamUtil.skipUntilEOF(is));
    is = new ByteArrayInputStream(new byte[length]);
    InputStreamUtil.skipFully(is, length - 1);
    assertEquals(1, InputStreamUtil.skipUntilEOF(is));
    is = new ByteArrayInputStream(new byte[length]);
    try {
        InputStreamUtil.skipFully(is, length + 1);
        fail("Should have Meet EOF!");
    } catch (EOFException e) {
        assertTrue(true);
    }
    assertEquals(0, InputStreamUtil.skipUntilEOF(is));
}

58. MemcmpDecoderTest#testDecodeLong()

Project: cdk
File: MemcmpDecoderTest.java
@Test
public void testDecodeLong() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new MemcmpDecoder(in);
    long i = decoder.readLong();
    assertEquals(1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new MemcmpDecoder(in);
    i = decoder.readLong();
    assertEquals(-1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new MemcmpDecoder(in);
    i = decoder.readLong();
    assertEquals(0L, i);
}

59. MemcmpDecoderTest#testDecodeInt()

Project: cdk
File: MemcmpDecoderTest.java
@Test
public void testDecodeInt() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new MemcmpDecoder(in);
    int i = decoder.readInt();
    assertEquals(1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new MemcmpDecoder(in);
    i = decoder.readInt();
    assertEquals(-1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new MemcmpDecoder(in);
    i = decoder.readInt();
    assertEquals(0, i);
}

60. ColumnDecoderTest#testDecodeLong()

Project: cdk
File: ColumnDecoderTest.java
@Test
public void testDecodeLong() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new ColumnDecoder(in);
    long i = decoder.readLong();
    assertEquals(1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new ColumnDecoder(in);
    i = decoder.readLong();
    assertEquals(-1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new ColumnDecoder(in);
    i = decoder.readLong();
    assertEquals(0L, i);
}

61. ColumnDecoderTest#testDecodeInt()

Project: cdk
File: ColumnDecoderTest.java
@Test
public void testDecodeInt() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new ColumnDecoder(in);
    int i = decoder.readInt();
    assertEquals(1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new ColumnDecoder(in);
    i = decoder.readInt();
    assertEquals(-1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new ColumnDecoder(in);
    i = decoder.readInt();
    assertEquals(0, i);
}

62. DecoderTest#testBinaryDecoding()

Project: ccnx
File: DecoderTest.java
@Test
public void testBinaryDecoding() throws Exception {
    ContentName interestName = ContentName.fromNative(interestTest);
    Interest interest = new Interest(interestName);
    byte[] interestBytes = interest.encode();
    ByteArrayInputStream bais = new ByteArrayInputStream(interestBytes);
    _decoder.beginDecoding(bais);
    XMLEncodable packet = _decoder.getPacket();
    Assert.assertTrue("Packet has incorrect type", packet instanceof Interest);
    Assert.assertEquals(((Interest) packet).name(), interestName);
    ContentName contentName = ContentName.fromNative(contentTest);
    KeyManager keyManager = new KeyManagerScaffold();
    ContentObject co = ContentObject.buildContentObject(contentName, null, "test decoder".getBytes(), SecurityBaseNoCcnd.publishers[0], keyManager, null);
    byte[] contentBytes = co.encode();
    bais = new ByteArrayInputStream(contentBytes);
    _decoder.beginDecoding(bais);
    packet = _decoder.getPacket();
    Assert.assertTrue("Packet has incorrect type", packet instanceof ContentObject);
    Assert.assertEquals(((ContentObject) packet).name(), contentName);
}

63. BloomFilter#decode()

Project: ccnx
File: BloomFilter.java
@Override
public void decode(XMLDecoder decoder) throws ContentDecodingException {
    ByteArrayInputStream bais = new ByteArrayInputStream(decoder.readBinaryElement(getElementLabel()));
    _lgBits = bais.read();
    _nHash = bais.read();
    // method & reserved - ignored for now
    bais.skip(2);
    _seed = new short[4];
    for (int i = 0; i < _seed.length; i++) _seed[i] = (byte) bais.read();
    for (int i = 0; i < _seed.length; i++) _seed[i] = (short) ((_seed[i]) & 0xff);
    int i = 0;
    while (bais.available() > 0) _bloom[i++] = (byte) bais.read();
    // DKS decoding check
    if (i != usedBits()) {
        Log.warning("Unexpected result in decoding BloomFilter: expecting " + usedBits() + " bytes, got " + i);
    }
    _size = -1;
}

64. TestObrRecognition#testAcceptExtensionElementOtherNamespace()

Project: bnd
File: TestObrRecognition.java
public static void testAcceptExtensionElementOtherNamespace() throws Exception {
    String testdata;
    ByteArrayInputStream stream;
    CheckResult result;
    // Arbitrary elements under resource are allowed
    testdata = "<?xml version='1.0'?>" + "<repository><resource><foo:XXX xmlns:foo='http://org.example/ns'/><YYY/><capability><p/></capability><ZZZ/></resource><repo...";
    stream = new ByteArrayInputStream(testdata.getBytes());
    result = new ObrContentProvider(indexer).checkStream("xxx", stream);
    assertEquals(accept, result.getDecision());
}

65. PropertiesTest#testInternationalCharacters()

Project: bnd
File: PropertiesTest.java
public static void testInternationalCharacters() throws Exception {
    String test = "#comment\n" + "Namex=Loïc Cotonéa\n" + "Export-Package: *\n" + "Unicode=\\u0040\n" + "NameAgain=Loïc Cotonéa";
    byte[] bytes = test.getBytes("ISO8859-1");
    ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
    Properties p = new Properties();
    p.load(bin);
    assertEquals("@", p.get("Unicode"));
    assertEquals("Loïc Cotonéa", p.get("Namex"));
    // Now test if we can make the round trip
    Builder b = new Builder();
    b.setProperties(p);
    b.addClasspath(IO.getFile("jar/asm.jar"));
    Jar jar = b.build();
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    jar.getManifest().write(bout);
    bin = new ByteArrayInputStream(bout.toByteArray());
    Manifest m = new Manifest(bin);
    assertEquals("Loïc Cotonéa", m.getMainAttributes().getValue("Namex"));
}

66. XMLWindow#setXML()

Project: bioformats
File: XMLWindow.java
// -- XMLWindow methods --
/** Displays XML from the given string. */
public void setXML(String xml) throws ParserConfigurationException, SAXException, IOException {
    setDocument(null);
    // parse XML from string into DOM structure
    DocumentBuilderFactory docFact = DocumentBuilderFactory.newInstance();
    DocumentBuilder db = docFact.newDocumentBuilder();
    ByteArrayInputStream is = new ByteArrayInputStream(xml.getBytes(Constants.ENCODING));
    Document doc = db.parse(is);
    is.close();
    setDocument(doc);
}

67. PreparedStatementTest#testBinaryStreamErrorsRestartable()

Project: pgjdbc-ng
File: PreparedStatementTest.java
@Test
public void testBinaryStreamErrorsRestartable() throws SQLException {
    byte[] buf = new byte[10];
    for (int i = 0; i < buf.length; i++) {
        buf[i] = (byte) i;
    }
    // InputStream is shorter than the length argument implies.
    InputStream is = new ByteArrayInputStream(buf);
    runBrokenStream(is, buf.length + 1);
    // InputStream throws an Exception during read.
    is = new BrokenInputStream(new ByteArrayInputStream(buf), buf.length / 2);
    runBrokenStream(is, buf.length);
    // Invalid length < 0.
    is = new ByteArrayInputStream(buf);
    runBrokenStream(is, -1);
    // Total Bind message length too long.
    is = new ByteArrayInputStream(buf);
    runBrokenStream(is, Integer.MAX_VALUE);
}

68. GZIPCompressionProviderTest#testCreateInputStream()

Project: pentaho-kettle
File: GZIPCompressionProviderTest.java
@Test
public void testCreateInputStream() throws IOException {
    GZIPCompressionProvider provider = (GZIPCompressionProvider) factory.getCompressionProviderByName(PROVIDER_NAME);
    // Create an in-memory GZIP output stream for use by the input stream (to avoid exceptions)
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    GZIPOutputStream gos = new GZIPOutputStream(baos);
    byte[] testBytes = "Test".getBytes();
    gos.write(testBytes);
    ByteArrayInputStream in = new ByteArrayInputStream(baos.toByteArray());
    // Test stream creation paths
    GZIPInputStream gis = new GZIPInputStream(in);
    in = new ByteArrayInputStream(baos.toByteArray());
    GZIPCompressionInputStream ncis = provider.createInputStream(in);
    assertNotNull(ncis);
    GZIPCompressionInputStream ncis2 = provider.createInputStream(gis);
    assertNotNull(ncis2);
}

69. JPEGFactory#createFromStream()

Project: PdfBox-Android
File: JPEGFactory.java
/**
	 * Creates a new JPEG Image XObject from an input stream containing JPEG data.
	 * 
	 * The input stream data will be preserved and embedded in the PDF file without modification.
	 * @param document the document where the image will be created
	 * @param stream a stream of JPEG data
	 * @return a new Image XObject
	 * 
	 * @throws IOException if the input stream cannot be read
	 */
public static PDImageXObject createFromStream(PDDocument document, InputStream stream) throws IOException {
    // copy stream
    ByteArrayInputStream byteStream = new ByteArrayInputStream(IOUtils.toByteArray(stream));
    // read image
    Bitmap awtImage = readJPEG(byteStream);
    byteStream.reset();
    // create Image XObject from stream
    PDImageXObject pdImage = new PDImageXObject(document, byteStream, COSName.DCT_DECODE, awtImage.getWidth(), awtImage.getHeight(), //awtImage.getColorModel().getComponentSize(0),
    8, //getColorSpaceFromAWT(awtImage));
    PDDeviceRGB.INSTANCE);
    // no alpha
    if (awtImage.hasAlpha()) {
        throw new UnsupportedOperationException("alpha channel not implemented");
    }
    return pdImage;
}

70. JPEGFactory#createFromStream()

Project: pdfbox
File: JPEGFactory.java
/**
     * Creates a new JPEG Image XObject from an input stream containing JPEG data.
     * 
     * The input stream data will be preserved and embedded in the PDF file without modification.
     * @param document the document where the image will be created
     * @param stream a stream of JPEG data
     * @return a new Image XObject
     * 
     * @throws IOException if the input stream cannot be read
     */
public static PDImageXObject createFromStream(PDDocument document, InputStream stream) throws IOException {
    // copy stream
    ByteArrayInputStream byteStream = new ByteArrayInputStream(IOUtils.toByteArray(stream));
    // read image
    BufferedImage awtImage = readJPEG(byteStream);
    byteStream.reset();
    // create Image XObject from stream
    PDImageXObject pdImage = new PDImageXObject(document, byteStream, COSName.DCT_DECODE, awtImage.getWidth(), awtImage.getHeight(), awtImage.getColorModel().getComponentSize(0), getColorSpaceFromAWT(awtImage));
    // no alpha
    if (awtImage.getColorModel().hasAlpha()) {
        throw new UnsupportedOperationException("alpha channel not implemented");
    }
    return pdImage;
}

71. TestConfiguration#testSerialization()

Project: PalDB
File: TestConfiguration.java
@Test
public void testSerialization() throws Throwable {
    Configuration c = new Configuration();
    c.set("foo", "bar");
    c.registerSerializer(new PointSerializer());
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(bos);
    out.writeObject(c);
    out.close();
    bos.close();
    byte[] bytes = bos.toByteArray();
    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    ObjectInputStream in = new ObjectInputStream(bis);
    Configuration sc = (Configuration) in.readObject();
    in.close();
    bis.close();
    Assert.assertEquals(sc, c);
}

72. Verify#setup()

Project: openjdk
File: Verify.java
private static void setup() throws CertificateException, CRLException {
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    /* Get public key of the CRL issuer cert */
    ByteArrayInputStream inputStream = new ByteArrayInputStream(crlIssuerCertStr.getBytes());
    cert = (X509Certificate) cf.generateCertificate(inputStream);
    crlIssuerCertPubKey = cert.getPublicKey();
    /* Get public key of the self-signed Cert */
    inputStream = new ByteArrayInputStream(selfSignedCertStr.getBytes());
    selfSignedCertPubKey = cf.generateCertificate(inputStream).getPublicKey();
}

73. SubjectNullTests#deserializeBuffer()

Project: openjdk
File: SubjectNullTests.java
/**
     * Deserialize an object from a byte array.
     *
     * @param type The {@code Class} that the serialized file is supposed
     *             to contain.
     * @param serBuffer The byte array containing the serialized object data
     *
     * @return An object of the type specified in the {@code type} parameter
     */
private static <T> T deserializeBuffer(Class<T> type, byte[] serBuffer) throws IOException, ClassNotFoundException {
    ByteArrayInputStream bis = new ByteArrayInputStream(serBuffer);
    ObjectInputStream ois = new ObjectInputStream(bis);
    T newObj = type.cast(ois.readObject());
    ois.close();
    bis.close();
    return newObj;
}

74. MarshalledObject#get()

Project: openjdk
File: MarshalledObject.java
/**
     * Returns a new copy of the contained marshalledobject.  The internal
     * representation is deserialized with the semantics used for
     * unmarshaling parameters for RMI calls.
     *
     * @return a copy of the contained object
     * @exception IOException if an <code>IOException</code> occurs while
     * deserializing the object from its internal representation.
     * @exception ClassNotFoundException if a
     * <code>ClassNotFoundException</code> occurs while deserializing the
     * object from its internal representation.
     * could not be found
     * @since 1.2
     */
public T get() throws IOException, ClassNotFoundException {
    if (// must have been a null object
    objBytes == null)
        return null;
    ByteArrayInputStream bin = new ByteArrayInputStream(objBytes);
    // locBytes is null if no annotations
    ByteArrayInputStream lin = (locBytes == null ? null : new ByteArrayInputStream(locBytes));
    MarshalledObjectInputStream in = new MarshalledObjectInputStream(bin, lin);
    @SuppressWarnings("unchecked") T obj = (T) in.readObject();
    in.close();
    return obj;
}

75. XmiCasDeserializerTest#testDuplicateNsPrefixes()

Project: uima-uimaj
File: XmiCasDeserializerTest.java
public void testDuplicateNsPrefixes() throws Exception {
    TypeSystemDescription ts = new TypeSystemDescription_impl();
    ts.addType("org.bar.foo.Foo", "", "uima.tcas.Annotation");
    ts.addType("org.baz.foo.Foo", "", "uima.tcas.Annotation");
    CAS cas = CasCreationUtils.createCas(ts, null, null);
    cas.setDocumentText("Foo");
    Type t1 = cas.getTypeSystem().getType("org.bar.foo.Foo");
    Type t2 = cas.getTypeSystem().getType("org.baz.foo.Foo");
    AnnotationFS a1 = cas.createAnnotation(t1, 0, 3);
    cas.addFsToIndexes(a1);
    AnnotationFS a2 = cas.createAnnotation(t2, 0, 3);
    cas.addFsToIndexes(a2);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    XmiCasSerializer.serialize(cas, baos);
    baos.close();
    byte[] bytes = baos.toByteArray();
    CAS cas2 = CasCreationUtils.createCas(ts, null, null);
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
    XmiCasDeserializer.deserialize(bais, cas2);
    bais.close();
    CasComparer.assertEquals(cas, cas2);
}

76. TwitterTest#assertDeserializedFormIsNotEqual()

Project: twitter4j
File: TwitterTest.java
public static Object assertDeserializedFormIsNotEqual(Object obj) throws Exception {
    ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(byteOutputStream);
    oos.writeObject(obj);
    byteOutputStream.close();
    ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteOutputStream.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(byteInputStream);
    Object that = ois.readObject();
    byteInputStream.close();
    ois.close();
    Assert.assertFalse(obj.equals(that));
    return that;
}

77. TestIFile#testCompressedFlag()

Project: tez
File: TestIFile.java
@Test(timeout = 5000)
public void testCompressedFlag() throws IOException {
    byte[] HEADER = new byte[] { (byte) 'T', (byte) 'I', (byte) 'F', (byte) 1 };
    ByteArrayInputStream bin = new ByteArrayInputStream(HEADER);
    boolean compressed = IFile.Reader.isCompressedFlagEnabled(bin);
    assert (compressed == true);
    //Negative case: Half cooked header
    HEADER = new byte[] { (byte) 'T', (byte) 'I' };
    bin = new ByteArrayInputStream(HEADER);
    try {
        compressed = IFile.Reader.isCompressedFlagEnabled(bin);
        fail("Should not have allowed wrong header");
    } catch (Exception e) {
    }
}

78. TestShuffleUtils#testShuffleToDiskChecksum()

Project: tez
File: TestShuffleUtils.java
@Test
public void testShuffleToDiskChecksum() throws Exception {
    // verify sending a stream of zeroes without checksum validation
    // does not trigger an exception
    byte[] bogusData = new byte[1000];
    Arrays.fill(bogusData, (byte) 0);
    ByteArrayInputStream in = new ByteArrayInputStream(bogusData);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ShuffleUtils.shuffleToDisk(baos, "somehost", in, bogusData.length, 2000, mock(Logger.class), "identifier", false, 0, false);
    Assert.assertArrayEquals(bogusData, baos.toByteArray());
    // verify sending same stream of zeroes with validation generates an exception
    in.reset();
    try {
        ShuffleUtils.shuffleToDisk(mock(OutputStream.class), "somehost", in, bogusData.length, 2000, mock(Logger.class), "identifier", false, 0, true);
        Assert.fail("shuffle was supposed to throw!");
    } catch (IOException e) {
    }
}

79. DebugInfoBodyTest#jsonInputStreamContent()

Project: olingo-odata2
File: DebugInfoBodyTest.java
@Test
public void jsonInputStreamContent() throws Exception {
    ODataResponse response = mock(ODataResponse.class);
    ByteArrayInputStream in = new ByteArrayInputStream(STRING_CONTENT.getBytes());
    when(response.getEntity()).thenReturn(in);
    when(response.getContentHeader()).thenReturn(HttpContentType.TEXT_PLAIN);
    assertEquals(STRING_CONTENT_JSON, appendJson(response));
    in = new ByteArrayInputStream(STRING_CONTENT.getBytes("UTF-8"));
    when(response.getEntity()).thenReturn(in);
    when(response.getContentHeader()).thenReturn("image/png");
    assertEquals("\"" + Base64.encodeBase64String(STRING_CONTENT.getBytes("UTF-8")) + "\"", appendJson(response));
}

80. CassandraBinaryStoreTest#setUp()

Project: modeshape
File: CassandraBinaryStoreTest.java
@Before
public void setUp() throws Exception {
    if (exceptionDuringCassandraStart != null) {
        throw exceptionDuringCassandraStart;
    }
    store = new CassandraBinaryStore(ClusteringHelper.getLocalHost().getHostAddress());
    store.start();
    ByteArrayInputStream stream = new ByteArrayInputStream("Binary value".getBytes());
    aliveValue = store.storeValue(stream, false);
    ByteArrayInputStream stream2 = new ByteArrayInputStream("Binary value".getBytes());
    unusedValue = store.storeValue(stream2, false);
}

81. CmisConnectorIT#shouldCreateFolderAndDocument()

Project: modeshape
File: CmisConnectorIT.java
@Test
public void shouldCreateFolderAndDocument() throws Exception {
    Node root = getSession().getNode("/cmis");
    String name = "test" + System.currentTimeMillis();
    Node node = root.addNode(name, "nt:folder");
    assertTrue(name.equals(node.getName()));
    // node.setProperty("name", "test-name");
    root = getSession().getNode("/cmis/" + name);
    Node node1 = root.addNode("test-1", "nt:file");
    // System.out.println("Test: creating binary content");
    byte[] content = "Hello World".getBytes();
    ByteArrayInputStream bin = new ByteArrayInputStream(content);
    bin.reset();
    // System.out.println("Test: creating content node");
    Node contentNode = node1.addNode("jcr:content", "nt:resource");
    Binary binary = session.getValueFactory().createBinary(bin);
    contentNode.setProperty("jcr:data", binary);
    contentNode.setProperty("jcr:lastModified", Calendar.getInstance());
    getSession().save();
}

82. CmisConnector#jcrBinaryContent()

Project: modeshape
File: CmisConnector.java
/**
     * Creates content stream using JCR node.
     * 
     * @param document JCR node representation
     * @return CMIS content stream object
     */
private ContentStream jcrBinaryContent(Document document) {
    // pickup node properties
    Document props = document.getDocument("properties").getDocument(JcrLexicon.Namespace.URI);
    // extract binary value and content
    Binary value = props.getBinary("data");
    if (value == null) {
        return null;
    }
    byte[] content = value.getBytes();
    String fileName = props.getString("fileName");
    String mimeType = props.getString("mimeType");
    // wrap with input stream
    ByteArrayInputStream bin = new ByteArrayInputStream(content);
    bin.reset();
    // create content stream
    return new ContentStreamImpl(fileName, BigInteger.valueOf(content.length), mimeType, bin);
}

83. StatusResponsePacket#stringToIcon()

Project: MCProtocolLib
File: StatusResponsePacket.java
private BufferedImage stringToIcon(String str) throws IOException {
    if (str.startsWith("data:image/png;base64,")) {
        str = str.substring("data:image/png;base64,".length());
    }
    byte bytes[] = Base64.decode(str.getBytes("UTF-8"));
    ByteArrayInputStream in = new ByteArrayInputStream(bytes);
    BufferedImage icon = ImageIO.read(in);
    in.close();
    if (icon != null && (icon.getWidth() != 64 || icon.getHeight() != 64)) {
        throw new IOException("Icon must be 64x64.");
    }
    return icon;
}

84. LensContainerRequest#getFormData()

Project: lens
File: LensContainerRequest.java
/**
   * Utility method for reading form/multipart-form data from container request.
   *
   * @param clz Either Form.class or FormDataMultiPart.class
   * @param <T> clz type
   * @return an instance of T
   */
public <T> T getFormData(Class<T> clz) {
    InputStream in = containerRequest.getEntityStream();
    if (in.getClass() != ByteArrayInputStream.class) {
        // Buffer input
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            ReaderWriter.writeTo(in, baos);
        } catch (IOException e) {
            throw new IllegalArgumentException(e);
        }
        in = new ByteArrayInputStream(baos.toByteArray());
        containerRequest.setEntityStream(in);
    }
    ByteArrayInputStream bais = (ByteArrayInputStream) in;
    T f = containerRequest.readEntity(clz);
    bais.reset();
    return f;
}

85. DictionaryManager#save()

Project: kylin
File: DictionaryManager.java
void save(DictionaryInfo dict) throws IOException {
    ResourceStore store = MetadataManager.getInstance(config).getStore();
    String path = dict.getResourcePath();
    logger.info("Saving dictionary at " + path);
    ByteArrayOutputStream buf = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(buf);
    DictionaryInfoSerializer.FULL_SERIALIZER.serialize(dict, dout);
    dout.close();
    buf.close();
    ByteArrayInputStream inputStream = new ByteArrayInputStream(buf.toByteArray());
    store.putResource(path, inputStream, System.currentTimeMillis());
    inputStream.close();
}

86. MemcmpDecoderTest#testDecodeLong()

Project: kite
File: MemcmpDecoderTest.java
@Test
public void testDecodeLong() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new MemcmpDecoder(in);
    long i = decoder.readLong();
    assertEquals(1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new MemcmpDecoder(in);
    i = decoder.readLong();
    assertEquals(-1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new MemcmpDecoder(in);
    i = decoder.readLong();
    assertEquals(0L, i);
}

87. MemcmpDecoderTest#testDecodeInt()

Project: kite
File: MemcmpDecoderTest.java
@Test
public void testDecodeInt() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new MemcmpDecoder(in);
    int i = decoder.readInt();
    assertEquals(1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x7f, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new MemcmpDecoder(in);
    i = decoder.readInt();
    assertEquals(-1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x80, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new MemcmpDecoder(in);
    i = decoder.readInt();
    assertEquals(0, i);
}

88. ColumnDecoderTest#testDecodeLong()

Project: kite
File: ColumnDecoderTest.java
@Test
public void testDecodeLong() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new ColumnDecoder(in);
    long i = decoder.readLong();
    assertEquals(1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new ColumnDecoder(in);
    i = decoder.readLong();
    assertEquals(-1L, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new ColumnDecoder(in);
    i = decoder.readLong();
    assertEquals(0L, i);
}

89. ColumnDecoderTest#testDecodeInt()

Project: kite
File: ColumnDecoderTest.java
@Test
public void testDecodeInt() throws Exception {
    InputStream in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x01 });
    Decoder decoder = new ColumnDecoder(in);
    int i = decoder.readInt();
    assertEquals(1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, (byte) 0xff });
    decoder = new ColumnDecoder(in);
    i = decoder.readInt();
    assertEquals(-1, i);
    in = new ByteArrayInputStream(new byte[] { (byte) 0x00, (byte) 0x00, (byte) 0x00, (byte) 0x00 });
    decoder = new ColumnDecoder(in);
    i = decoder.readInt();
    assertEquals(0, i);
}

90. EntityEncodingManagerTest#testInternalInputTranslator()

Project: sakai
File: EntityEncodingManagerTest.java
public void testInternalInputTranslator() {
    String xml = "<" + TestData.PREFIX6 + "><stuff>TEST</stuff><number>5</number></" + TestData.PREFIX6 + ">";
    ByteArrayInputStream inputStream = new ByteArrayInputStream(xml.getBytes());
    MyEntity me = (MyEntity) entityEncodingManager.translateInputToEntity(new EntityReference(TestData.PREFIX6, ""), Formats.XML, inputStream, null);
    assertNotNull(me);
    assertEquals("TEST", me.getStuff());
    assertEquals(5, me.getNumber());
    // old sucky way String json = "{\""+TestData.PREFIX6+"\" : { \"stuff\" : \"TEST\", \"number\" : 5 }}";
    String json = "{ \"stuff\" : \"TEST\", \"number\" : 5 }";
    inputStream = new ByteArrayInputStream(json.getBytes());
    MyEntity me2 = (MyEntity) entityEncodingManager.translateInputToEntity(new EntityReference(TestData.PREFIX6, ""), Formats.JSON, inputStream, null);
    assertNotNull(me2);
    assertEquals("TEST", me2.getStuff());
    assertEquals(5, me2.getNumber());
}

91. EntityBrokerImplTest#testTranslateInputToEntity()

Project: sakai
File: EntityBrokerImplTest.java
@Test
public void testTranslateInputToEntity() {
    InputStream input = null;
    MyEntity me = null;
    // test creating an entity
    String reference = TestData.SPACE6;
    String format = Formats.XML;
    input = new ByteArrayInputStream(makeUTF8Bytes("<" + TestData.PREFIX6 + "><stuff>TEST</stuff><number>5</number></" + TestData.PREFIX6 + ">"));
    me = (MyEntity) entityBroker.translateInputToEntity(reference, format, input, null);
    assertNotNull(me);
    assertNull(me.getId());
    assertEquals("TEST", me.getStuff());
    assertEquals(5, me.getNumber());
    // test modifying an entity
    reference = TestData.REF6_2;
    input = new ByteArrayInputStream(makeUTF8Bytes("<" + TestData.PREFIX6 + "><id>" + TestData.IDS6[1] + "</id><stuff>TEST-PUT</stuff><number>8</number></" + TestData.PREFIX6 + ">"));
    me = (MyEntity) entityBroker.translateInputToEntity(reference, format, input, null);
    assertNotNull(me);
    assertNotNull(me.getId());
    assertEquals(TestData.IDS6[1], me.getId());
    assertEquals("TEST-PUT", me.getStuff());
    assertEquals(8, me.getNumber());
}

92. Transaction#createPartImage()

Project: qksms
File: Transaction.java
// create the image part to be stored in database
private static Uri createPartImage(Context context, String id, byte[] imageBytes, String mimeType) throws Exception {
    ContentValues mmsPartValue = new ContentValues();
    mmsPartValue.put("mid", id);
    mmsPartValue.put("ct", mimeType);
    mmsPartValue.put("cid", "<" + System.currentTimeMillis() + ">");
    Uri partUri = Uri.parse("content://mms/" + id + "/part");
    Uri res = context.getContentResolver().insert(partUri, mmsPartValue);
    // Add data to part
    OutputStream os = context.getContentResolver().openOutputStream(res);
    ByteArrayInputStream is = new ByteArrayInputStream(imageBytes);
    byte[] buffer = new byte[256];
    for (int len = 0; (len = is.read(buffer)) != -1; ) {
        os.write(buffer, 0, len);
    }
    os.close();
    is.close();
    return res;
}

93. Compresser#inflate()

Project: zstack
File: Compresser.java
public static byte[] inflate(byte[] input, int bufferSize) throws IOException {
    ByteArrayInputStream in = new ByteArrayInputStream(input);
    Inflater inf = new Inflater();
    InflaterInputStream iis = new InflaterInputStream(in, inf, bufferSize);
    ByteArrayOutputStream out = new ByteArrayOutputStream(input.length * 5);
    for (int c = iis.read(); c != -1; c = iis.read()) {
        out.write(c);
    }
    in.close();
    iis.close();
    byte[] ret = out.toByteArray();
    out.close();
    return ret;
}

94. DigestTest#testStreamable()

Project: JGroups
File: DigestTest.java
public void testStreamable() throws Exception {
    ByteArrayOutputStream outstream = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(outstream);
    d.writeTo(dos);
    dos.close();
    byte[] buf = outstream.toByteArray();
    ByteArrayInputStream instream = new ByteArrayInputStream(buf);
    DataInputStream dis = new DataInputStream(instream);
    Digest tmp = new Digest();
    tmp.readFrom(dis);
    Assert.assertEquals(d, tmp);
}

95. DiagnosticsHandler#authorizeProbeRequest()

Project: JGroups
File: DiagnosticsHandler.java
/**
     * Performs authorization on given DatagramPacket.
     *
     * @param packet to authorize
    * @return offset in DatagramPacket where request payload starts
    * @throws Exception thrown if passcode received from client does not match set passcode
    */
protected int authorizeProbeRequest(DatagramPacket packet) throws Exception {
    int offset = 0;
    ByteArrayInputStream bis = new ByteArrayInputStream(packet.getData());
    DataInputStream in = new DataInputStream(bis);
    long t1 = in.readLong();
    double q1 = in.readDouble();
    int length = in.readInt();
    byte[] digest = new byte[length];
    in.readFully(digest);
    offset = 8 + 8 + 4 + digest.length;
    byte[] local = Util.createDigest(passcode, t1, q1);
    if (!MessageDigest.isEqual(digest, local))
        throw new Exception("Authorization failed! Make sure correct passcode is used");
    else
        log.debug("Request authorized");
    return offset;
}

96. SPARQL_Update#executeForm()

Project: jena
File: SPARQL_Update.java
private void executeForm(HttpAction action) {
    String requestStr = action.request.getParameter(paramUpdate);
    if (requestStr == null)
        requestStr = action.request.getParameter(paramRequest);
    if (action.verbose)
        action.log.info(format("[%d] Form update = \n%s", action.id, requestStr));
    // A little ugly because we are taking a copy of the string, but hopefully shouldn't be too big if we are in this code-path
    // If we didn't want this additional copy, we could make the parser take a Reader in addition to an InputStream
    byte[] b = StrUtils.asUTF8bytes(requestStr);
    ByteArrayInputStream input = new ByteArrayInputStream(b);
    // free it early at least
    requestStr = null;
    execute(action, input);
    ServletOps.successPage(action, "Update succeeded");
}

97. SPARQL_Update#executeForm()

Project: jena
File: SPARQL_Update.java
private void executeForm(HttpAction action) {
    String requestStr = action.request.getParameter(paramUpdate);
    if (requestStr == null)
        requestStr = action.request.getParameter(paramRequest);
    if (action.verbose)
        //requestLog.info(format("[%d] Form update = %s", action.id, formatForLog(requestStr))) ;
        requestLog.info(format("[%d] Form update = \n%s", action.id, requestStr));
    // A little ugly because we are taking a copy of the string, but hopefully shouldn't be too big if we are in this code-path
    // If we didn't want this additional copy, we could make the parser take a Reader in addition to an InputStream
    byte[] b = StrUtils.asUTF8bytes(requestStr);
    ByteArrayInputStream input = new ByteArrayInputStream(b);
    // free it early at least
    requestStr = null;
    execute(action, input);
    successPage(action, "Update succeeded");
}

98. TestPeekInputStreamSource#make()

Project: jena
File: TestPeekInputStreamSource.java
@Override
PeekInputStream make(String contents, int size) {
    // Very carefuly ensure this is not a byte array-based PeekReader
    ByteArrayInputStream bin;
    try {
        bin = new ByteArrayInputStream(contents.getBytes("ASCII"));
    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
        return null;
    }
    return PeekInputStream.make(bin, size);
}

99. TestTurtleWriter#bnode_cycles()

Project: jena
File: TestTurtleWriter.java
@Test
public void bnode_cycles() {
    Model m = RDFDataMgr.loadModel("testing/DAWG-Final/construct/data-ident.ttl");
    Assert.assertTrue(m.size() > 0);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    RDFDataMgr.write(output, m, Lang.TURTLE);
    ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
    Model m2 = ModelFactory.createDefaultModel();
    RDFDataMgr.read(m2, input, Lang.TURTLE);
    Assert.assertTrue(m2.size() > 0);
    Assert.assertTrue(m.isIsomorphicWith(m2));
}

100. TestTurtleWriter#blankNodeLang()

Project: jena
File: TestTurtleWriter.java
/** Read in N-Triples data, which is not empty,
     *  then write-read-compare using the format given.
     *  
     * @param testdata
     * @param lang
     */
static void blankNodeLang(String testdata, RDFFormat lang) {
    StringReader r = new StringReader(testdata);
    Model m = ModelFactory.createDefaultModel();
    RDFDataMgr.read(m, r, null, RDFLanguages.NTRIPLES);
    Assert.assertTrue(m.size() > 0);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    RDFDataMgr.write(output, m, lang);
    ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
    Model m2 = ModelFactory.createDefaultModel();
    RDFDataMgr.read(m2, input, lang.getLang());
    Assert.assertTrue(m2.size() > 0);
    Assert.assertTrue(m.isIsomorphicWith(m2));
}