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:org.openehealth.ipf.platform.camel.lbs.mina.mllp.MllpDecoder.java

private void copy(MllpMessagePart message, OutputStream outputStream) throws IOException {
    ByteArrayInputStream input = new ByteArrayInputStream(message.asByteArray());
    try {/*from w w w.  j  a  v  a 2 s  .  com*/
        IOUtils.copy(input, outputStream);
    } finally {
        input.close();
    }
}

From source file:org.calrissian.accumulorecipes.metricsstore.ext.custom.function.SummaryStatsFunction.java

/**
 * {@inheritDoc}//from   w  w  w .ja  v a 2 s  .  c o m
 */
@Override
public SummaryStatistics deserialize(byte[] data) {
    try {

        ByteArrayInputStream byteArrStream = new ByteArrayInputStream(data);
        ObjectInputStream istream = new ObjectInputStream(byteArrStream);
        SummaryStatistics retVal = (SummaryStatistics) istream.readObject();
        istream.close();
        byteArrStream.close();
        return retVal;

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.microsoft.azure.keyvault.test.CertificateOperationsTest.java

/**
 * Extracts certificates from PEM contents
 * /*from  w w w . j a v  a 2s  .c om*/
 * @throws CertificateException
 * @throws IOException
 */
private static List<X509Certificate> extractCertificatesFromPemContents(String pemContents)
        throws CertificateException, IOException {
    Matcher matcher = _certificate.matcher(pemContents);
    if (!matcher.find()) {
        throw new IllegalArgumentException("No certificate found in PEM contents.");
    }

    List<X509Certificate> result = new ArrayList<X509Certificate>();
    int offset = 0;
    while (true) {
        if (!matcher.find(offset)) {
            break;
        }
        byte[] certBytes = _base64.decode(matcher.group(1));
        ByteArrayInputStream certStream = new ByteArrayInputStream(certBytes);
        CertificateFactory certificateFactory = CertificateFactory.getInstance(X509);
        X509Certificate x509Certificate = (X509Certificate) certificateFactory.generateCertificate(certStream);
        certStream.close();

        result.add(x509Certificate);
        offset = matcher.end();
    }

    return result;
}

From source file:org.paxle.gui.impl.servlets.MetaDataIconServlet.java

@Override
protected void doRequest(HttpServletRequest request, HttpServletResponse response) {
    try {//  w  ww.  java  2s .  c om
        final Context context = this.getVelocityView().createContext(request, response);
        final String servicePID = request.getParameter(REQ_PARAM_SERVICEPID);

        if (servicePID != null) {
            // getting the metaDataTool
            final MetaDataTool tool = (MetaDataTool) context.get(MetaDataTool.TOOL_NAME);
            if (tool == null) {
                this.log("No MetaDataTool found");
                return;
            }

            final IMetaData metaData = tool.getMetaData(servicePID);
            if (metaData == null) {
                this.log(String.format("No metadata found for service with PID '%s'.", servicePID));
                return;
            }

            // getting the icon
            InputStream in = metaData.getIcon(16);
            if (in == null)
                in = this.getClass().getResourceAsStream("/resources/images/cog.png");

            // loading date
            final ByteArrayOutputStream bout = new ByteArrayOutputStream();
            IOUtils.copy(in, bout);
            bout.close();
            in.close();

            // trying to detect the mimetype of the image
            final ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
            String contentType = URLConnection.guessContentTypeFromStream(bin);
            bin.close();

            // reading the image
            BufferedImage img = null;
            Iterator<ImageReader> readers = null;
            if (contentType != null) {
                readers = ImageIO.getImageReadersByMIMEType(contentType);
                while (readers != null && readers.hasNext() && img == null) {
                    // trying the next reader
                    ImageReader reader = readers.next();

                    InputStream input = null;
                    try {
                        input = new ByteArrayInputStream(bout.toByteArray());
                        reader.setInput(ImageIO.createImageInputStream(input));
                        img = reader.read(0);
                    } catch (Exception e) {
                        this.log(String.format("Unable to read metadata icon for service with PID '%s'.",
                                servicePID), e);
                    } finally {
                        if (input != null)
                            input.close();
                    }
                }
            }

            if (img != null) {
                response.setHeader("Content-Type", "image/png");
                ImageIO.write(img, "png", response.getOutputStream());
                return;
            } else {
                response.sendError(404);
                return;
            }
        } else {
            response.sendError(500, "Invalid usage");
        }
    } catch (Throwable e) {
        this.log(String.format("Unexpected '%s'.", e.getClass().getName()), e);
    }
}

From source file:corner.service.svn.HibernateObjectTest.java

@Test
public void testDecodeBase64() {
    byte[] bytes = base64.decode("dGVzdA==");

    ByteArrayInputStream input = new ByteArrayInputStream(bytes);

    ByteArrayOutputStream out = new ByteArrayOutputStream();

    int ch = 0;/* ww  w.  j  a  v  a 2  s  .c o  m*/

    try {
        while ((ch = input.read()) != -1) {
            out.write((char) ch);
        }
        input.close();
        out.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
    assertEquals("test", new String(out.toByteArray()));
}

From source file:Base64.java

/**
 * Attempts to decode Base64 data and deserialize a Java
 * Object within. Returns <tt>null</tt> if there was an error.
 *
 * @param encodedObject The Base64 data to decode
 * @return The decoded and deserialized object
 * @since 1.4//from   w w  w  . j a  v  a2s . co m
 */
public static Object decodeToObject(String encodedObject) {

    byte[] objBytes = decode(encodedObject);

    java.io.ByteArrayInputStream bais = null;
    java.io.ObjectInputStream ois = null;

    try {
        bais = new java.io.ByteArrayInputStream(objBytes);
        ois = new java.io.ObjectInputStream(bais);

        return ois.readObject();
    } // end try
    catch (java.io.IOException e) {

        e.printStackTrace();
        return null;
    } // end catch
    catch (ClassNotFoundException e) {

        e.printStackTrace();
        return null;
    } // end catch
    finally {
        try {
            bais.close();
            ois.close();
        } catch (Exception e) {
        }
    } // end finally
}

From source file:ch.cyberduck.core.onedrive.OneDriveWriteFeatureTest.java

@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);/* w w  w  .ja v  a2  s.com*/
    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());
}

From source file:org.deegree.securityproxy.filter.RequestBodyWrapper.java

@Override
public BufferedReader getReader() throws IOException {
    final ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArray);
    return new BufferedReader(new InputStreamReader(byteArrayInputStream)) {

        @Override/*from  www  .java2  s .  c  om*/
        public void close() throws IOException {
            super.close();
            byteArrayInputStream.close();
        }
    };
}

From source file:org.codehaus.plexus.archiver.zip.ConcurrentJarCreator.java

/**
 * Adds an archive entry to this archive.
 * <p/>/*ww  w  . ja  v a  2  s  .c o  m*/
 * This method is expected to be called from a single client thread
 *
 * @param zipArchiveEntry The entry to add. Compression method
 * @param source          The source input stream supplier
 * @throws java.io.IOException
 */

public void addArchiveEntry(final ZipArchiveEntry zipArchiveEntry, final InputStreamSupplier source)
        throws IOException {
    final int method = zipArchiveEntry.getMethod();
    if (method == -1)
        throw new IllegalArgumentException("Method must be set on the supplied zipArchiveEntry");
    if (zipArchiveEntry.isDirectory() && !zipArchiveEntry.isUnixSymlink()) {
        final ByteArrayInputStream payload = new ByteArrayInputStream(new byte[] {});
        directories.addArchiveEntry(
                createZipArchiveEntryRequest(zipArchiveEntry, createInputStreamSupplier(payload)));
        payload.close();
    } else if ("META-INF".equals(zipArchiveEntry.getName())) {
        InputStream payload = source.get();
        if (zipArchiveEntry.isDirectory())
            zipArchiveEntry.setMethod(ZipEntry.STORED);
        metaInfDir.addArchiveEntry(
                createZipArchiveEntryRequest(zipArchiveEntry, createInputStreamSupplier(payload)));
        payload.close();
    } else if ("META-INF/MANIFEST.MF".equals(zipArchiveEntry.getName())) {
        InputStream payload = source.get();
        if (zipArchiveEntry.isDirectory())
            zipArchiveEntry.setMethod(ZipEntry.STORED);
        manifest.addArchiveEntry(
                createZipArchiveEntryRequest(zipArchiveEntry, createInputStreamSupplier(payload)));
        payload.close();
    } else {
        parallelScatterZipCreator.addArchiveEntry(zipArchiveEntry, source);
    }
}

From source file:com.beetle.framework.util.ObjectUtil.java

/**
 * //from  w  w  w. j ava 2  s .c  om
 * 
 * @param originObj
 * @return
 */
public final static Object objectClone(Object originObj) {
    ByteArrayOutputStream bao = null;
    ByteArrayInputStream bai = null;
    ObjectOutputStream oos;
    ObjectInputStream ois;
    try {
        bao = new ByteArrayOutputStream();
        oos = new ObjectOutputStream(bao);
        oos.writeObject(originObj);
        oos.flush();
        oos.close();
        bai = new ByteArrayInputStream(bao.toByteArray());
        ois = new ObjectInputStream(bai);
        Object obj = ois.readObject();
        ois.close();
        oos = null;
        ois = null;
        return obj;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (bao != null) {
                bao.close();
                bao = null;
            }
            if (bai != null) {
                bai.close();
                bai = null;
            }
        } catch (IOException e) {
        }
    }
}