Example usage for java.io ByteArrayOutputStream flush

List of usage examples for java.io ByteArrayOutputStream flush

Introduction

In this page you can find the example usage for java.io ByteArrayOutputStream flush.

Prototype

public void flush() throws IOException 

Source Link

Document

Flushes this output stream and forces any buffered output bytes to be written out.

Usage

From source file:it.geosolutions.imageio.plugins.exif.EXIFUtilities.java

/**
 * Initialize a ByteArrayOutputStream on top of an {@link EXIFMetadata} entity.
 * /*www .  ja  va 2s  . c o  m*/
 * @param exif an {@link EXIFMetadata} instance representing EXIF tags to be put to the stream
 * @param outputStream an optional {@link ByteArrayOutputStream} where to write the exif marker.
 * If null, a new {@link ByteArrayOutputStream} will be created and returned
 * 
 * @return the {@link ByteArrayOutputStream} containing the written EXIF bytes.
 * @throws IOException
 */
private static ByteArrayOutputStream initializeExifStream(final EXIFMetadata exif,
        final ByteArrayOutputStream outputStream) throws IOException {

    // Preliminar check. Write on: the provided ByteArrayOutputStream VS a newly created one
    final ByteArrayOutputStream baos = outputStream == null ? new ByteArrayOutputStream() : outputStream;

    // Get exif tags from the specified EXIF object.
    List<TIFFTagWrapper> baselineTags = exif.getList(Type.BASELINE);
    List<TIFFTagWrapper> exifTags = exif.getList(Type.EXIF);
    final int baseLength = TIFF_HEADER_LENGTH + BYTES_FOR_TAGS_NUMBER + NEXT_IFD.length;

    // Initialize number of fields and tags
    final int numBaselineTags = baselineTags.size();
    final int numExifTags = exifTags.size();
    final byte[] numFieldsB = intToBytes(numBaselineTags);
    final byte[] numSpecificFieldsB = intToBytes(numExifTags);

    // Initialize tags sizes and offsets
    final int baseLineTagsOffsets[] = new int[numBaselineTags];
    final int baseLineTagsContentSizes[] = new int[numBaselineTags];
    computeOffsetsAndSizes(baselineTags, baseLength, baseLineTagsOffsets, baseLineTagsContentSizes);
    final int baselineContentLength = sum(baseLineTagsContentSizes);

    final int exifTagsOffsets[] = new int[numExifTags];
    final int exifTagsContentSizes[] = new int[numExifTags];
    computeOffsetsAndSizes(exifTags, baseLineTagsOffsets[numBaselineTags - 1] + BYTES_FOR_TAGS_NUMBER,
            exifTagsOffsets, exifTagsContentSizes);
    final int exifTagsContentLength = sum(exifTagsContentSizes);

    // Compute total marker length (which is the first entry to be written out after the marker)
    int app1Lenght = APP1_MARKER.length - 1 // -1 due to the 0xFF part
            + EXIF_MARKER.length + baseLength + BYTES_FOR_TAGS_NUMBER // Num Fields (2 bytes)
            + BYTES_FOR_TAGS_NUMBER // Num EXIF Fields (2 bytes)
            + numBaselineTags * IFD_LENGTH + numExifTags * IFD_LENGTH // Bytes needed to represent all IFD
            + baselineContentLength + exifTagsContentLength; // Bytes used for tags contents

    // Write headers
    baos.write(APP1_MARKER);
    baos.write(intToBytes(app1Lenght));
    baos.write(EXIF_MARKER);
    baos.write(TIFF_HEADER);
    baos.write(numFieldsB);

    // Write BaseLine IFDs and their content
    writeIFDs(baos, baselineTags);
    baos.write(NEXT_IFD);
    writeTagsContent(baos, baselineTags);
    baos.write(numSpecificFieldsB);

    // Write EXIF Specific IFDs and their content
    writeIFDs(baos, exifTags);
    writeTagsContent(baos, exifTags);
    baos.flush();
    return baos;
}

From source file:big.BigZip.java

/**
 * Version 2 that permits to extract the text from a compressed file without
 * creating any file on the disk.//  w  ww  .ja v a 2 s .  com
 * @param filePosition
 * @return      The source code of the compressed file
 */
public String extractBytesToRAM(final long filePosition) {

    String result = null;

    try {

        // add the signature bytes to our start position
        long startPosition = filePosition + magicSignature.length();

        // enable random access to the BIG file (fast as heck)
        RandomAccessFile dataBIG = new RandomAccessFile(fileMainBIG, "r");
        // jump directly to the position where the file is positioned
        dataBIG.seek(startPosition);
        // create a byte array
        ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();

        // get the end of this file entry (by brute-force)
        char test = 0;
        long endPosition = -1;
        while (test != -1) {
            test = dataBIG.readChar();
            // if the magic devil number was found..
            if (test == 66) {
                // read the next value for confirmation
                byte value = dataBIG.readByte();
                if (value != 73) {
                    continue;
                }
                // we found the next entry
                endPosition = dataBIG.getFilePointer() - 1;
                break;
            }
        }

        // rewind back to the start position
        dataBIG.seek(startPosition);

        // now we start reading bytes during the mentioned interval
        while (dataBIG.getFilePointer() < endPosition) {
            // read a byte from our BIG archive
            int data = dataBIG.read();
            byteOutput.write(data);
        }
        // flush data at this point
        byteOutput.flush();
        // now convert the stream from input into an output (to feed the zip stream)
        ByteArrayInputStream byteInput = new ByteArrayInputStream(byteOutput.toByteArray());
        // where we place the decompressed bytes
        ByteArrayOutputStream textOutput = new ByteArrayOutputStream();
        // create the zip streamer
        final ArchiveInputStream archiveStream;
        archiveStream = new ArchiveStreamFactory().createArchiveInputStream("zip", byteInput);
        final ZipArchiveEntry entry = (ZipArchiveEntry) archiveStream.getNextEntry();
        // copy all bytes from one location to the other (and decompress the data)
        IOUtils.copy(archiveStream, textOutput);
        // flush the results
        textOutput.flush();
        // we've got the result right here!
        result = textOutput.toString();
        // now close all the streams that we have open
        dataBIG.close();
        byteOutput.close();
        byteInput.close();
        textOutput.close();
        archiveStream.close();

    } catch (FileNotFoundException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (IOException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
        return null;
    } catch (ArchiveException ex) {
        Logger.getLogger(BigZip.class.getName()).log(Level.SEVERE, null, ex);
    }

    return result;
}

From source file:fi.foyt.fni.materials.MaterialController.java

public TypedData printDocumentAsPdf(String contextPath, String baseUrl, User user, Document document)
        throws DocumentException, IOException, ParserConfigurationException, SAXException {
    ITextRenderer renderer = new ITextRenderer();
    ReplacedElementFactory replacedElementFactory = new B64ImgReplacedElementFactory();
    renderer.getSharedContext().setReplacedElementFactory(replacedElementFactory);

    String documentContent = document.getData();
    org.w3c.dom.Document domDocument = tidyForPdf(document.getTitle(), documentContent);

    try {//ww w.  jav  a 2  s  . c o m
        NodeList imageList = XPathAPI.selectNodeList(domDocument, "//img");
        for (int i = 0, l = imageList.getLength(); i < l; i++) {
            Element imageElement = (Element) imageList.item(i);
            String src = imageElement.getAttribute("src");

            try {
                boolean internal = false;

                if (src.startsWith("http://") || src.startsWith("https://")) {
                    if (src.startsWith(baseUrl)) {
                        src = RequestUtils.stripCtxPath(contextPath, src.substring(baseUrl.length()));
                        internal = true;
                    } else {
                        internal = false;
                    }
                } else {
                    src = RequestUtils.stripCtxPath(contextPath, src);
                    internal = true;
                }

                if (internal) {
                    Material material = findMaterialByCompletePath(src);
                    if (materialPermissionController.hasAccessPermission(user, material)) {
                        if (material.getType() == MaterialType.IMAGE) {
                            Image image = (Image) material;

                            StringBuilder srcBuilder = new StringBuilder().append("data:")
                                    .append(image.getContentType()).append(";base64,")
                                    .append(new String(Base64.encodeBase64(image.getData())));

                            imageElement.setAttribute("src", srcBuilder.toString());
                        }
                    }
                }

            } catch (Exception e) {
                // If anything goes wrong we just leave this img "as is".
            }
        }
    } catch (Exception e) {
        // If anything goes wrong we just leave the document "as is".
    }

    ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
    renderer.setDocument(domDocument, baseUrl);
    renderer.layout();
    renderer.createPDF(pdfStream);
    pdfStream.flush();
    pdfStream.close();

    return new TypedData(pdfStream.toByteArray(), "application/pdf");
}

From source file:com.anyonavinfo.commonuserregister.MainActivity.java

/**
 * Post?// www. j  a  v  a 2  s  .  c om
 */
public static String doPost(String urlStr, File file) {
    URL url = null;
    HttpURLConnection conn = null;
    InputStream is = null;
    ByteArrayOutputStream baos = null;
    String BOUNDARY = UUID.randomUUID().toString(); //  ??
    String PREFIX = "--", LINE_END = "\r\n";
    String CONTENT_TYPE = "multipart/form-data"; // 

    try {
        url = new URL(urlStr);
        conn = (HttpURLConnection) url.openConnection();
        conn.setReadTimeout(15000);
        conn.setConnectTimeout(15000);
        conn.setRequestMethod("POST");
        conn.setDoInput(true); // ??
        conn.setDoOutput(true); // ??
        conn.setUseCaches(false); // ??
        conn.setRequestProperty("encoding", "utf-8");
        conn.setRequestProperty("connection", "keep-alive");
        conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

        if (file != null) {
            /**
             * ?
             */
            DataOutputStream dos = new DataOutputStream(conn.getOutputStream());
            StringBuffer sb = new StringBuffer();
            sb.append(PREFIX);
            sb.append(BOUNDARY);
            sb.append(LINE_END);
            /**
             * ?? name???key ?key ??
             * filename??????
             */

            sb.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\""
                    + LINE_END);
            sb.append("Content-Type: application/octet-stream; charset=" + "utf-8" + LINE_END);
            sb.append(LINE_END);
            dos.write(sb.toString().getBytes());
            InputStream IS = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = IS.read(bytes)) != -1) {
                dos.write(bytes, 0, len);
            }
            IS.close();
            dos.write(LINE_END.getBytes());
            byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END).getBytes();
            dos.write(end_data);
            dos.flush();
        }

        if (conn.getResponseCode() == 200) {
            is = conn.getInputStream();
            baos = new ByteArrayOutputStream();
            int len = -1;
            byte[] buf = new byte[128];

            while ((len = is.read(buf)) != -1) {
                baos.write(buf, 0, len);
                Log.d("Sjj--->", len + "");
            }
            baos.flush();
            return baos.toString();
        } else {
            throw new RuntimeException(" responseCode is not 200 ... ");
        }

    } catch (Exception e) {
        // 
        if (e instanceof SocketTimeoutException) {
            return "SocketTimeoutException";
        } else if (e instanceof UnknownHostException) {
            return "UnknownHostException";
        }
        e.printStackTrace();
    } finally {
        try {
            if (is != null)
                is.close();
            if (baos != null)
                baos.close();
            if (conn != null) {
                conn.disconnect();
            }
        } catch (IOException e) {
        }
    }

    return null;
}

From source file:com.amalto.core.storage.StorageWrapper.java

protected String getXmlString(String clusterName, ComplexTypeMetadata type, Iterator<DataRecord> iterator,
        String uniqueID, String encoding, boolean isUserFormat) throws IOException {
    String xmlString = null;//from  w w w .  ja va2 s .com
    if (iterator.hasNext()) {
        DataRecord result = iterator.next();
        if (iterator.hasNext()) {
            iterateUnexceptedRecords(LOGGER, uniqueID, iterator);
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream(1024);
        // Enforce root element name in case query returned instance of a subtype.
        DataRecordWriter dataRecordXmlWriter = isUserFormat ? new DataRecordXmlWriter(type)
                : new SystemDataRecordXmlWriter(
                        (ClassRepository) getStorage(clusterName).getMetadataRepository(), type);
        if (isUserFormat) {
            dataRecordXmlWriter.setSecurityDelegator(SecuredStorage.getDelegator());
            String key = uniqueID.startsWith(PROVISIONING_PREFIX_INFO)
                    ? StringUtils.substringAfter(uniqueID, PROVISIONING_PREFIX_INFO)
                    : uniqueID.split("\\.")[2]; //$NON-NLS-1$
            long timestamp = result.getRecordMetadata().getLastModificationTime();
            String taskId = result.getRecordMetadata().getTaskId();
            String modelName = StringUtils.substringBeforeLast(clusterName, StorageAdmin.STAGING_SUFFIX);
            byte[] start = ("<ii><c>" + clusterName + "</c><dmn>" + modelName + "</dmn><dmr/><sp/><t>" //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$
                    + timestamp + "</t><taskId>" + taskId + "</taskId><i>" + StringEscapeUtils.escapeXml(key) //$NON-NLS-1$//$NON-NLS-2$
                    + "</i><p>").getBytes(); //$NON-NLS-1$
            output.write(start);
        }
        dataRecordXmlWriter.write(result, output);
        if (isUserFormat) {
            byte[] end = ("</p></ii>").getBytes(); //$NON-NLS-1$
            output.write(end);
        }
        output.flush();
        xmlString = new String(output.toByteArray(), encoding);
    }
    return xmlString;
}

From source file:com.karura.framework.plugins.utils.ContactAccessorSdk5.java

/**
 * Gets the raw bytes from the supplied filename
 * //from  w w w  .j a v  a2s .c  o m
 * @param filename
 *            the file to read the bytes from
 * @return a byte array
 * @throws IOException
 */
private byte[] getPhotoBytes(String filename) {
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    try {
        int bytesRead = 0;
        long totalBytesRead = 0;
        byte[] data = new byte[8192];
        InputStream in = getPathFromUri(filename);

        while ((bytesRead = in.read(data, 0, data.length)) != -1 && totalBytesRead <= MAX_PHOTO_SIZE) {
            buffer.write(data, 0, bytesRead);
            totalBytesRead += bytesRead;
        }

        in.close();
        buffer.flush();
    } catch (FileNotFoundException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    } catch (IOException e) {
        Log.e(LOG_TAG, e.getMessage(), e);
    }
    return buffer.toByteArray();
}

From source file:es.javocsoft.android.lib.toolbox.ToolBox.java

/**
 * Reads the byte data from a input stream.
 * //ww  w.jav a 2  s. co m
 * @param input
 * @return
 * @throws java.io.IOException
 */
public static byte[] io_inputStreamToByteArray(InputStream input) throws IOException {
    byte[] res = null;

    try {
        // this dynamically extends to take the bytes you read
        ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();

        // this is storage overwritten on each iteration with bytes
        int bufferSize = 1024;
        byte[] buffer = new byte[bufferSize];

        // we need to know how may bytes were read to write them to the byteBuffer
        int len = 0;
        while (input.available() > 0 && (len = input.read(buffer)) != -1) {
            byteBuffer.write(buffer, 0, len);
        }

        byteBuffer.flush();
        res = byteBuffer.toByteArray();

        byteBuffer.close();
    } catch (Exception e) {
        throw new IOException("Failed to read byte data from the stream (" + e.getMessage() + ").", e);
    }

    return res;
}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Builds changes XML document from Bugzilla XML Document
 * //  w  w w.ja v a 2  s .c  o m
 * @param bugsDocument
 * @throws MojoExecutionException
 */
private void builChangesXML(final Document bugsDocument) throws MojoExecutionException {
    FileOutputStream fos = null;
    Transform t;
    try {
        t = new Transform(this.getClass().getClassLoader().getResourceAsStream("bugzilla.xsl"));
    } catch (final TransformerConfigurationException e) {
        this.getLog().error("Internal XSL error.", e);
        throw new MojoExecutionException("Error with internal XSL transformation file.", e);
    }
    ByteArrayOutputStream baos = null;
    try {
        // creamos los directorios
        this.createFilePath();
        // formamos el documento de cambios
        final byte[] changesXml = t.transformar(bugsDocument);

        // comprobamos si ya existe el fichero y estamos con currentVersionOnly=true.
        // por lo que hay que mantener los cambios de versiones anteriores
        if (this.currentVersionOnly && this.xmlPath.exists()) {
            final Document changesDocument = this.getChangesDocument();
            // buscamos la release que se corresponde con la versin actual
            final NodeList nodelist = changesDocument.getElementsByTagName(ELEMENT_RELEASE);
            boolean replaced = false;
            for (int i = 0; i < nodelist.getLength(); i++) {
                final Element elementRelease = (Element) nodelist.item(i);
                if (this.versionName.equals(elementRelease.getAttribute(ATTRIBUTE_VERSION))) {
                    // sustituimos el nodo de la release por el que hemos obtenido ahora
                    this.replaceReleaseNode(elementRelease, changesXml);
                    replaced = true;
                    break;
                }
            }
            if (!replaced) {
                this.addNewRelease(changesDocument, changesXml);
            }
            this.saveChangesDocument(changesDocument);

        } else {
            // escribimos el documento XML de cambios
            fos = new FileOutputStream(this.xmlPath);
            baos = new ByteArrayOutputStream();
            baos.write(changesXml);
            baos.writeTo(fos);
            baos.flush();
            fos.flush();
        }

    } catch (final IOException e) {
        this.getLog().error("Error creating file " + this.xmlPath, e);
        throw new MojoExecutionException("Error creating file " + this.xmlPath, e);
    } catch (final TransformerException e) {
        this.getLog().error("Error creating file " + this.xmlPath, e);
        throw new MojoExecutionException("Error creating file " + this.xmlPath, e);
    } finally {
        if (baos != null) {
            try {
                baos.close();
            } catch (final IOException e) {
                // ignore
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (final IOException e) {
                // ignore
            }
        }
    }

}

From source file:org.apache.olingo.fit.V4Services.java

@POST
@Path("/async/$batch")
public Response async(@Context final UriInfo uriInfo,
        @HeaderParam("Prefer") @DefaultValue(StringUtils.EMPTY) final String prefer,
        final @Multipart MultipartBody attachment) {

    try {/*  w w  w  .java  2  s.c o  m*/
        final ByteArrayOutputStream bos = new ByteArrayOutputStream();
        bos.write("HTTP/1.1 200 Ok".getBytes());
        bos.write(CRLF);
        bos.write("OData-Version: 4.0".getBytes());
        bos.write(CRLF);
        bos.write(
                ("Content-Type: " + ContentType.APPLICATION_OCTET_STREAM + ";boundary=" + BOUNDARY).getBytes());
        bos.write(CRLF);
        bos.write(CRLF);

        bos.write(("--" + BOUNDARY).getBytes());
        bos.write(CRLF);
        bos.write("Content-Type: application/http".getBytes());
        bos.write(CRLF);
        bos.write("Content-Transfer-Encoding: binary".getBytes());
        bos.write(CRLF);
        bos.write(CRLF);

        bos.write("HTTP/1.1 202 Accepted".getBytes());
        bos.write(CRLF);
        bos.write("Location: http://service-root/async-monitor".getBytes());
        bos.write(CRLF);
        bos.write("Retry-After: 10".getBytes());
        bos.write(CRLF);
        bos.write(CRLF);
        bos.write(("--" + BOUNDARY + "--").getBytes());
        bos.write(CRLF);

        final UUID uuid = UUID.randomUUID();
        providedAsync.put(uuid.toString(), bos.toString(Constants.ENCODING.toString()));

        bos.flush();
        bos.close();

        return xml.createAsyncResponse(uriInfo.getRequestUri().toASCIIString().replace("async/$batch", "")
                + "monitor/" + uuid.toString());
    } catch (Exception e) {
        return xml.createFaultResponse(Accept.JSON.toString(), e);
    }
}

From source file:bftsmart.tom.core.TOMLayer.java

private void catch_up(int regency) {

    Logger.println("(TOMLayer.catch_up) verify STOPDATA info");
    ObjectOutputStream out = null;
    ByteArrayOutputStream bos = null;

    LastEidData lastHighestEid = lcManager.getHighestLastEid(regency);

    int currentEid = lastHighestEid.getEid() + 1;
    HashSet<SignedObject> signedCollects = null;
    byte[] propose = null;
    int batchSize = -1;

    // normalize the collects and apply to them the predicate "sound"
    if (lcManager.sound(lcManager.selectCollects(regency, currentEid))) {

        Logger.println("(TOMLayer.catch_up) sound predicate is true");

        signedCollects = lcManager.getCollects(regency); // all original collects that the replica has received

        Consensus cons = new Consensus(-1); // the only purpose of this object is to obtain the batchsize,
        // using code inside of createPropose()

        propose = createPropose(cons);//w  w w .j  ava  2s . c  o  m
        batchSize = cons.batchSize;

        try { // serialization of the CATCH-UP message
            bos = new ByteArrayOutputStream();
            out = new ObjectOutputStream(bos);

            out.writeObject(lastHighestEid);

            //TODO: Missing: serialization of the proof

            out.writeInt(currentEid);
            out.writeObject(signedCollects);
            out.writeObject(propose);
            out.writeInt(batchSize);

            out.flush();
            bos.flush();

            byte[] payload = bos.toByteArray();
            out.close();
            bos.close();

            Logger.println("(TOMLayer.catch_up) sending SYNC message for regency " + regency);

            // send the CATCH-UP message
            communication.send(this.controller.getCurrentViewOtherAcceptors(), new LCMessage(
                    this.controller.getStaticConf().getProcessId(), TOMUtil.SYNC, regency, payload));

            finalise(regency, lastHighestEid, currentEid, signedCollects, propose, batchSize, true);

        } catch (IOException ex) {
            ex.printStackTrace();
            java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                out.close();
                bos.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                java.util.logging.Logger.getLogger(TOMLayer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
}