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
Source File: Account.java
View license
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. TestObrRecognition#testRejectOnRepositoryChildElementName()

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

3. TestObrRecognition#testRejectOnCapabilityChildElementName()

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

4. TestR5Recognition#testUndecidable()

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

5. TestR5Recognition#testAcceptOnCapabilityChildElementNames()

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

6. ECIESCoder#decrypt()

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

7. ECIESTest#decrypt()

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

8. OldAndroidByteArrayInputStreamTest#testByteArrayInputStream()

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

9. PreparedStatementTest#testSetBinaryStream()

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

10. PreparedStatementTest#testSetAsciiStream()

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

11. PreparedStatementTest#testSetBinaryStream()

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

12. PreparedStatementTest#testSetAsciiStream()

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

13. DataFormatConcurrentTest#unmarshal()

Project: camel
Source File: DataFormatConcurrentTest.java
View license
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
Source File: CompatibilityTest.java
View license
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
Source File: Verify.java
View license
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. TTextProtocolTest#tTextProtocolReadWriteTest()

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

17. StreamSourceDispatchTests#testOneWayPayloadMode()

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

18. ConsumersTest#testAsynchronousIOExceptionInConsumerOutputStream()

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

19. ConsumersTest#testAsynchronousOutOfMemoryErrorInConsumerOutputStream()

Project: bazel
Source File: ConsumersTest.java
View license
/**
   * 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#testAsynchronousErrorInConsumerOutputStream()

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

21. ConsumersTest#testAsynchronousRuntimeExceptionInConsumerOutputStream()

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

22. Filter#unpickle()

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

23. EncryptionKeyTest#testEncode()

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

24. XMLWindow#setXML()

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

25. PropertiesTest#testInternationalCharacters()

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

26. TestObrRecognition#testAcceptExtensionElementOtherNamespace()

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

27. BloomFilter#decode()

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

28. DecoderTest#testBinaryDecoding()

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

29. ColumnDecoderTest#testDecodeInt()

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

30. ColumnDecoderTest#testDecodeLong()

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

31. MemcmpDecoderTest#testDecodeInt()

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

32. MemcmpDecoderTest#testDecodeLong()

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

33. UIManager#parseImage()

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

34. TTextProtocolTest#tTextProtocolReadWriteTest()

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

35. DiffModelTest#testDuplicateModels()

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

36. DiffModelTest#testIncUpdateTitleDescription()

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

37. DiffModelTest#testNonIncUpdateDefaultAspectAdded()

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

38. DiffModelTest#testIncUpdatePropertiesAddedToMandatoryAspect()

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

39. DiffModelTest#testNonIncUpdatePropertiesRemovedFromMandatoryAspect()

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

40. ModelBatchTest#testProtoBatch()

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

41. ModelBatchTest#testProtoBatchModifier()

Project: CoreNLP
Source File: ModelBatchTest.java
View license
@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#testProtoBatchWithoutFactors()

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

43. InputStreamUtilTest#testSkipFully()

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

44. UtilsTest#testFill()

Project: dfs-datastores
Source File: UtilsTest.java
View license
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]);
    }
}

45. Util#main()

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

46. ReportModeller#writeToFile()

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

47. SerializerUtilsTest#testChannelWritelong()

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

48. SerializerUtilsTest#testChannelWriteString()

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

49. TlvUtilTest#testSearchTagByIdIn()

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

50. TestXMLRead#testRead()

Project: encog-java-core
Source File: TestXMLRead.java
View license
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. SerializeRoundTrip#roundTrip()

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

52. LineReadingInputStreamTest#testBothImplementation()

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

53. ConsoleServiceTest#shouldReturnConsoleUpdates()

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

54. ChainingClassLoaderTest#getResourceAsStreamReturnsStreamFromChildClassLoader()

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

55. TestOpenFilesInfo#testSerialize()

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

56. BitmapUtils#imageBytes2Bitmap()

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

57. Bytes#split()

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

58. OldInputStreamReaderTest#setUp()

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

59. SerializationTest#testInvalidXmlThrowsInvalidSerializedDataException()

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

60. DataStoreTextWriterTest#basicOperation()

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

61. IOUtilsBehaviour#shouldProcessInputStream()

Project: jbehave-core
Source File: IOUtilsBehaviour.java
View license
// 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));
}

62. JbpmSerializationHelper#deserializeKnowledgeSession()

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

63. MarshalledObject#get()

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

64. TestResultSetIO#test_resultset_01()

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

65. IpAddressTest#testIPv6WithStreamable()

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

66. IpAddressTest#testStreamableWithHighPort()

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

67. ColumnDecoderTest#testDecodeInt()

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

68. ColumnDecoderTest#testDecodeLong()

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

69. MemcmpDecoderTest#testDecodeInt()

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

70. MemcmpDecoderTest#testDecodeLong()

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

71. DictionaryManager#save()

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

72. LensContainerRequest#getFormData()

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

73. StatusResponsePacket#stringToIcon()

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

74. CmisConnector#jcrBinaryContent()

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

75. CmisConnectorIT#shouldCreateFolderAndDocument()

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

76. CassandraBinaryStoreTest#setUp()

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

77. DebugInfoBodyTest#jsonInputStreamContent()

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

78. MarshalledObject#get()

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

79. SubjectNullTests#deserializeBuffer()

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

80. Verify#setup()

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

81. TestConfiguration#testSerialization()

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

82. JPEGFactory#createFromStream()

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

83. JPEGFactory#createFromStream()

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

84. GZIPCompressionProviderTest#testCreateInputStream()

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

85. PreparedStatementTest#testBinaryStreamErrorsRestartable()

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

86. Transaction#createPartImage()

Project: qksms
Source File: Transaction.java
View license
// 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;
}

87. EntityBrokerImplTest#testTranslateInputToEntity()

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

88. EntityEncodingManagerTest#testInternalInputTranslator()

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

89. TestShuffleUtils#testShuffleToDiskChecksum()

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

90. TestIFile#testCompressedFlag()

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

91. TwitterTest#assertDeserializedFormIsNotEqual()

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

92. XmiCasDeserializerTest#testDuplicateNsPrefixes()

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

93. Compresser#inflate()

Project: zstack
Source File: Compresser.java
View license
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. Create#write()

Project: activemq-artemis
Source File: Create.java
View license
private void write(String source, File target, HashMap<String, String> filters, boolean unixTarget) throws Exception {
    if (target.exists() && !force) {
        throw new CLIException(String.format("The file '%s' already exists.  Use --force to overwrite.", target));
    }
    String content = applyFilters(readTextFile(source), filters);
    // and then writing out in the new target encoding..  Let's also replace \n with the values
    // that is correct for the current platform.
    String separator = unixTarget && IS_CYGWIN ? "\n" : System.getProperty("line.separator");
    content = content.replaceAll("\\r?\\n", Matcher.quoteReplacement(separator));
    ByteArrayInputStream in = new ByteArrayInputStream(content.getBytes(encoding));
    try (FileOutputStream fout = new FileOutputStream(target)) {
        copy(in, fout);
    }
}

95. ConnectionFactoryURITest#persistIP6()

View license
private void persistIP6(String ipv6, ActiveMQConnectionFactory factory) throws IOException, ClassNotFoundException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (ObjectOutputStream outStream = new ObjectOutputStream(baos)) {
        outStream.writeObject(factory);
    } finally {
        baos.close();
    }
    try (ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream in = new ObjectInputStream(bais)) {
        factory = (ActiveMQConnectionFactory) in.readObject();
    }
    Assert.assertEquals("[" + ipv6 + "]", factory.getStaticConnectors()[0].getParams().get("host"));
}

96. FileConfigurationParserTest#testParsingClusterConnectionURIs()

View license
@Test
public void testParsingClusterConnectionURIs() throws Exception {
    FileConfigurationParser parser = new FileConfigurationParser();
    String configStr = firstPart + "<cluster-connections>\n" + "   <cluster-connection-uri name=\"my-cluster\" address=\"multicast://my-discovery-group?messageLoadBalancingType=STRICT;retryInterval=333;connectorName=netty-connector;maxHops=1\"/>\n" + "</cluster-connections>\n" + lastPart;
    ByteArrayInputStream input = new ByteArrayInputStream(configStr.getBytes(StandardCharsets.UTF_8));
    Configuration config = parser.parseMainConfig(input);
    Assert.assertEquals(1, config.getClusterConfigurations().size());
    Assert.assertEquals("my-discovery-group", config.getClusterConfigurations().get(0).getDiscoveryGroupName());
    Assert.assertEquals(333, config.getClusterConfigurations().get(0).getRetryInterval());
}

97. VersionImplTest#testSerialize()

View license
@Test
public void testSerialize() throws Exception {
    VersionImpl version = new VersionImpl("uyiuy", 3, 7, 6, 12, new int[] { 9, 10, 11, 12 });
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(version);
    oos.flush();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    VersionImpl version2 = (VersionImpl) ois.readObject();
    Assert.assertTrue(version.equals(version2));
}

98. ActiveMQConnectionFactoryTest#testFactorySerializable()

View license
public void testFactorySerializable() throws Exception {
    String clientID = "TestClientID";
    ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory();
    cf.setClientID(clientID);
    ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
    ObjectOutputStream objectsOut = new ObjectOutputStream(bytesOut);
    objectsOut.writeObject(cf);
    objectsOut.flush();
    byte[] data = bytesOut.toByteArray();
    ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
    ObjectInputStream objectsIn = new ObjectInputStream(bytesIn);
    cf = (ActiveMQConnectionFactory) objectsIn.readObject();
    assertEquals(cf.getClientID(), clientID);
}

99. DataFileGeneratorTestSupport#testGenerateAndReParsingIsTheSame()

View license
public void testGenerateAndReParsingIsTheSame() throws Exception {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    DataOutputStream ds = new DataOutputStream(buffer);
    Object expected = createObject();
    LOG.info("Created: " + expected);
    openWireformat.marshal(expected, ds);
    ds.close();
    // now lets try parse it back again
    ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray());
    DataInputStream dis = new DataInputStream(in);
    Object actual = openWireformat.unmarshal(dis);
    assertBeansEqual("", new HashSet<>(), expected, actual);
    LOG.info("Parsed: " + actual);
}

100. NumberRangesWhileMarshallingTest#testMaxFrameSize()

View license
public void testMaxFrameSize() throws Exception {
    OpenWireFormat wf = new OpenWireFormat();
    wf.setMaxFrameSize(10);
    ActiveMQTextMessage msg = new ActiveMQTextMessage();
    msg.setText("This is a test");
    writeObject(msg);
    ds.writeInt(endOfStreamMarker);
    // now lets read from the stream
    ds.close();
    ByteArrayInputStream in = new ByteArrayInputStream(buffer.toByteArray());
    DataInputStream dis = new DataInputStream(in);
    try {
        wf.unmarshal(dis);
    } catch (IOException ioe) {
        return;
    }
    fail("Should fail because of the large frame size");
}