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.eclipse.dawnsci.doe.DOEUtils.java

/**
 * Creates a clone of any serializable object. Collections and arrays may be cloned if the entries are serializable.
 * Caution super class members are not cloned if a super class is not serializable.
 *//* w  w  w .ja  va2 s .co  m*/
public static <T extends Serializable> T deepClone(T toClone, final ClassLoader classLoader) throws Exception {
    if (null == toClone)
        return null;

    ByteArrayOutputStream bOut = new ByteArrayOutputStream();
    ObjectOutputStream oOut = new ObjectOutputStream(bOut);
    oOut.writeObject(toClone);
    oOut.close();
    ByteArrayInputStream bIn = new ByteArrayInputStream(bOut.toByteArray());
    bOut.close();
    ObjectInputStream oIn = new ObjectInputStream(bIn) {
        /**
         * What we are saying with this is that either the class loader or any of the beans added using extension
         * points classloaders should be able to find the class.
         */
        @Override
        protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
            try {
                return Class.forName(desc.getName(), false, classLoader);
            } catch (Exception ne) {
                ne.printStackTrace();
            }
            return null;
        }
    };
    bIn.close();
    // the whole idea is to create a clone, therefore the readObject must
    // be the same type in the toClone, hence of T
    @SuppressWarnings("unchecked")
    T copy = (T) oIn.readObject();
    oIn.close();

    return copy;
}

From source file:edu.jhuapl.graphs.controller.GraphController.java

public static String zipGraphs(List<GraphObject> graphs, String tempDir, String userId) throws GraphException {
    if (graphs != null && graphs.size() > 0) {
        byte[] byteBuffer = new byte[1024];
        String zipFileName = getUniqueId(userId) + ".zip";

        try {//  ww w . j a v a2s  .  c  o  m
            File zipFile = new File(tempDir, zipFileName);
            ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipFile));
            boolean hasGraphs = false;

            for (GraphObject graph : graphs) {
                if (graph != null) {
                    byte[] renderedGraph = graph.getRenderedGraph().getData();
                    ByteArrayInputStream in = new ByteArrayInputStream(renderedGraph);
                    int len;

                    zos.putNextEntry(new ZipEntry(graph.getImageFileName()));

                    while ((len = in.read(byteBuffer)) > 0) {
                        zos.write(byteBuffer, 0, len);
                    }

                    in.close();
                    zos.closeEntry();
                    hasGraphs = true;
                }
            }

            zos.close();

            if (hasGraphs) {
                return zipFileName;
            } else {
                return null;
            }
        } catch (IOException e) {
            throw new GraphException("Could not write zip", e);
        }
    }

    return null;
}

From source file:net.sqs2.translator.impl.SQSToPDFTranslator.java

private byte[] createSVGPrint(FOUserAgent userAgent, int numPages) {
    try {//from   w  w w.  ja  va 2  s .  c om
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.println("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
        writer.println("<svg:svg ");
        writer.println(" xmlns=\"" + SQSNamespaces.SVG_URI + "\" ");
        writer.println(" xmlns:svg=\"" + SQSNamespaces.SVG_URI + "\" ");
        writer.println(" xmlns:sqs=\"" + SQSNamespaces.SQS2004_URI + "\" ");
        writer.println(" xmlns:xforms=\"" + SQSNamespaces.XFORMS_URI + "\" ");
        writer.println(" xmlns:master=\"" + SQSNamespaces.SQS2007MASTER_URI + "\" ");
        writer.print("width=\"");
        PageSetting pageSetting = (PageSetting) userAgent.getRendererOptions().get("pageSetting");
        writer.print(pageSetting.getWidth());
        writer.print("\" height=\"");
        writer.print(pageSetting.getHeight());
        writer.println("\">");

        pageSetting.init(SVGElementIDToPageRectangleMap.getInstance(), userAgent);

        printPageSet(pageSetting, userAgent, numPages, writer);
        writer.println("</svg:svg>");
        writer.close();
        out.close();

        byte[] svgBytes = out.toByteArray();

        if (false) {
            ByteArrayInputStream svgInputStream = new ByteArrayInputStream(svgBytes);
            OutputStream sqmOutputStream = new BufferedOutputStream(new FileOutputStream("/tmp/sqs.sqm"));
            FileUtil.connect(svgInputStream, sqmOutputStream);
            svgInputStream.close();
            sqmOutputStream.close();
        }

        return svgBytes;
    } catch (IOException ex) {
        ex.printStackTrace();
    } catch (SQMSchemeException ex) {
        ex.printStackTrace();
    }
    return null;
}

From source file:de.elatePortal.autotool.SubTasklet_AutotoolImpl.java

private Object deserialize(byte[] arr) {
    try {/* ww w . j  a  v  a2s  .com*/
        ByteArrayInputStream bos = new ByteArrayInputStream(arr);
        ObjectInputStream oos = new ObjectInputStream(bos);
        Object o = oos.readObject();
        oos.close();
        bos.close();
        return o;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:org.apache.taverna.activities.interaction.InteractionActivityRunnable.java

@Override
public void run() {
    /*//from www . jav a  2  s .  c  om
     * InvocationContext context = callback.getContext();
     */
    final String runId = InteractionUtils.getUsedRunId(this.requestor.getRunId());

    final String id = Sanitizer.sanitize(UUID.randomUUID().toString(), "", true, Normalizer.Form.D);

    final Map<String, Object> inputData = this.requestor.getInputData();

    if (interactionPreference.getUseJetty()) {
        interactionJetty.startJettyIfNecessary(credentialManager);
    }
    interactionJetty.startListenersIfNecessary();
    try {
        interactionUtils.copyFixedFile("pmrpc.js");
        interactionUtils.copyFixedFile("interaction.css");
    } catch (final IOException e1) {
        logger.error(e1);
        this.requestor.fail("Unable to copy necessary fixed file");
        return;
    }
    synchronized (ABDERA) {
        final Entry interactionNotificationMessage = this.createBasicInteractionMessage(id, runId);

        for (final String key : inputData.keySet()) {
            final Object value = inputData.get(key);
            if (value instanceof byte[]) {
                final String replacementUrl = interactionPreference.getPublicationUrlString(id, key);
                final ByteArrayInputStream bais = new ByteArrayInputStream((byte[]) value);
                try {
                    interactionUtils.publishFile(replacementUrl, bais, runId, id);
                    bais.close();
                    inputData.put(key, replacementUrl);
                } catch (final IOException e) {
                    logger.error(e);
                    this.requestor.fail("Unable to publish to " + replacementUrl);
                    return;
                }
            }
        }

        final String inputDataString = this.createInputDataJson(inputData);
        if (inputDataString == null) {
            return;
        }
        final String inputDataUrl = interactionPreference.getInputDataUrlString(id);
        try {
            interactionUtils.publishFile(inputDataUrl, inputDataString, runId, id);
        } catch (final IOException e) {
            logger.error(e);
            this.requestor.fail("Unable to publish to " + inputDataUrl);
            return;
        }

        String outputDataUrl = null;

        if (!this.requestor.getInteractionType().equals(InteractionType.Notification)) {
            outputDataUrl = interactionPreference.getOutputDataUrlString(id);
        }
        final String interactionUrlString = this.generateHtml(inputDataUrl, outputDataUrl, inputData, runId,
                id);

        try {
            this.postInteractionMessage(id, interactionNotificationMessage, interactionUrlString, runId);
        } catch (IOException e) {
            logger.error(e);
            this.requestor.fail("Unable to post message");
            return;
        }
        if (!this.requestor.getInteractionType().equals(InteractionType.Notification)) {
            responseFeedListener.registerInteraction(interactionNotificationMessage, this.requestor);
        } else {
            this.requestor.carryOn();

        }
    }
}

From source file:org.exist.http.servlets.Log4jInit.java

private void convertLogFile(File srcConfig, File destConfig, File logDir) {

    // Step 1 read config file into memory
    String srcDoc = "not initialized";
    try {//from  w  w  w.  j av  a  2 s.c o  m
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final FileInputStream is = new FileInputStream(srcConfig);

        final byte[] buf = new byte[1024];
        int len;
        while ((len = is.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }

        is.close();
        baos.close();
        srcDoc = new String(baos.toByteArray());
    } catch (final FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (final IOException ex) {
        ex.printStackTrace();
    }

    // Step 2 ; substitute Patterns
    final String destDoc = srcDoc.replaceAll("loggerdir", logDir.getAbsolutePath().replaceAll("\\\\", "/"));

    // Step 3 ; write back to file
    try {
        final ByteArrayInputStream bais = new ByteArrayInputStream(destDoc.getBytes());
        final FileOutputStream fos = new FileOutputStream(destConfig);
        final byte[] buf = new byte[1024];
        int len;
        while ((len = bais.read(buf)) > 0) {
            fos.write(buf, 0, len);
        }
        fos.close();
        bais.close();
    } catch (final FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (final IOException ex) {
        ex.printStackTrace();
    }
}

From source file:org.apache.myfaces.wap.renderkit.WmlResponseStateManagerImpl.java

private Object decode64(String s) {
    try {/*w ww . j a v a 2s  .c  o m*/
        Base64 base64Codec = new Base64();
        ByteArrayInputStream decodedStream = new ByteArrayInputStream(
                base64Codec.decode(s.getBytes(ZIP_CHARSET)));
        InputStream unzippedStream = new GZIPInputStream(decodedStream);
        ObjectInputStream ois = new ObjectInputStream(unzippedStream);
        Object obj = ois.readObject();
        ois.close();
        unzippedStream.close();
        decodedStream.close();
        return obj;
    } catch (IOException e) {
        log.fatal("Cannot decode Object from Base64 String", e);
        throw new FacesException(e);
    } catch (ClassNotFoundException e) {
        log.fatal("Cannot decode Object from Base64 String", e);
        throw new FacesException(e);
    }
}

From source file:org.mule.util.compression.GZipCompression.java

/**
 * Used for uncompressing a byte array into a uncompressed byte array using GZIP
 * /*w w w  .  j ava  2s  . co m*/
 * @param bytes An array of bytes to uncompress
 * @return an uncompressed byte array
 * @throws java.io.IOException if it fails to read from a GZIPInputStream
 * @see java.util.zip.GZIPInputStream
 */
public byte[] uncompressByteArray(byte[] bytes) throws IOException {
    // TODO add strict behaviour as option
    if (!isCompressed(bytes)) {
        /*
         * if (strict) { // throw a specific exception here to allow users of
         * this method to // diffientiate between general IOExceptions and an
         * invalid format logger.warn("Data is not of type GZIP compressed." + "
         * The data may not have been compressed in the first place."); throw new
         * CompressionException("Not in GZIP format"); }
         */

        // nothing to uncompress
        if (logger.isDebugEnabled()) {
            logger.debug("Data already uncompressed; doing nothing");
        }
        return bytes;
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Uncompressing message of size: " + bytes.length);
    }

    ByteArrayInputStream bais = null;
    GZIPInputStream gzis = null;
    ByteArrayOutputStream baos = null;

    try {
        bais = new ByteArrayInputStream(bytes);
        gzis = new GZIPInputStream(bais);
        baos = new ByteArrayOutputStream(DEFAULT_BUFFER_SIZE);

        IOUtils.copy(gzis, baos);
        gzis.close();
        bais.close();

        byte[] uncompressedByteArray = baos.toByteArray();
        baos.close();

        if (logger.isDebugEnabled()) {
            logger.debug("Uncompressed message to size: " + uncompressedByteArray.length);
        }

        return uncompressedByteArray;
    } catch (IOException ioex) {
        throw ioex;
    } finally {
        IOUtils.closeQuietly(gzis);
        IOUtils.closeQuietly(bais);
        IOUtils.closeQuietly(baos);
    }
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private Charset getCharset(byte[] content, String contentType) throws IOException {
    ContentType type = ContentType.parse(contentType);
    Charset charset = type.getCharset();
    if (charset != null)
        return charset;
    ByteArrayInputStream in = new ByteArrayInputStream(content);
    try {//  w w  w.ja  v a 2s.c om
        return new CharsetDetector().detect(in);
    } finally {
        in.close();
    }
}

From source file:de.javakaffee.web.msm.serializer.jackson.JacksonTranscoderTest.java

private StandardSession javaRoundtrip(final StandardSession session,
        final MemcachedBackupSessionManager manager) throws IOException, ClassNotFoundException {

    final ByteArrayOutputStream bos = new ByteArrayOutputStream();
    final ObjectOutputStream oos = new ObjectOutputStream(bos);
    session.writeObjectData(oos);// ww  w . j a va 2s . co m
    oos.close();
    bos.close();

    final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    final ObjectInputStream ois = new ObjectInputStream(bis);
    final StandardSession readSession = manager.createEmptySession();
    readSession.readObjectData(ois);
    ois.close();
    bis.close();

    return readSession;
}