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:org.apache.kylin.metadata.MetadataManager.java

public void saveTableExd(String tableId, Map<String, String> tableExdProperties) throws IOException {
    if (tableId == null) {
        throw new IllegalArgumentException("tableId couldn't be null");
    }//  w w  w .j  a  va  2  s  . com
    TableDesc srcTable = srcTableMap.get(tableId);
    if (srcTable == null) {
        throw new IllegalArgumentException("Couldn't find Source Table with identifier: " + tableId);
    }

    String path = TableDesc.concatExdResourcePath(tableId);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    JsonUtil.writeValueIndent(os, tableExdProperties);
    os.flush();
    InputStream is = new ByteArrayInputStream(os.toByteArray());
    getStore().putResource(path, is, System.currentTimeMillis());
    os.close();
    is.close();

    srcTableExdMap.put(tableId, tableExdProperties);
}

From source file:deployer.TestUtils.java

public static ByteBuffer createSampleOpenShiftWebAppTarBallWithEmptyFiles(String[] filepaths)
        throws IOException, ArchiveException {
    ByteArrayInputStream bis = new ByteArrayInputStream(createSampleAppTarBall(ArtifactType.WebApp).array());
    CompressorInputStream cis = new GzipCompressorInputStream(bis);
    ArchiveInputStream ais = new TarArchiveInputStream(cis);

    ByteArrayOutputStream bos = new ByteArrayOutputStream(bis.available() + 2048);
    CompressorOutputStream cos = new GzipCompressorOutputStream(bos);
    ArchiveOutputStream aos = new TarArchiveOutputStream(cos);

    ArchiveEntry nextEntry;/*from ww w  . j  a v  a  2  s  .  co  m*/
    while ((nextEntry = ais.getNextEntry()) != null) {
        aos.putArchiveEntry(nextEntry);
        IOUtils.copy(ais, aos);
        aos.closeArchiveEntry();
    }
    ais.close();
    cis.close();
    bis.close();

    TarArchiveEntry entry = new TarArchiveEntry(
            Paths.get(".openshift", CONFIG_DIRECTORY, "/standalone.xml").toFile());
    byte[] xmlData = SAMPLE_STANDALONE_DATA.getBytes();
    entry.setSize(xmlData.length);
    aos.putArchiveEntry(entry);
    IOUtils.write(xmlData, aos);

    for (int i = 0; i < filepaths.length; i++) {
        String filepath = filepaths[i];
        TarArchiveEntry emptyEntry = new TarArchiveEntry(Paths.get(filepath).toFile());
        byte[] emptyData = "".getBytes();
        emptyEntry.setSize(emptyData.length);
        aos.putArchiveEntry(emptyEntry);
        IOUtils.write(emptyData, aos);
        aos.closeArchiveEntry();
    }

    aos.finish();
    cos.close();
    bos.flush();
    return ByteBuffer.wrap(bos.toByteArray());
}

From source file:ispok.pres.bb.VisitorEdit.java

public StreamedContent getPhotoThumb() {

    if (visitorDto == null) {
        return null;
    }//from   w w  w.  j av a  2 s.c om

    BufferedImage bi = null;
    try {
        byte[] photoData = visitorDto.getPhoto();
        if (photoData == null) {
            return null;
        }
        bi = ImageIO.read(new ByteArrayInputStream(visitorDto.getPhoto()));
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(VisitorEdit.class.getName()).log(Level.SEVERE, null, ex);
    }

    int width = bi.getWidth();
    int height = bi.getHeight();
    float scaleFactorThumb;
    if (height > width) {
        scaleFactorThumb = (float) 200 / height;
    } else {
        scaleFactorThumb = (float) 200 / width;
    }

    int thumbWidth = (int) (width * scaleFactorThumb);
    int thumbHeight = (int) (height * scaleFactorThumb);

    BufferedImage thumbPhotoImage = ImageUtil.resizeImage(bi, thumbWidth, thumbHeight);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        ImageIO.write(thumbPhotoImage, "png", baos);
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(VisitorEdit.class.getName()).log(Level.SEVERE, null, ex);
    }
    try {
        baos.flush();
    } catch (IOException ex) {
        java.util.logging.Logger.getLogger(VisitorEdit.class.getName()).log(Level.SEVERE, null, ex);
    }

    InputStream is = new ByteArrayInputStream(baos.toByteArray());

    return new DefaultStreamedContent(is, "image/png");

}

From source file:org.alfresco.extensions.bulkexport.dao.AlfrescoExportDaoImpl.java

/**
 * @see com.alfresco.bulkexport.dao.AlfrescoExportDao#getContent(java.lang.String)
 *///from w w  w.  j  a v a  2s.com
public ByteArrayOutputStream getContent(NodeRef nodeRef) throws Exception {
    ContentReader reader = contentService.getReader(nodeRef, ContentModel.PROP_CONTENT);
    if (reader == null) {
        // no data for this node
        return null;
    }

    InputStream in = reader.getContentInputStream();
    int size = in.available();

    ByteArrayOutputStream out = new ByteArrayOutputStream();
    byte[] buf = new byte[(size + 100)];
    int sizeOut;

    while ((sizeOut = in.read(buf)) != -1) {
        out.write(buf, 0, sizeOut);
    }

    out.flush();
    out.close();

    in.close();

    return out;
}

From source file:com.liferay.mobile.android.async.FileDownloadAsyncTest.java

@Test
public void download() throws Exception {
    BasicAuthentication basic = (BasicAuthentication) session.getAuthentication();

    DigestAuthentication digest = new DigestAuthentication(basic.getUsername(), basic.getPassword());

    session.setAuthentication(digest);/*w w w. j ava  2  s.c o  m*/

    String url = session.getServer() + "/webdav/guest/document_library/"
            + _file.getString(DLAppServiceTest.TITLE);

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    final CountDownLatch lock = new CountDownLatch(1);

    FileProgressCallback fileProgressCallback = new FileProgressCallback() {

        @Override
        public void onBytes(byte[] bytes) {
            try {
                baos.write(bytes);
            } catch (IOException ioe) {
                fail(ioe.getMessage());
            }
        }

        @Override
        public void onProgress(int totalBytes) {
            if (totalBytes == 5) {
                try {
                    baos.flush();
                } catch (IOException ioe) {
                    fail(ioe.getMessage());
                }
            }
        }

    };

    session.setCallback(new Callback() {

        @Override
        public void inBackground(Response response) {
            assertEquals(Status.OK, response.getStatusCode());
            lock.countDown();
        }

        @Override
        public void doFailure(Exception exception) {
            fail(exception.getMessage());
            lock.countDown();
        }

    });

    HttpUtil.download(session, url, fileProgressCallback);
    lock.await(500, TimeUnit.MILLISECONDS);
    assertEquals(5, baos.size());
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Builds up a new message from the passed message parts
 * @param messageType one of the message types definfed in the class AS2Message
 *///from   w  w  w  .j  a v  a  2 s.c om
public AS2Message createMessage(Partner sender, Partner receiver, File[] payloadFiles, int messageType)
        throws Exception {
    //create payloads from the payload files
    AS2Payload[] payloads = new AS2Payload[payloadFiles.length];
    for (int i = 0; i < payloadFiles.length; i++) {
        File payloadFile = payloadFiles[i];
        InputStream inStream = new FileInputStream(payloadFile);
        ByteArrayOutputStream payloadOut = new ByteArrayOutputStream();
        this.copyStreams(inStream, payloadOut);
        inStream.close();
        payloadOut.flush();
        payloadOut.close();
        //add payload
        AS2Payload payload = new AS2Payload();
        payload.setData(payloadOut.toByteArray());
        payload.setOriginalFilename(payloadFile.getName().replace(' ', '_'));
        payloads[i] = payload;
    }
    return (this.createMessage(sender, receiver, payloads, messageType));
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Encrypts a byte array and returns it*/
private void encryptDataToMessage(AS2Message message, String receiverCryptAlias, int encryptionType,
        Partner receiver) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    X509Certificate certificate = this.encryptionCertManager.getX509Certificate(receiverCryptAlias);
    CMSEnvelopedDataStreamGenerator dataGenerator = new CMSEnvelopedDataStreamGenerator();
    dataGenerator.addKeyTransRecipient(certificate);
    DeferredFileOutputStream encryptedOutput = new DeferredFileOutputStream(1024 * 1024, "as2encryptdata_",
            ".mem", null);
    OutputStream out = null;/*  w w  w .j a  v a2 s  . c o m*/
    if (encryptionType == AS2Message.ENCRYPTION_3DES) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.DES_EDE3_CBC, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_DES) {
        out = dataGenerator.open(encryptedOutput,
                cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_DES), 56, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC2_40) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.RC2_CBC, 40, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC2_64) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.RC2_CBC, 64, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC2_128) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.RC2_CBC, 128, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC2_196) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.RC2_CBC, 196, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_AES_128) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.AES128_CBC, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_AES_192) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.AES192_CBC, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_AES_256) {
        out = dataGenerator.open(encryptedOutput, CMSEnvelopedDataGenerator.AES256_CBC, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC4_40) {
        out = dataGenerator.open(encryptedOutput,
                cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4), 40, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC4_56) {
        out = dataGenerator.open(encryptedOutput,
                cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4), 56, "BC");
    } else if (encryptionType == AS2Message.ENCRYPTION_RC4_128) {
        out = dataGenerator.open(encryptedOutput,
                cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_RC4), 128, "BC");
    }
    if (out == null) {
        throw new Exception("Internal failure: unsupported encryption type " + encryptionType);
    }
    out.write(message.getDecryptedRawData());
    out.close();
    encryptedOutput.close();
    //size of the data was < than the threshold
    if (encryptedOutput.isInMemory()) {
        message.setRawData(encryptedOutput.getData());
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        encryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = encryptedOutput.getFile().delete();
        message.setRawData(memOut.toByteArray());
    }
    if (this.logger != null) {
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.logger.log(Level.INFO, this.rb.getResourceString("message.encrypted",
                new Object[] { info.getMessageId(), cryptAlias,
                        this.rbMessage.getResourceString("encryption." + receiver.getEncryptionType()) }),
                info);
    }
}

From source file:de.mendelson.comm.as2.message.AS2MessageCreation.java

/**Prepares the message if it contains no MIME structure*/
public AS2Message createMessageNoMIME(AS2Message message, Partner receiver) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    BCCryptoHelper cryptoHelper = new BCCryptoHelper();
    //payload content type.
    message.setContentType(receiver.getContentType());
    message.setRawData(message.getPayload(0).getData());
    message.setDecryptedRawData(message.getPayload(0).getData());
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("message.notsigned", new Object[] { info.getMessageId() }), info);
    }//  www  .  j  a v a2s.  c om
    //compute content mic. Use sha1 as hash alg.
    String digestOID = cryptoHelper.convertAlgorithmNameToOID(BCCryptoHelper.ALGORITHM_SHA1);
    String mic = cryptoHelper.calculateMIC(message.getPayload(0).getData(), digestOID);
    info.setReceivedContentMIC(mic + ", sha1");
    //add compression
    if (receiver.getCompressionType() == AS2Message.COMPRESSION_ZLIB) {
        info.setCompressionType(AS2Message.COMPRESSION_ZLIB);
        int uncompressedSize = message.getDecryptedRawData().length;
        MimeBodyPart bodyPart = this.compressPayload(receiver, message.getDecryptedRawData(),
                receiver.getContentType());
        int compressedSize = bodyPart.getSize();
        //sometimes size() is unable to determine the size of the compressed body part and will return -1. Dont log the
        //compression ratio in this case.
        if (compressedSize == -1) {
            if (this.logger != null) {
                this.logger.log(Level.INFO, this.rb.getResourceString("message.compressed.unknownratio",
                        new Object[] { info.getMessageId() }), info);
            }
        } else {
            if (this.logger != null) {
                this.logger.log(Level.INFO,
                        this.rb.getResourceString("message.compressed",
                                new Object[] { info.getMessageId(),
                                        AS2Tools.getDataSizeDisplay(uncompressedSize),
                                        AS2Tools.getDataSizeDisplay(compressedSize) }),
                        info);
            }
        }
        //write compressed data into the message array
        ByteArrayOutputStream bodyOutStream = new ByteArrayOutputStream();
        bodyPart.writeTo(bodyOutStream);
        bodyOutStream.flush();
        bodyOutStream.close();
        message.setDecryptedRawData(bodyOutStream.toByteArray());
    }
    //no encryption
    if (info.getEncryptionType() == AS2Message.ENCRYPTION_NONE) {
        if (this.logger != null) {
            this.logger.log(Level.INFO,
                    this.rb.getResourceString("message.notencrypted", new Object[] { info.getMessageId() }),
                    info);
        }
        message.setRawData(message.getDecryptedRawData());
    } else {
        //encrypt the message raw data
        String cryptAlias = this.encryptionCertManager
                .getAliasByFingerprint(receiver.getCryptFingerprintSHA1());
        this.encryptDataToMessage(message, cryptAlias, info.getEncryptionType(), receiver);
    }
    return (message);
}

From source file:de.uni_rostock.goodod.owl.comparison.TripleBasedEntitySimComparator.java

/**
 * Serialized an ontology to an in-memory RDF/XML representation. This is required for 
 * deserializing it using the JENA API.//from  w w  w  .  ja  va2 s . c  om
 * @param ont The ontology to serialize
 * @return A byte array output stream containing an RDF/XML serialization of the ontology.
 * @throws OWLOntologyStorageException 
 * @throws IOException 
 */
private ByteArrayOutputStream outputStreamForOntology(OWLOntology ont)
        throws OWLOntologyStorageException, IOException {
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    OWLOntologyManager manager = ont.getOWLOntologyManager();
    // Since JENA might not play very well with imports, we remove them,
    // although it is a tad suboptimal.
    Set<OWLImportsDeclaration> imports = ont.getImportsDeclarations();
    for (OWLImportsDeclaration i : imports) {
        manager.applyChange(new RemoveImport(ont, i));
    }
    RDFXMLOntologyFormat fmt = new RDFXMLOntologyFormat();

    manager.saveOntology(ont, fmt, stream);
    // Make sure all writes end up in the buffer:
    stream.flush();
    return stream;
}

From source file:com.phonegap.api.impl.NetworkCommand.java

private JSONObject readFileData(String filePath) throws Exception {
    FileConnection fileConnection = null;
    try {/*ww w. j  a va 2  s .  co m*/
        fileConnection = (FileConnection) Connector.open(filePath, Connector.READ);
        long fileSize = fileConnection.fileSize();
        long lastModified = fileConnection.lastModified();
        String fileName = fileConnection.getName();
        InputStream fileStream = fileConnection.openInputStream();
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        Base64OutputStream base64OutStream = new Base64OutputStream(outStream);
        int byteRead = 0;
        while ((byteRead = fileStream.read()) != -1) {
            base64OutStream.write(byteRead);
        }
        base64OutStream.flush();
        base64OutStream.close();
        outStream.flush();
        String base64Data = outStream.toString();
        outStream.close();

        JSONObject fileData = new JSONObject();
        fileData.put("file", base64Data);
        fileData.put("filename", fileName);
        fileData.put("filesize", fileSize);
        fileData.put("timestamp", lastModified);
        fileData.put("filemime", getMimeType(fileName));
        LogCommand.DEBUG(
                "Successfully read file " + filePath + ". Base 64 Data length is " + base64Data.length());
        return fileData;
    } catch (Exception e) {
        LogCommand.LOG("Fail to read file " + filePath + ". " + e.getMessage());
        throw e;
    } finally {
        if (fileConnection != null && fileConnection.isOpen()) {
            try {
                fileConnection.close();
            } catch (IOException e) {
            }
        }
    }

}