List of usage examples for org.apache.commons.io.output DeferredFileOutputStream writeTo
public void writeTo(OutputStream out) throws IOException
From source file:mitm.common.mail.MailUtils.java
/** * Saves the MimePart to the output stream * @param part// w w w . j a v a2 s .c o m * @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 *//*w ww . j ava 2 s .c om*/ 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 ww w .j ava2 s . c om*/ 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.resources.remote.ProcessRemoteResourcesMojo.java
/** * If the transformation result fits in memory and the destination file already exists * then both are compared./* w ww . j a v a2s . c o m*/ * <p>If destination file is byte-by-byte equal, then it is not overwritten. * This improves subsequent compilation times since upstream plugins property see that * the resource was not modified. * <p>Note: the method should be called after {@link org.apache.commons.io.output.DeferredFileOutputStream#close} * * @param outStream Deferred stream * @throws IOException */ private void fileWriteIfDiffers(DeferredFileOutputStream outStream) throws IOException { File file = outStream.getFile(); if (outStream.isThresholdExceeded()) { getLog().info("File " + file + " was overwritten due to content limit threshold " + outStream.getThreshold() + " reached"); return; } boolean needOverwrite = true; if (file.exists()) { InputStream is = new FileInputStream(file); InputStream newContents = new ByteArrayInputStream(outStream.getData()); try { needOverwrite = !IOUtil.contentEquals(is, newContents); if (getLog().isDebugEnabled()) { getLog().debug("File " + file + " contents " + (needOverwrite ? "differs" : "does not differ")); } } finally { IOUtil.close(is); } } if (!needOverwrite) { getLog().info("File " + file + " is up to date"); return; } getLog().info("Writing " + file); OutputStream os = new FileOutputStream(file); try { outStream.writeTo(os); } finally { IOUtil.close(os); } }
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 w ww .j a v a2 s .c o 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(); } }