Example usage for java.io ByteArrayInputStream close

List of usage examples for java.io ByteArrayInputStream close

Introduction

In this page you can find the example usage for java.io ByteArrayInputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closing a ByteArrayInputStream has no effect.

Usage

From source file:com.vsct.dt.hesperides.feedback.FeedbacksAggregate.java

private void writeImage(String pathImageName, String imageString) {

    // create a buffered image
    BufferedImage bufferedImage;/*from   www  . ja v  a2  s  .c  om*/
    byte[] imageByte;

    try {
        BASE64Decoder decoder = new BASE64Decoder();
        imageByte = decoder.decodeBuffer(imageString);
        ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
        bufferedImage = ImageIO.read(bis);
        bis.close();

        File imageDirectory = new File(pathImageName).getParentFile();
        if (!imageDirectory.exists()) {
            imageDirectory.mkdirs();
        }

        // write the image to a file
        FileOutputStream outputfile = new FileOutputStream(pathImageName, false);
        ImageIO.write(bufferedImage, "png", outputfile);

        outputfile.close();

    } catch (IOException e1) {
        e1.printStackTrace();
    }
}

From source file:com.heliosapm.tsdblite.json.JSON.java

private static Object jdeserialize(final byte[] bytes) {
    if (bytes == null || bytes.length == 0)
        return null;
    ByteArrayInputStream bais = null;
    ObjectInputStream ois = null;
    try {/*  w  ww  . j  a  v  a 2  s.  com*/
        bais = new ByteArrayInputStream(bytes);
        ois = new ObjectInputStream(bais);
        return ois.readObject();
    } catch (Exception ex) {
        throw new RuntimeException(ex);
    } finally {
        if (ois != null)
            try {
                ois.close();
            } catch (Exception x) {
                /* No Op */}
        if (bais != null)
            try {
                bais.close();
            } catch (Exception x) {
                /* No Op */}
    }
}

From source file:org.limy.lrd.deploy.FtpDeployer.java

/**
 * FTP????/*from w  w  w .  ja v  a 2s.c o  m*/
 * @param path ???
 * @param contents 
 * @throws IOException I/O
 * @throws LrdException 
 */
private void deployByteContents(String path, byte[] contents) throws IOException, LrdException {

    ByteArrayInputStream inputStream = new ByteArrayInputStream(contents);
    boolean success;
    try {
        success = FtpUtils.uploadFileFtp(client, ftpInfo.getPath(), path, inputStream);
    } finally {
        inputStream.close();
    }

    if (!success) {
        // ?
        LOG.debug("Fail to upload : " + path);
        throw new LrdException(path + " ??????");
    }
}

From source file:org.eclipse.smila.ontology.test.TestSesameConfig.java

/**
 * test of configuration creation./*from   ww  w .j a  va  2 s. c om*/
 *
 * @throws Exception
 *           test fails
 */
public void testWrite() throws Exception {
    final SesameConfiguration config = createTestConfig();

    final ByteArrayOutputStream out = new ByteArrayOutputStream();
    SesameConfigurationHandler.writeConfiguration(config, out);
    out.close();
    if (_log.isDebugEnabled()) {
        _log.debug(new String(out.toByteArray()));
    }
    final ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    final SesameConfiguration readConfig = SesameConfigurationHandler.readConfiguration(in);
    in.close();

    assertNotNull(readConfig);
    assertEquals(config.getDefault(), readConfig.getDefault());

    assertNotNull(readConfig.getRepositoryConfig());
    assertEquals(config.getRepositoryConfig().size(), config.getRepositoryConfig().size());

    for (int i = 0; i < config.getRepositoryConfig().size(); i++) {
        final RepositoryConfig expRepo = config.getRepositoryConfig().get(i);
        final RepositoryConfig readRepo = readConfig.getRepositoryConfig().get(i);
        assertEquals(expRepo.getName(), readRepo.getName());
        assertTrue((expRepo.getNativeStore() == null) == (readRepo.getNativeStore() == null));
        assertTrue((expRepo.getMemoryStore() == null) == (readRepo.getMemoryStore() == null));
        assertTrue((expRepo.getRdbmsStore() == null) == (readRepo.getRdbmsStore() == null));
        assertTrue((expRepo.getHttpStore() == null) == (readRepo.getHttpStore() == null));
        assertEquals(expRepo.getStackable().size(), readRepo.getStackable().size());
    }

    final Iterator<RepositoryConfig> expIter = config.getRepositoryConfig().iterator();
    final Iterator<RepositoryConfig> readIter = readConfig.getRepositoryConfig().iterator();
    final RepositoryConfig expMemRepo = expIter.next();
    final MemoryStore expMem = expMemRepo.getMemoryStore();
    final RepositoryConfig readMemRepo = readIter.next();
    final MemoryStore readMem = readMemRepo.getMemoryStore();
    assertEquals(expMem.isPersist(), readMem.isPersist());
    assertEquals(expMem.getSyncDelay(), readMem.getSyncDelay());
    assertEquals(expMemRepo.getStackable().get(0).getClassname(),
            readMemRepo.getStackable().get(0).getClassname());
    assertEquals(expMemRepo.getStackable().get(1).getClassname(),
            readMemRepo.getStackable().get(1).getClassname());

    final NativeStore expNative = expIter.next().getNativeStore();
    final NativeStore readNative = readIter.next().getNativeStore();
    assertEquals(expNative.isForceSync(), readNative.isForceSync());
    assertEquals(expNative.getIndexes(), readNative.getIndexes());

    final RdbmsStore expDb = expIter.next().getRdbmsStore();
    final RdbmsStore readDb = readIter.next().getRdbmsStore();
    assertEquals(expDb.getDriver(), readDb.getDriver());
    assertEquals(expDb.getUrl(), readDb.getUrl());
    assertEquals(expDb.getUser(), readDb.getUser());
    assertEquals(expDb.getPassword(), readDb.getPassword());
    assertEquals(expDb.isIndexed(), readDb.isIndexed());
    assertEquals(expDb.isSequenced(), readDb.isSequenced());
    assertEquals(expDb.getMaxTripleTables(), readDb.getMaxTripleTables());

    final HttpStore expHttp = expIter.next().getHttpStore();
    final HttpStore readHttp = readIter.next().getHttpStore();
    assertEquals(expHttp.getRepositoryId(), readHttp.getRepositoryId());
    assertEquals(expHttp.getUrl(), readHttp.getUrl());
    assertEquals(expHttp.getUser(), readHttp.getUser());
    assertEquals(expHttp.getPassword(), readHttp.getPassword());
}

From source file:org.apache.stratos.mock.iaas.persistence.RegistryManager.java

/**
 * Deserialize a byte array and retrieve the object.
 *
 * @param bytes bytes to be deserialized
 * @return the deserialized {@link Object}
 * @throws Exception if the deserialization is failed.
 *//*  w w  w . ja v a 2 s.  co m*/
private Object deserializeFromByteArray(byte[] bytes) throws Exception {

    ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
    ObjectInput in = null;
    try {
        in = new ObjectInputStream(bis);
        return in.readObject();
    } finally {
        bis.close();
        if (in != null) {
            in.close();
        }
    }
}

From source file:ch.cyberduck.core.openstack.SwiftLargeUploadWriteFeatureTest.java

@Test
public void testWriteUploadLargeBuffer() 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());
    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));
    container.attributes().setRegion("DFW");
    final TransferStatus status = new TransferStatus();
    status.setLength(-1L);/*w ww. j  av  a  2  s  . c om*/
    final Path file = new Path(container, UUID.randomUUID().toString(), EnumSet.of(Path.Type.file));
    final OutputStream out = feature.write(file, status, new DisabledConnectionCallback());
    final byte[] content = RandomUtils.nextBytes(6 * 1024 * 1024);
    final ByteArrayInputStream in = new ByteArrayInputStream(content);
    final TransferStatus progress = new TransferStatus();
    new StreamCopier(new TransferStatus(), progress).transfer(in, out);
    assertEquals(content.length, progress.getOffset());
    in.close();
    out.close();
    assertTrue(new SwiftFindFeature(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());
    session.close();
}

From source file:org.jaqpot.algorithms.resource.Standarization.java

@POST
@Path("prediction")
public Response prediction(PredictionRequest request) {
    try {/*w w  w.  java2 s .  c o  m*/
        if (request.getDataset().getDataEntry().isEmpty()
                || request.getDataset().getDataEntry().get(0).getValues().isEmpty()) {
            return Response.status(Response.Status.BAD_REQUEST)
                    .entity("Dataset is empty. Cannot make predictions on empty dataset.").build();
        }
        List<String> features = request.getDataset().getDataEntry().stream().findFirst().get().getValues()
                .keySet().stream().collect(Collectors.toList());
        String base64Model = (String) request.getRawModel();
        byte[] modelBytes = Base64.getDecoder().decode(base64Model);
        ByteArrayInputStream bais = new ByteArrayInputStream(modelBytes);
        ObjectInput in = new ObjectInputStream(bais);
        ScalingModel model = (ScalingModel) in.readObject();
        in.close();
        bais.close();

        List<LinkedHashMap<String, Object>> predictions = new ArrayList<>();

        for (DataEntry dataEntry : request.getDataset().getDataEntry()) {
            LinkedHashMap<String, Object> data = new LinkedHashMap<>();
            for (String feature : features) {
                Double stdev = model.getMaxValues().get(feature);
                Double mean = model.getMinValues().get(feature);
                Double value = Double.parseDouble(dataEntry.getValues().get(feature).toString());
                if (stdev != null && stdev != 0.0 && mean != null) {
                    value = (value - mean) / stdev;
                } else {
                    value = 1.0;
                }
                data.put("Standarized " + feature, value);
            }
            predictions.add(data);
        }

        PredictionResponse response = new PredictionResponse();
        response.setPredictions(predictions);

        return Response.ok(response).build();
    } catch (Exception ex) {
        LOG.log(Level.SEVERE, null, ex);
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(ex.getMessage()).build();
    }
}

From source file:com.wabacus.config.database.type.AbsDatabaseType.java

public void setBlobValue(int iindex, byte[] value, PreparedStatement pstmt) throws SQLException {
    if (value == null) {
        pstmt.setBinaryStream(iindex, null, 0);
    } else {//from   www  .j  a  va  2s . c om
        try {
            ByteArrayInputStream in = Tools.getInputStreamFromBytesArray(value);
            pstmt.setBinaryStream(iindex, in, in.available());
            in.close();
        } catch (IOException e) {
            throw new WabacusRuntimeException("??", e);
        }
    }
}

From source file:com.adaptris.core.MimeEncoder.java

/**
 * Convenience method that is available so that existing underlying
 * implementations are not broken due to the AdaptrisMessageEncoder interface
 * change./*  w  w  w.  j a v a2 s .  c o  m*/
 *
 * @param bytes the bytes to decode.
 * @return the AdaptrisMessage.
 * @throws CoreException wrapping any underyling exception.
 */
public AdaptrisMessage decode(byte[] bytes) throws CoreException {
    AdaptrisMessage msg = null;
    ByteArrayInputStream in = null;
    try {
        in = new ByteArrayInputStream(bytes);
        msg = readMessage(in);
        in.close();
    } catch (IOException e) {
        throw new CoreException(e);
    }
    return msg;
}

From source file:com.krawler.common.util.ByteUtil.java

/**
 * uncompress the supplied data using GZIPInputStream and return the
 * uncompressed data./*ww w  .  j a v a 2 s .com*/
 * 
 * @param data
 *            data to uncompress
 * @return uncompressed data
 */
public static byte[] uncompress(byte[] data) throws IOException {
    // TODO: optimize, this makes my head hurt
    ByteArrayOutputStream baos = null;
    ByteArrayInputStream bais = null;
    GZIPInputStream gis = null;
    try {
        int estimatedResultSize = data.length * 3;
        baos = new ByteArrayOutputStream(estimatedResultSize);
        bais = new ByteArrayInputStream(data);
        byte[] buffer = new byte[8192];
        gis = new GZIPInputStream(bais);

        int numRead;
        while ((numRead = gis.read(buffer, 0, buffer.length)) != -1) {
            baos.write(buffer, 0, numRead);
        }
        return baos.toByteArray();
    } finally {
        if (gis != null)
            gis.close();
        else if (bais != null)
            bais.close();
        if (baos != null)
            baos.close();
    }
}