Example usage for org.apache.commons.io.output DeferredFileOutputStream close

List of usage examples for org.apache.commons.io.output DeferredFileOutputStream close

Introduction

In this page you can find the example usage for org.apache.commons.io.output DeferredFileOutputStream close.

Prototype

public void close() throws IOException 

Source Link

Document

Closes underlying output stream, and mark this as closed

Usage

From source file:mitm.common.mail.MailUtils.java

/**
 * Saves the MimePart to the output stream
 * @param part/*from w w w . j a va 2  s .  c om*/
 * @param output
 * @throws IOException
 * @throws MessagingException
 */
public static void writeMessage(MimePart part, OutputStream output) throws IOException, MessagingException {
    /*
     * we need to store the result in a temporary buffer so we can fall back 
     * on a different procedure when writeTo fails. If not, MimePart#writeTo might
     * fail halfway and some data has already been written to output. 
     */
    DeferredFileOutputStream buffer = new DeferredFileOutputStream(SizeUtils.MB, FileConstants.TEMP_FILE_PREFIX,
            null, null);

    /*
     * First try the writeTo method. Sometimes this will fail when the message uses 
     * an unsupported or corrupt encoding. For example the content encoding says that
     * the message is base64 encoded but it is not.  
     */
    try {
        part.writeTo(buffer);

        /*
         * Need to close the DeferredFileOutputStream before we can write
         */
        buffer.close();

        /* 
         * writeTo was successful so we can copy the result to the final output
         */
        buffer.writeTo(output);
    } catch (IOException e) {
        writeMessageRaw(part, output);
    } catch (MessagingException e) {
        writeMessageRaw(part, output);
    } finally {
        /*
         * Delete any possible temp file used by DeferredFileOutputStream.
         */
        FileUtils.deleteQuietly(buffer.getFile());
    }
}

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

/**Decrypts the data of a message with all given certificates etc
 * @param info MessageInfo, the encryption algorith will be stored in the encryption type of this info
 * @param rawMessageData encrypted data, will be decrypted
 * @param contentType contentType of the data
 * @param privateKey receivers private key
 * @param certificate receivers certificate
 *///from w  w  w .ja  va2 s.c o  m
public byte[] decryptData(AS2Message message, byte[] data, String contentType, PrivateKey privateKeyReceiver,
        X509Certificate certificateReceiver, String receiverCryptAlias) throws Exception {
    AS2MessageInfo info = (AS2MessageInfo) message.getAS2Info();
    MimeBodyPart encryptedBody = new MimeBodyPart();
    encryptedBody.setHeader("content-type", contentType);
    encryptedBody.setDataHandler(new DataHandler(new ByteArrayDataSource(data, contentType)));
    RecipientId recipientId = new JceKeyTransRecipientId(certificateReceiver);
    SMIMEEnveloped enveloped = new SMIMEEnveloped(encryptedBody);
    BCCryptoHelper helper = new BCCryptoHelper();
    String algorithm = helper.convertOIDToAlgorithmName(enveloped.getEncryptionAlgOID());
    if (algorithm.equals(BCCryptoHelper.ALGORITHM_3DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_3DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_DES)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_DES);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC2)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC2_UNKNOWN);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_128)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_128);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_192)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_192);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_AES_256)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_AES_256);
    } else if (algorithm.equals(BCCryptoHelper.ALGORITHM_RC4)) {
        info.setEncryptionType(AS2Message.ENCRYPTION_RC4_UNKNOWN);
    } else {
        info.setEncryptionType(AS2Message.ENCRYPTION_UNKNOWN_ALGORITHM);
    }
    RecipientInformationStore recipients = enveloped.getRecipientInfos();
    enveloped = null;
    encryptedBody = null;
    RecipientInformation recipient = recipients.get(recipientId);
    if (recipient == null) {
        //give some details about the required and used cert for the decryption
        Collection recipientList = recipients.getRecipients();
        Iterator iterator = recipientList.iterator();
        while (iterator.hasNext()) {
            RecipientInformation recipientInfo = (RecipientInformation) iterator.next();
            if (this.logger != null) {
                this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.inforequired",
                        new Object[] { info.getMessageId(), recipientInfo.getRID() }), info);
            }
        }
        if (this.logger != null) {
            this.logger.log(Level.SEVERE, this.rb.getResourceString("decryption.infoassigned",
                    new Object[] { info.getMessageId(), receiverCryptAlias, recipientId }), info);
        }
        throw new AS2Exception(AS2Exception.AUTHENTIFICATION_ERROR,
                "Error decrypting the message: Recipient certificate does not match.", message);
    }
    //Streamed decryption. Its also possible to use in memory decryption using getContent but that uses
    //far more memory.
    InputStream contentStream = recipient
            .getContentStream(new JceKeyTransEnvelopedRecipient(privateKeyReceiver).setProvider("BC"))
            .getContentStream();
    //InputStream contentStream = recipient.getContentStream(privateKeyReceiver, "BC").getContentStream();
    //threshold set to 20 MB: if the data is less then 20MB perform the operaion in memory else stream to disk
    DeferredFileOutputStream decryptedOutput = new DeferredFileOutputStream(20 * 1024 * 1024, "as2decryptdata_",
            ".mem", null);
    this.copyStreams(contentStream, decryptedOutput);
    decryptedOutput.flush();
    decryptedOutput.close();
    contentStream.close();
    byte[] decryptedData = null;
    //size of the data was < than the threshold
    if (decryptedOutput.isInMemory()) {
        decryptedData = decryptedOutput.getData();
    } else {
        //data has been written to a temp file: reread and return
        ByteArrayOutputStream memOut = new ByteArrayOutputStream();
        decryptedOutput.writeTo(memOut);
        memOut.flush();
        memOut.close();
        //finally delete the temp file
        boolean deleted = decryptedOutput.getFile().delete();
        decryptedData = memOut.toByteArray();
    }
    if (this.logger != null) {
        this.logger.log(Level.INFO,
                this.rb.getResourceString("decryption.done.alias",
                        new Object[] { info.getMessageId(), receiverCryptAlias,
                                this.rbMessage.getResourceString("encryption." + info.getEncryptionType()) }),
                info);
    }
    return (decryptedData);
}

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;/*from   w  w  w  . j a  v  a  2  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:org.apache.maven.plugin.surefire.report.StatelessXmlReporter.java

private void addOutputStreamElement(OutputStreamWriter outputStreamWriter, OutputStream fw,
        EncodingOutputStream eos, XMLWriter xmlWriter, DeferredFileOutputStream stdOut, String name) {
    if (stdOut != null && stdOut.getByteCount() > 0) {

        xmlWriter.startElement(name);//from ww w. ja  v  a2  s . co  m

        try {
            xmlWriter.writeText(""); // Cheat sax to emit element
            outputStreamWriter.flush();
            stdOut.close();
            eos.getUnderlying().write("<![CDATA[".getBytes()); // emit cdata
            stdOut.writeTo(eos);
            eos.getUnderlying().write("]]>".getBytes());
            eos.flush();
        } catch (IOException e) {
            throw new ReporterException("When writing xml report stdout/stderr", e);
        }
        xmlWriter.endElement();
    }
}

From source file:org.apache.phoenix.iterate.SpoolingResultIterator.java

/**
* Create a result iterator by iterating through the results of a scan, spooling them to disk once
* a threshold has been reached. The scanner passed in is closed prior to returning.
* @param scanner the results of a table scan
* @param mm memory manager tracking memory usage across threads.
* @param thresholdBytes the requested threshold.  Will be dialed down if memory usage (as determined by
*  the memory manager) is exceeded./*from w w  w  .java 2s.co  m*/
* @throws SQLException
*/
SpoolingResultIterator(SpoolingMetricsHolder sMetrics, MemoryMetricsHolder mMetrics, ResultIterator scanner,
        MemoryManager mm, final int thresholdBytes, final long maxSpoolToDisk, final String spoolDirectory)
        throws SQLException {
    this.spoolMetrics = sMetrics;
    this.memoryMetrics = mMetrics;
    boolean success = false;
    long startTime = System.currentTimeMillis();
    final MemoryChunk chunk = mm.allocate(0, thresholdBytes);
    long waitTime = System.currentTimeMillis() - startTime;
    GLOBAL_MEMORY_WAIT_TIME.update(waitTime);
    memoryMetrics.getMemoryWaitTimeMetric().change(waitTime);
    DeferredFileOutputStream spoolTo = null;
    try {
        // Can't be bigger than int, since it's the max of the above allocation
        int size = (int) chunk.getSize();
        spoolTo = new DeferredFileOutputStream(size, "ResultSpooler", ".bin", new File(spoolDirectory)) {
            @Override
            protected void thresholdReached() throws IOException {
                try {
                    super.thresholdReached();
                } finally {
                    chunk.close();
                }
            }
        };
        DataOutputStream out = new DataOutputStream(spoolTo);
        final long maxBytesAllowed = maxSpoolToDisk == -1 ? Long.MAX_VALUE : thresholdBytes + maxSpoolToDisk;
        long bytesWritten = 0L;
        for (Tuple result = scanner.next(); result != null; result = scanner.next()) {
            int length = TupleUtil.write(result, out);
            bytesWritten += length;
            if (bytesWritten > maxBytesAllowed) {
                throw new SpoolTooBigToDiskException("result too big, max allowed(bytes): " + maxBytesAllowed);
            }
        }
        if (spoolTo.isInMemory()) {
            byte[] data = spoolTo.getData();
            chunk.resize(data.length);
            spoolFrom = new InMemoryResultIterator(data, chunk);
            GLOBAL_MEMORY_CHUNK_BYTES.update(data.length);
            memoryMetrics.getMemoryChunkSizeMetric().change(data.length);
        } else {
            long sizeOfSpoolFile = spoolTo.getFile().length();
            GLOBAL_SPOOL_FILE_SIZE.update(sizeOfSpoolFile);
            GLOBAL_SPOOL_FILE_COUNTER.increment();
            spoolMetrics.getNumSpoolFileMetric().increment();
            spoolMetrics.getSpoolFileSizeMetric().change(sizeOfSpoolFile);
            spoolFrom = new OnDiskResultIterator(spoolTo.getFile());
            if (spoolTo.getFile() != null) {
                spoolTo.getFile().deleteOnExit();
            }
        }
        success = true;
    } catch (IOException e) {
        throw ServerUtil.parseServerException(e);
    } finally {
        try {
            scanner.close();
        } finally {
            try {
                if (spoolTo != null) {
                    if (!success && spoolTo.getFile() != null) {
                        spoolTo.getFile().delete();
                    }
                    spoolTo.close();
                }
            } catch (IOException ignored) {
                // ignore close error
            } finally {
                if (!success) {
                    chunk.close();
                }
            }
        }
    }
}

From source file:org.geoserver.wms.topojson.TopologyBuilder.java

@Override
public RawMap build(WMSMapContent mapContent) throws IOException {

    Map<String, TopoGeom.GeometryColleciton> layers = new HashMap<>();
    for (String layer : this.layers.keySet()) {
        Collection<TopoGeom> collection = this.layers.get(layer);
        GeometryColleciton layerCollection = new TopoGeom.GeometryColleciton(collection);
        layers.put(layer, layerCollection);
    }// www .j  a va  2 s.  c  om

    List<LineString> arcs = this.arcs;
    this.arcs = null;
    this.layers = null;
    Topology topology = new Topology(screenToWorld, arcs, layers);

    final int threshold = 8096;
    DeferredFileOutputStream out = new DeferredFileOutputStream(threshold, "topology", ".topojson", null);
    TopoJSONEncoder encoder = new TopoJSONEncoder();

    Writer writer = new OutputStreamWriter(out, Charsets.UTF_8);
    encoder.encode(topology, writer);
    writer.flush();
    writer.close();
    out.close();

    long length;
    RawMap map;
    if (out.isInMemory()) {
        byte[] data = out.getData();
        length = data.length;
        map = new RawMap(mapContent, data, MIME_TYPE);
    } else {
        File f = out.getFile();
        length = f.length();
        map = new DeferredFileOutputStreamWebMap(mapContent, out, MIME_TYPE);
    }
    map.setResponseHeader("Content-Length", String.valueOf(length));

    return map;
}

From source file:org.geoserver.wms.vector.DeferredFileOutputStreamWebMap.java

public DeferredFileOutputStreamWebMap(WMSMapContent mapContent, DeferredFileOutputStream mapContents,
        String mimeType) throws IOException {

    super(mapContent, (byte[]) null, mimeType);
    // make sure the stream is closed to be able of retrieving its contents
    mapContents.close();
    this.mapContents = mapContents;
}