Java Code Examples for java.io.ByteArrayInputStream.close()

The following are Jave code examples for showing how to use close() of the java.io.ByteArrayInputStream class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: firebase-admin-java   File: FirebaseCredentialsTest.java   View Source Code Vote up 6 votes
@Test
public void certificateReadIsDoneSynchronously()
    throws ExecutionException, InterruptedException, IOException {
  MockTokenServerTransport transport = new MockTokenServerTransport();
  transport.addServiceAccount(ServiceAccount.EDITOR.getEmail(), ACCESS_TOKEN);

  ByteArrayInputStream inputStream =
      new ByteArrayInputStream(
          ServiceAccount.EDITOR.asString().getBytes(Charset.defaultCharset()));

  FirebaseCredential credential =
      FirebaseCredentials.fromCertificate(inputStream, transport, Utils.getDefaultJsonFactory());

  Assert.assertEquals(0, inputStream.available());
  inputStream.close();

  Assert.assertNotNull(((BaseCredential) credential).getGoogleCredentials());
  Assert.assertEquals(ACCESS_TOKEN, Tasks.await(credential.getAccessToken()).getAccessToken());
}
 
Example 2
Project: jrpip   File: ByteUtils.java   View Source Code Vote up 6 votes
public static Object convertBytesToObject(byte[] input) throws IOException, ClassNotFoundException
{
    ByteArrayInputStream bis = new ByteArrayInputStream(input);
    FixedInflaterInputStream zis = null;
    Object result = null;
    try
    {
        zis = new FixedInflaterInputStream(bis);
        ObjectInputStream ois = new ObjectInputStream(zis);
        result = ois.readObject();
        ois.close();
        zis.finish();
        zis.close();
        zis = null;
        bis.close();
    }
    finally
    {
        if (zis != null)
        {
            zis.finish();
        }
    }
    return result;
}
 
Example 3
Project: incubator-netbeans   File: NbObjectInputStream.java   View Source Code Vote up 6 votes
/** Reads an object from the given object input.
* The object had to be saved by the {@link NbObjectOutputStream#writeSafely} method.
*
* @param oi object input
* @return the read object
* @exception IOException if IO error occured
* @exception SafeException if the operation failed but the stream is ok
*    for further reading
*/
public static Object readSafely(ObjectInput oi) throws IOException {
    int size = oi.readInt();
    byte[] byteArray = new byte[size];
    oi.readFully(byteArray, 0, size);

    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(byteArray);
        NbObjectInputStream ois = new NbObjectInputStream(bis);
        Object obj = ois.readObject();
        bis.close();

        return obj;
    } catch (Exception exc) {
        // encapsulate all exceptions into safe exception
        throw new SafeException(exc);
    } catch (LinkageError le) {
        throw new SafeException(new InvocationTargetException(le));
    }
}
 
Example 4
Project: cyberduck   File: OneDriveWriteFeatureTest.java   View Source Code Vote up 6 votes
@Test
public void testWriteZeroLength() throws Exception {
    final OneDriveWriteFeature feature = new OneDriveWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(0);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 5
Project: jodis-client   File: CacheUtils.java   View Source Code Vote up 6 votes
/**
 * 
 * 功能描述:自己数组转换成对象 <br>
 * 〈功能详细描述〉
 *
 * @param bytes bytes
 * @return object
 * @throws IOException ioexception
 * @see [相关类/方法](可选)
 * @since [产品/模块版本](可选)
 */
public static Object byteArrayToObject(byte[] bytes) throws IOException {
    if (bytes == null || bytes.length <= 0) {
        return null;
    }
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bis));
        obj = ois.readObject();
        bis.close();
        ois.close();
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
    }
    return obj;
}
 
Example 6
Project: onolisa   File: SessionStreamUtils.java   View Source Code Vote up 6 votes
/**
 * 
 * 功能描述:自己数组转换成对象 <br>
 * 〈功能详细描述〉
 *
 * @param bytes bytes
 * @return object
 * @throws IOException ioexception
 * @see [相关类/方法](可选)
 * @since [产品/模块版本](可选)
 */
public static Object byteArrayToObject(byte[] bytes) throws IOException {
    if (bytes == null || bytes.length <= 0) {
        return null;
    }
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bis));
        obj = ois.readObject();
        bis.close();
        ois.close();
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
    }
    return obj;
}
 
Example 7
Project: redis-client   File: CacheUtils.java   View Source Code Vote up 6 votes
/**
 * 
 * 功能描述:自己数组转换成对象 <br>
 * 〈功能详细描述〉
 * 
 * @param bytes
 *            bytes
 * @return object
 * @throws IOException
 *             ioexception
 * @see [相关类/方法](可选)
 * @since [产品/模块版本](可选)
 */
public static Object byteArrayToObject(byte[] bytes) throws IOException {
    if (bytes == null || bytes.length <= 0) {
        return null;
    }
    Object obj = null;
    try {
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInputStream ois = new ObjectInputStream(new BufferedInputStream(bis));
        obj = ois.readObject();
        bis.close();
        ois.close();
    } catch (ClassNotFoundException e) {
        logger.error(e.getMessage());
    }
    return obj;
}
 
Example 8
Project: cyberduck   File: OneDriveWriteFeatureTest.java   View Source Code Vote up 6 votes
@Test
public void testWrite() throws Exception {
    final OneDriveWriteFeature feature = new OneDriveWriteFeature(session);
    final Path container = new OneDriveHomeFinderFeature(session).find();
    final byte[] content = RandomUtils.nextBytes(5 * 1024 * 1024);
    final TransferStatus status = new TransferStatus();
    status.setLength(content.length);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<Void> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    final byte[] buffer = new byte[32 * 1024];
    assertEquals(content.length, IOUtils.copyLarge(in, out, buffer));
    in.close();
    out.close();
    assertNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new OneDriveReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new OneDriveDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 9
Project: redirector   File: SelectServerTemplate.java   View Source Code Vote up 5 votes
protected SelectServer unmarshalJsonStringObject(String jsonStringObject) throws java.io.IOException {
    MessageBodyReader<SelectServer> messageBodyReader = getJsonMessageBodyReader();
    ByteArrayInputStream bais = new ByteArrayInputStream(jsonStringObject.getBytes());
    SelectServer responseObject = messageBodyReader.readFrom(SelectServer.class, SelectServer.class, SelectServer.class.getAnnotations(), null, null, bais);
    bais.close();
    return responseObject;
}
 
Example 10
Project: incubator-servicecomb-java-chassis   File: TestProduceJsonProcessor.java   View Source Code Vote up 5 votes
@Test
public void testStreamNormal() throws Exception {
  String value = "abc";
  ByteArrayOutputStream os = new ByteArrayOutputStream();

  pp.encodeResponse(os, value);
  Assert.assertEquals("\"abc\"", os.toString(StandardCharsets.UTF_8.name()));

  ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
  Object result = pp.decodeResponse(is, stringType);
  Assert.assertEquals(value, result);

  os.close();
  is.close();
}
 
Example 11
Project: cyberduck   File: B2LargeUploadWriteFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteZeroLength() throws Exception {
    final B2Session session = new B2Session(
            new Host(new B2Protocol(), new B2Protocol().getDefaultHostname(),
                    new Credentials(
                            System.getProperties().getProperty("b2.user"), System.getProperties().getProperty("b2.key")
                    )));
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final B2LargeUploadWriteFeature feature = new B2LargeUploadWriteFeature(session);
    final Path container = new Path("test-cyberduck", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final byte[] content = RandomUtils.nextBytes(0);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final StatusOutputStream<VersionId> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNotNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new B2ReadFeature(session).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new B2DeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 12
Project: incubator-netbeans   File: XmlFileEncodingQueryImpl.java   View Source Code Vote up 5 votes
private String getEncoding () throws IOException {
    byte[] arr = buffer.array();
    ByteArrayInputStream in = new ByteArrayInputStream (arr);
    try {
        return EncodingUtil.detectEncoding(in);
    }            
    finally {
        in.close();                
    }
}
 
Example 13
Project: incubator-netbeans   File: HtmlDataObject.java   View Source Code Vote up 5 votes
private String getEncoding () throws IOException {
    byte[] arr = buffer.array();
    ByteArrayInputStream in = new ByteArrayInputStream (arr);
    try {
        return getFileEncoding(in);
    }
    finally {
        in.close();
    }
}
 
Example 14
Project: cyberduck   File: SwiftLargeUploadWriteFeatureTest.java   View Source Code Vote up 5 votes
@Test
public void testWriteZeroLength() throws Exception {
    final Host host = new Host(new SwiftProtocol(), "identity.api.rackspacecloud.com", new Credentials(
            System.getProperties().getProperty("rackspace.key"), System.getProperties().getProperty("rackspace.secret")
    ));
    final SwiftSession session = new SwiftSession(host);
    session.open(new DisabledHostKeyCallback(), new DisabledLoginCallback());
    session.login(new DisabledPasswordStore(), new DisabledLoginCallback(), new DisabledCancelCallback());
    final SwiftRegionService regionService = new SwiftRegionService(session);
    final SwiftLargeUploadWriteFeature feature = new SwiftLargeUploadWriteFeature(session, regionService,
            new SwiftSegmentService(session, ".segments-test/"));
    final Path container = new Path("test.cyberduck.ch", EnumSet.of(Path.Type.directory, Path.Type.volume));
    final byte[] content = RandomUtils.nextBytes(0);
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);
    final Path file = new Path(container, new AlphanumericRandomStringService().random(), EnumSet.of(Path.Type.file));
    final HttpResponseOutputStream<List<StorageObject>> out = feature.write(file, status, new DisabledConnectionCallback());
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    assertEquals(content.length, IOUtils.copyLarge(in, out));
    in.close();
    out.close();
    assertNotNull(out.getStatus());
    assertTrue(new DefaultFindFeature(session).find(file));
    final byte[] compare = new byte[content.length];
    final InputStream stream = new SwiftReadFeature(session, regionService).read(file, new TransferStatus().length(content.length), new DisabledConnectionCallback());
    IOUtils.readFully(stream, compare);
    stream.close();
    assertArrayEquals(content, compare);
    new SwiftDeleteFeature(session).delete(Collections.singletonList(file), new DisabledLoginCallback(), new Delete.DisabledCallback());
}
 
Example 15
Project: Nird2   File: BriarIntegrationTest.java   View Source Code Vote up 5 votes
private void syncMessage(SyncSessionFactory fromSync, ContactId fromId,
		SyncSessionFactory toSync, ContactId toId, int num, boolean valid)
		throws IOException, TimeoutException {

	// Debug output
	String from = "0";
	if (fromSync == sync1) from = "1";
	else if (fromSync == sync2) from = "2";
	String to = "0";
	if (toSync == sync1) to = "1";
	else if (toSync == sync2) to = "2";
	LOG.info("TEST: Sending message from " + from + " to " + to);

	ByteArrayOutputStream out = new ByteArrayOutputStream();
	// Create an outgoing sync session
	SyncSession sessionFrom =
			fromSync.createSimplexOutgoingSession(toId, TestPluginConfigModule.MAX_LATENCY, out);
	// Write whatever needs to be written
	sessionFrom.run();
	out.close();

	ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
	// Create an incoming sync session
	SyncSession sessionTo = toSync.createIncomingSession(fromId, in);
	// Read whatever needs to be read
	sessionTo.run();
	in.close();

	if (valid) {
		deliveryWaiter.await(TIMEOUT, num);
	} else {
		validationWaiter.await(TIMEOUT, num);
	}
}
 
Example 16
Project: monarch   File: JavaSerializationJUnitTest.java   View Source Code Vote up 5 votes
private void verifyJavaSerialization(Object obj) throws Exception {
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  ObjectOutputStream out = new ObjectOutputStream(baos);
  out.writeObject(obj);
  out.close();
  baos.close();
  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
  ObjectInputStream in = new ObjectInputStream(bais);
  Object obj2 = in.readObject();
  in.close();
  bais.close();
  assert (obj.equals(obj2));
}
 
Example 17
Project: open-kilda   File: ByteArraySerializer.java   View Source Code Vote up 5 votes
@Override
default Object deserialize() throws IOException, ClassNotFoundException {
    ByteArrayInputStream bais = new ByteArrayInputStream(byteBuffer.array());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Object obj = ois.readObject();
    ois.close();
    bais.close();
    byteBuffer.clear();
    return obj;
}
 
Example 18
Project: ProyectoPacientes   File: ResultSetImpl.java   View Source Code Vote up 5 votes
private Object getObjectDeserializingIfNeeded(int columnIndex) throws SQLException {
    final Field field = this.fields[columnIndex - 1];

    if (field.isBinary() || field.isBlob()) {
        byte[] data = getBytes(columnIndex);

        if (this.connection.getAutoDeserialize()) {
            Object obj = data;

            if ((data != null) && (data.length >= 2)) {
                if ((data[0] == -84) && (data[1] == -19)) {
                    // Serialized object?
                    try {
                        ByteArrayInputStream bytesIn = new ByteArrayInputStream(data);
                        ObjectInputStream objIn = new ObjectInputStream(bytesIn);
                        obj = objIn.readObject();
                        objIn.close();
                        bytesIn.close();
                    } catch (ClassNotFoundException cnfe) {
                        throw SQLError.createSQLException(Messages.getString("ResultSet.Class_not_found___91") + cnfe.toString()
                                + Messages.getString("ResultSet._while_reading_serialized_object_92"), getExceptionInterceptor());
                    } catch (IOException ex) {
                        obj = data; // not serialized?
                    }
                } else {
                    return getString(columnIndex);
                }
            }

            return obj;
        }

        return data;
    }

    return getBytes(columnIndex);
}
 
Example 19
Project: AI-Powered-Intelligent-Banking-Platform   File: AvsSpeakItem.java   View Source Code Vote up 4 votes
public AvsSpeakItem(String token, String cid, ByteArrayInputStream audio) throws IOException {
    this(token, cid, IOUtils.toByteArray(audio));
    audio.close();
}
 
Example 20
Project: openjdk-jdk10   File: SupplementaryChars.java   View Source Code Vote up 4 votes
@Test(dataProvider = "unsupported", expectedExceptions = SAXParseException.class)
public void testInvalid(String xml) throws Exception {
    ByteArrayInputStream stream = new ByteArrayInputStream(xml.getBytes("UTF-8"));
    getParser().parse(stream, new DefaultHandler());
    stream.close();
}