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

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

Introduction

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

Prototype

public DeferredFileOutputStream(int threshold, String prefix, String suffix, File directory) 

Source Link

Document

Constructs an instance of this class which will trigger an event at the specified threshold, and save data to a temporary file beyond that point.

Usage

From source file:mitm.common.util.ReadableOutputStreamBuffer.java

/**
 * Creates a ReadableOutputStream. If the number of bytes written exceeds threshold, the data will
 * be stored in a temporary file. The caller should always call close to make sure the temp file
 * is deleted./* w w w . j a  v a  2s  .co  m*/
 */
public ReadableOutputStreamBuffer(int threshold) {
    buffer = new DeferredFileOutputStream(threshold, FileConstants.TEMP_FILE_PREFIX, null, null);
}

From source file:mitm.common.util.ClearableDeferredOutputStream.java

public ClearableDeferredOutputStream(int threshold, String prefix, String suffix, File directory) {
    this.threshold = threshold;
    this.prefix = prefix;
    this.suffix = suffix;
    this.directory = directory;

    delegate = new DeferredFileOutputStream(threshold, prefix, suffix, directory);
    bufferedDelegate = new BufferedOutputStream(delegate);
}

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

/**
 * Saves the MimePart to the output stream
 * @param part/*  w  w w.j a v  a 2s . com*/
 * @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:mitm.common.extractor.impl.TextExtractorUtils.java

/**
 * conveniance method that writes data and fires a 
 * {@link TextExtractorEventHandler#textEvent(mitm.common.extractor.ExtractedPart)} event. The Data is written
 * to disk if total bytes exceed threshold. If total bytes written exceeds maxSize, an IOException will
 * be thrown./*  www .jav  a  2s  .  com*/
 * 
 */
public static void fireTextEvent(TextExtractorEventHandler handler, TextExtractorContext context,
        TextExtractorWriterHandler writerHandler, int threshold, long maxSize) throws IOException {
    Check.notNull(handler, "handler");
    Check.notNull(writerHandler, "writerHandler");

    DeferredFileOutputStream output = new DeferredFileOutputStream(threshold, FileConstants.TEMP_FILE_PREFIX,
            null, null);

    RewindableInputStream content = null;

    try {
        /*
         * Wrap the output in a buffered stream and protect against 'zip bombs'.
         */
        SizeLimitedOutputStream buffered = new SizeLimitedOutputStream(new BufferedOutputStream(output),
                maxSize);

        Writer writer = new OutputStreamWriter(buffered, TextExtractor.ENCODING);

        try {
            writerHandler.write(writer);
        } finally {
            /*
             * Must close to make sure all data is written. 
             * 
             * Note: if DeferredFileOutputStream uses a file, the file should NOT 
             * be deleted here because it will be deleted when the returned 
             * DeferredBufferedInputStream is closed.
             */
            writer.close();
        }

        content = new RewindableInputStream(MiscIOUtils.toInputStream(output), threshold);

        handler.textEvent(new ExtractedPartImpl(context, content, buffered.getByteCount()));
    } catch (IOException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    } catch (RuntimeException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    }
}

From source file:mitm.common.util.ClearableDeferredOutputStream.java

/**
 * Write the current output of this stream to output. If autoClose is true, the stream will be closed. 
 *///  w ww .j a  v  a2 s  .  c  o m
public void writeTo(OutputStream output, boolean autoClose) throws IOException {
    checkClosed();

    /*
     * We must first close the delegate stream before we can write to output to be 100% certain that all 
     * data written. If we would not close it, it can happen that not all data is written to the file when 
     * we try to read from the file.
     */
    bufferedDelegate.close();

    delegate.writeTo(output);

    DeferredFileOutputStream newDelegate = null;

    if (!autoClose) {
        /*
         * We should create a new DeferredFileOutputStream and copy the existing data to it
         */
        newDelegate = new DeferredFileOutputStream(threshold, prefix, suffix, directory);

        delegate.writeTo(newDelegate);
    } else {
        closed = true;
    }

    /*
     * Make sure the old temp file is deleted
     */
    deleteFile();

    if (newDelegate != null) {
        /*
         * Set the new DeferredFileOutputStream
         */
        delegate = newDelegate;
        bufferedDelegate = new BufferedOutputStream(delegate);
    }
}

From source file:mitm.common.util.ClearableDeferredOutputStream.java

public void clear() throws IOException {
    checkClosed();//  w  w  w  .  jav  a  2s  . c  o  m

    cleanup();

    delegate = new DeferredFileOutputStream(threshold, prefix, suffix, directory);
    bufferedDelegate = new BufferedOutputStream(delegate);
}

From source file:hudson.gridmaven.SplittableBuildListener.java

private DeferredFileOutputStream newLog() {
    return new DeferredFileOutputStream(10 * 1024, "maven-build", "log", null);
}

From source file:mitm.common.extractor.impl.TextExtractorUtils.java

/**
 * conveniance method that writes data and fires a 
 * {@link TextExtractorEventHandler#textEvent(mitm.common.extractor.ExtractedPart)} event. The Data is written
 * to disk if total bytes exceed threshold. If total bytes written exceeds maxSize, an IOException will
 * be thrown.//from ww  w .jav a2s . c  o  m
 * 
 */
public static void fireAttachmentEvent(TextExtractorEventHandler handler, TextExtractorContext context,
        TextExtractorAttachmentHandler attachmentHandler, int threshold, long maxSize) throws IOException {
    Check.notNull(handler, "handler");
    Check.notNull(attachmentHandler, "attachmentHandler");

    DeferredFileOutputStream output = new DeferredFileOutputStream(threshold, FileConstants.TEMP_FILE_PREFIX,
            null, null);

    RewindableInputStream content = null;

    try {
        /*
         * Wrap the output in a buffered stream and protect against 'zip bombs'.
         */
        SizeLimitedOutputStream buffered = new SizeLimitedOutputStream(new BufferedOutputStream(output),
                maxSize);

        try {
            attachmentHandler.write(buffered);
        } finally {
            /*
             * Must close to make sure all data is written. 
             * 
             * Note: if DeferredFileOutputStream uses a file, the file should NOT 
             * be deleted here because it will be deleted when the returned 
             * DeferredBufferedInputStream is closed.
             */
            buffered.close();
        }

        content = new RewindableInputStream(MiscIOUtils.toInputStream(output), threshold);

        handler.attachmentEvent(new ExtractedPartImpl(context, content, buffered.getByteCount()));
    } catch (IOException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    } catch (RuntimeException e) {
        /*
         * Must close the RewindableInputStream to prevent a possible temp file leak
         */
        IOUtils.closeQuietly(content);

        /*
         * Delete the tempfile (if) used by DeferredFileOutputStream.
         */
        IOUtils.closeQuietly(output);
        FileUtils.deleteQuietly(output.getFile());

        throw e;
    }
}

From source file:com.alibaba.citrus.service.upload.impl.cfu.AbstractFileItem.java

/**
 * Returns an {@link java.io.OutputStream OutputStream} that can be used for
 * storing the contents of the file.//from   ww w  .ja va 2s  .  c  om
 *
 * @return An {@link java.io.OutputStream OutputStream} that can be used for
 *         storing the contensts of the file.
 * @throws IOException if an error occurs.
 */
public OutputStream getOutputStream() throws IOException {
    if (dfos == null) {
        int sizeThreshold;

        if (keepFormFieldInMemory && isFormField()) {
            sizeThreshold = Integer.MAX_VALUE;
        } else {
            sizeThreshold = this.sizeThreshold;
        }

        dfos = new DeferredFileOutputStream(sizeThreshold, "upload_" + UID, ".tmp", repository);
    }
    return dfos;
}

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  a2  s. com
    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);
    }
}