private static InputStream doExtractResponseBodyAsStream(InputStream is, Exchange exchange) throws IOException { // As httpclient is using a AutoCloseInputStream, it will be closed when the connection is closed // we need to cache the stream for it. CachedOutputStream cos = null; try { // This CachedOutputStream will not be closed when the exchange is onCompletion cos = new CachedOutputStream(exchange, false); IOHelper.copy(is, cos); // When the InputStream is closed, the CachedOutputStream will be closed return cos.getWrappedInputStream(); } catch (IOException ex) { // try to close the CachedOutputStream when we get the IOException try { cos.close(); } catch (IOException ignore) { //do nothing here } throw ex; } finally { IOHelper.close(is, "Extracting response body", LOG); } }
@Converter public static InputStream soapMessageToInputStream(final SOAPMessage soapMessage, Exchange exchange) throws SOAPException, IOException { CachedOutputStream cos = new CachedOutputStream(exchange); soapMessage.writeTo(cos); InputStream in = cos.getInputStream(); return in; }
/** * Reads the response body from the given input stream. * * @param is the input stream * @param exchange the exchange * @return the response body, can be <tt>null</tt> if no body * @throws IOException is thrown if error reading response body */ public static Object readResponseBodyFromInputStream(InputStream is, Exchange exchange) throws IOException { if (is == null) { return null; } // convert the input stream to StreamCache if the stream cache is not disabled if (exchange.getProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, Boolean.FALSE, Boolean.class)) { return is; } else { CachedOutputStream cos = new CachedOutputStream(exchange); IOHelper.copyAndCloseInput(is, cos); return cos.newStreamCache(); } }
private Object transformToStreamCacheOrByteArray(Exchange exchange, InputStream is) throws CryptoCmsException { // the input stream must be completely read, outherwise you will get // errors when your use as next component the file adapter. OutputStreamBuilder output = OutputStreamBuilder.withExchange(exchange); try { // data can be null in the case of explicit Signed Data if (is != null) { try { IOHelper.copy(is, output); } finally { IOHelper.close(is); } } LOG.debug("CMS Enveloped Data decryption successful"); return output.build(); } catch (IOException e) { throw new CryptoCmsException("Error during reading the unencrypted content of the enveloped data object", e); } finally { IOHelper.close(output); } }
reader = new DelegatingXMLStreamReader(reader, nsmap); CachedOutputStream cos = new CachedOutputStream(exchange); try { StaxUtils.copy(reader, cos); li.set(new StreamSourceCache(cos.newStreamCache())); try { xml.toResult(source, sr); li.set(new StreamSourceCache(cos.newStreamCache()));
osb = OutputStreamBuilder.withExchange(exchange); osb.write(buffer, 0, bytesRead); if (signature != null) { signature.update(buffer, 0, bytesRead); osb.flush(); return osb.build();
ServletOutputStream os = response.getOutputStream(); if (!checkChunked(message, exchange)) { CachedOutputStream stream = new CachedOutputStream(exchange); try { OutputStream current = stream.getCurrentStream(); if (current instanceof ByteArrayOutputStream) { if (LOG.isDebugEnabled()) { LOG.debug("Streaming response in non-chunked mode with content-length {} and buffer size: {}", len, len); copyStream(stream.getInputStream(), os, len);
protected OutputStreamBuilder getOutputStream(CMSSignedDataParser sp, Exchange exchange) throws Exception { // get the InputStream with the plain data InputStream data; try { data = sp.getSignedContent().getContentStream(); } catch (NullPointerException e) { // nullpointer exception is // thrown when the signed content // is missing throw getContentMissingException(e); } // the input stream must be completely read, otherwise the signer // info is not available! OutputStreamBuilder osb = OutputStreamBuilder.withExchange(exchange); try { // data can be null in the case of explicit Signed Data if (data != null) { try { IOHelper.copy(data, osb); } finally { IOHelper.close(data); } } } catch (IOException e) { throw new CryptoCmsException("Error during reading the signed content of the signed data object", e); } return osb; }
@Override protected Object unmarshalInternal(InputStream is, Exchange exchange) throws Exception { CMSSignedDataParser sp; try { sp = new CMSSignedDataParser(new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build(), is); } catch (CMSException e) { throw new CryptoCmsFormatException(getFormatErrorMessage(), e); } OutputStreamBuilder output = getOutputStream(sp, exchange); debugLog(sp); verify(sp, exchange); return output.build(); }
@Converter public static Payload toPayload(StreamSource source, Exchange exchange) throws IOException { return toPayload(new StreamSourceCache(source, exchange), exchange); }
@Converter public static Payload toPayload(final StreamSourceCache cache, Exchange exchange) throws IOException { long contentLength = ByteStreams.toByteArray(cache.getInputStream()).length; cache.reset(); InputStreamPayload payload = new InputStreamPayload(cache.getInputStream()); payload.getContentMetadata().setContentLength(contentLength); setContentMetadata(payload, exchange); return payload; }
@Override public Object unmarshal(final Exchange exchange, final InputStream inputStream) throws Exception { if (usingIterator) { ZipIterator zipIterator = new ZipIterator(exchange, inputStream); zipIterator.setAllowEmptyDirectory(allowEmptyDirectory); return zipIterator; } else { ZipInputStream zis = new ZipInputStream(inputStream); OutputStreamBuilder osb = OutputStreamBuilder.withExchange(exchange); try { ZipEntry entry = zis.getNextEntry(); if (entry != null) { exchange.getOut().setHeader(FILE_NAME, entry.getName()); IOHelper.copy(zis, osb); } entry = zis.getNextEntry(); if (entry != null) { throw new IllegalStateException("Zip file has more than 1 entry."); } return osb.build(); } finally { IOHelper.close(zis, osb); } } }
private static Object extractResponseBodyAsStream(final InputStream is, final Exchange exchange) { // As httpclient is using a AutoCloseInputStream, it will be closed when the connection is closed // we need to cache the stream for it. if (is == null) { return null; } // convert the input stream to StreamCache if the stream cache is not disabled if (exchange.getProperty(DISABLE_HTTP_STREAM_CACHE, FALSE, Boolean.class)) { return is; } else { try (final CachedOutputStream cos = new CachedOutputStream(exchange)) { // This CachedOutputStream will not be closed when the exchange is onCompletion IOHelper.copyAndCloseInput(is, cos); // When the InputStream is closed, the CachedOutputStream will be closed return cos.newStreamCache(); } catch (IOException ex) { LOGGER.debug("Error extracting body from http request", ex); return null; } } } }
protected Object createByteArrayFromBytesMessage(Exchange exchange, BytesMessage message) throws JMSException { // ActiveMQ has special optimised mode for bytes message, so we should use streaming if possible Long size = getSafeLongProperty(message, "_AMQ_LARGE_SIZE"); if (size != null && size > 0) { LOG.trace("Optimised for Artemis: Reading from BytesMessage in streaming mode directly into CachedOutputStream payload"); CachedOutputStream cos = new CachedOutputStream(exchange, true); // this will save the stream and wait until the entire message is written before continuing. message.setObjectProperty("JMS_AMQ_SaveStream", cos); try { // and then lets get the input stream of this so we can read it return cos.getInputStream(); } catch (IOException e) { JMSException cause = new MessageFormatException(e.getMessage()); cause.initCause(e); throw cause; } finally { IOHelper.close(cos); } } if (message.getBodyLength() > Integer.MAX_VALUE) { LOG.warn("Length of BytesMessage is too long: {}", message.getBodyLength()); return null; } byte[] result = new byte[(int)message.getBodyLength()]; message.readBytes(result); return result; }
private Map.Entry<String, Object> downloadSingleFile(String path) throws DropboxException { try { OutputStreamBuilder target = OutputStreamBuilder.withExchange(exchange); DbxDownloader<FileMetadata> downloadedFile = client.files().download(path); if (downloadedFile != null) { downloadedFile.download(target); LOG.debug("downloaded path={}", path); return new AbstractMap.SimpleEntry<>(path, target.build()); } else { return null; } } catch (DbxException e) { throw new DropboxException(path + " does not exist or cannot obtain metadata", e); } catch (IOException e) { throw new DropboxException(path + " cannot obtain a stream", e); } } }
/** * Reads the response body from the given input stream. * * @param is the input stream * @param exchange the exchange * @return the response body, can be <tt>null</tt> if no body * @throws IOException is thrown if error reading response body */ public static Object readRequestBodyFromInputStream(InputStream is, Exchange exchange) throws IOException { if (is == null) { return null; } boolean disableStreamCaching = false; // Just take the consideration of the setting of Camel Context StreamCaching if (exchange.getContext() instanceof DefaultCamelContext) { DefaultCamelContext context = (DefaultCamelContext) exchange.getContext(); disableStreamCaching = !context.isStreamCaching(); } // convert the input stream to StreamCache if the stream cache is not disabled if (exchange.getProperty(Exchange.DISABLE_HTTP_STREAM_CACHE, disableStreamCaching, Boolean.class)) { return is; } else { CachedOutputStream cos = new CachedOutputStream(exchange); IOHelper.copyAndCloseInput(is, cos); return cos.newStreamCache(); } }
@Override public void process(Exchange exchange) throws Exception { // NOPMD all // exceptions must be caught to react on exception case and re-thrown, // see code below OutputStreamBuilder output = OutputStreamBuilder.withExchange(exchange); OutputStream outStream; if (config.getToBase64()) { outStream = new Base64OutputStream(output); } else { outStream = output; } InputStream body = exchange.getIn().getMandatoryBody(InputStream.class); // lets setup the out message before we invoke the processing // so that it can mutate it if necessary Message out = exchange.getOut(); out.copyFrom(exchange.getIn()); try { try { marshalInternal(body, outStream, exchange); } finally { IOHelper.close(outStream); // base64 stream must be closed, // before we fetch the bytes } setBodyAndHeader(out, output.build()); } catch (Throwable e) { // remove OUT message, as an exception occurred exchange.setOut(null); throw e; } }
@Override protected int poll() throws Exception { shutdownRunningTask = null; pendingExchanges = 0; Queue<Exchange> queue = new LinkedList<>(); String directory = endpoint.getDirectory(); ListContainerOptions opt = new ListContainerOptions(); if (!Strings.isNullOrEmpty(directory)) { opt = opt.inDirectory(directory); } for (StorageMetadata md : blobStore.list(container, opt.maxResults(maxMessagesPerPoll).recursive())) { String blobName = md.getName(); if (md.getType().equals(StorageType.BLOB)) { if (!Strings.isNullOrEmpty(blobName)) { InputStream body = JcloudsBlobStoreHelper.readBlob(blobStore, container, blobName); if (body != null) { Exchange exchange = endpoint.createExchange(); CachedOutputStream cos = new CachedOutputStream(exchange); IOHelper.copy(body, cos); exchange.getIn().setBody(cos.newStreamCache()); exchange.setProperty(JcloudsConstants.BLOB_NAME, blobName); queue.add(exchange); } } } } return queue.isEmpty() ? 0 : processBatch(CastUtils.cast(queue)); }
public Object unmarshal(final Exchange exchange, final InputStream encryptedStream) throws Exception { if (encryptedStream != null) { byte[] iv = getInlinedInitializationVector(exchange, encryptedStream); Key key = getKey(exchange); CipherInputStream cipherStream = null; OutputStreamBuilder osb = null; try { cipherStream = new CipherInputStream(encryptedStream, initializeCipher(DECRYPT_MODE, key, iv)); osb = OutputStreamBuilder.withExchange(exchange); HMACAccumulator hmac = getMessageAuthenticationCode(key); byte[] buffer = new byte[bufferSize]; hmac.attachStream(osb); int read; while ((read = cipherStream.read(buffer)) >= 0) { hmac.decryptUpdate(buffer, read); } hmac.validate(); return osb.build(); } finally { IOHelper.close(cipherStream, "cipher", LOG); IOHelper.close(osb, "plaintext", LOG); } } return null; }
@Override public Object unmarshal(final Exchange exchange, final InputStream stream) throws Exception { if (usingIterator) { TarIterator tarIterator = new TarIterator(exchange, stream); tarIterator.setAllowEmptyDirectory(allowEmptyDirectory); return tarIterator; } else { BufferedInputStream bis = new BufferedInputStream(stream); TarArchiveInputStream tis = (TarArchiveInputStream) new ArchiveStreamFactory().createArchiveInputStream(ArchiveStreamFactory.TAR, bis); OutputStreamBuilder osb = OutputStreamBuilder.withExchange(exchange); try { TarArchiveEntry entry = tis.getNextTarEntry(); if (entry != null) { exchange.getOut().setHeader(FILE_NAME, entry.getName()); IOHelper.copy(tis, osb); } entry = tis.getNextTarEntry(); if (entry != null) { throw new IllegalStateException("Tar file has more than 1 entry."); } return osb.build(); } finally { IOHelper.close(osb, tis, bis); } } }