@Override public void releaseRetrievedFileResources(Exchange exchange) throws GenericFileOperationFailedException { InputStream is = exchange.getIn().getHeader(RemoteFileComponent.REMOTE_FILE_INPUT_STREAM, InputStream.class); if (is != null) { try { IOHelper.close(is); client.completePendingCommand(); } catch (IOException e) { throw new GenericFileOperationFailedException(e.getMessage(), e); } } }
@Override public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { try (final OutputStreamWriter osw = new OutputStreamWriter(stream, IOHelper.getCharsetName(exchange)); final BufferedWriter writer = IOHelper.buffered(osw)) { gson.toJson(graph, writer); } if (contentTypeHeader) { if (exchange.hasOut()) { exchange.getOut().setHeader(Exchange.CONTENT_TYPE, "application/json"); } else { exchange.getIn().setHeader(Exchange.CONTENT_TYPE, "application/json"); } } }
protected int copyStream(InputStream is, OutputStream os, int bufferSize) throws IOException { try { // copy stream, and must flush on each write as etc Jetty has better performance when // flushing after writing to its servlet output stream return IOHelper.copy(is, os, bufferSize, true); } finally { IOHelper.close(os, is); } }
protected void findLocations(Set<String> locations, ClassLoader classLoader) throws IOException { Enumeration<URL> resources = classLoader.getResources(LOCATION_PROPERTIES); while (resources.hasMoreElements()) { URL url = resources.nextElement(); BufferedReader reader = IOHelper.buffered(new InputStreamReader(url.openStream(), UTF8)); try { while (true) { String line = reader.readLine(); if (line == null) { break; } line = line.trim(); if (line.startsWith("#") || line.length() == 0) { continue; } locations.add(line); } } finally { IOHelper.close(reader, null, LOG); } } }
InputStream is = new ByteArrayInputStream(combined.getBytes()); OutputStream os = new FileOutputStream(file, false); IOHelper.copyAndCloseInput(is, os); IOHelper.close(os);
public void process(Exchange exchange) throws Exception { String cacheKey = key.evaluate(exchange, String.class); if (isValid(cacheManager, cacheName, cacheKey)) { Ehcache cache = cacheManager.getCache(cacheName); if (LOG.isDebugEnabled()) { LOG.debug("Replacing Token {} in Message with value stored against key {} in CacheName {}", new Object[]{replacementToken, cacheKey, cacheName}); } exchange.getIn().setHeader(CacheConstants.CACHE_KEY, cacheKey); Object body = exchange.getIn().getBody(); InputStream is = exchange.getContext().getTypeConverter().convertTo(InputStream.class, body); byte[] buffer; try { buffer = IOConverter.toBytes(is); } finally { IOHelper.close(is, "is", LOG); } // Note: The value in the cache must be a String String cacheValue = exchange.getContext().getTypeConverter() .convertTo(String.class, cache.get(cacheKey).getObjectValue()); String replacedTokenString = new String(buffer).replaceAll(replacementToken, cacheValue); LOG.trace("replacedTokenString = {}", replacedTokenString); exchange.getIn().setBody(replacedTokenString.getBytes()); } }
@Override public Object toHttpResponse(HttpServerExchange httpExchange, Message message) throws IOException { boolean failed = message.getExchange().isFailed(); int defaultCode = failed ? 500 : 200; int code = message.getHeader(Exchange.HTTP_RESPONSE_CODE, defaultCode, int.class); TypeConverter tc = message.getExchange().getContext().getTypeConverter(); Object value = entry.getValue(); final Iterator<?> it = ObjectHelper.createIterator(value, null); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next()); if (headerValue != null && headerFilterStrategy != null && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, message.getExchange())) { Object body = message.getBody(); Exception exception = message.getExchange().getException(); oos.writeObject(exception); oos.flush(); IOHelper.close(oos, bos);
@Override public void marshal(final Exchange exchange, final Object graph, final OutputStream stream) throws Exception { String filename; String filepath = exchange.getIn().getHeader(FILE_NAME, String.class); if (filepath == null) { // generate the file name as the camel file component would do filename = filepath = StringHelper.sanitize(exchange.getIn().getMessageId()); } else { filename = Paths.get(filepath).getFileName().toString(); // remove any path elements } ZipOutputStream zos = new ZipOutputStream(stream); if (preservePathElements) { createZipEntries(zos, filepath); } else { createZipEntries(zos, filename); } InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph); try { IOHelper.copy(is, zos); } finally { IOHelper.close(is, zos); } String newFilename = filename + ".zip"; exchange.getOut().setHeader(FILE_NAME, newFilename); }
if (exchange.getIn().getBody() == null) { is = new ByteArrayInputStream(exchange.getIn().getMandatoryBody(String.class).getBytes(charset)); log.trace("Using InputStream {} with charset {}.", is, charset); } else { is = exchange.getIn().getMandatoryBody(InputStream.class); if (ObjectHelper.isNotEmpty(chmod)) { log.debug("Setting chmod: {} on file: {}", chmod, targetName); String command = "chmod " + chmod + " " + targetName; throw new GenericFileOperationFailedException("Cannot store file: " + name, e); } finally { IOHelper.close(is, "store: " + name, log);
@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 InputStream stream = exchange.getIn().getMandatoryBody(InputStream.class); try { // lets setup the out message before we invoke the dataFormat // so that it can mutate it if necessary Message out = exchange.getOut(); out.copyFrom(exchange.getIn()); if (config.isFromBase64(exchange)) { stream = new Base64InputStream(stream); } Object result = unmarshalInternal(stream, exchange); out.setBody(result); } catch (Throwable e) { // remove OUT message, as an exception occurred exchange.setOut(null); throw e; } finally { IOHelper.close(stream, "input stream"); } }
String currentDir = null; try { GenericFile<ChannelSftp.LsEntry> target = (GenericFile<ChannelSftp.LsEntry>)exchange.getProperty(FileComponent.FILE_EXCHANGE_FILE); ObjectHelper.notNull(target, "Exchange should have the " + FileComponent.FILE_EXCHANGE_FILE + " set"); exchange.getIn().setHeader(RemoteFileComponent.REMOTE_FILE_INPUT_STREAM, is); } else { IOHelper.copyAndCloseInput(is, bos); IOHelper.close(bos);
if (headersInline) { mimeMessage = new MimeBodyPart(stream); camelMessage = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); contentType = mimeMessage.getHeader(CONTENT_TYPE, null); if (ho instanceof Header) { Header header = (Header) ho; camelMessage.setHeader(header.getName(), header.getValue()); contentType = exchange.getIn().getHeader(CONTENT_TYPE, String.class); if (contentType == null) { return stream; MessageHelper.copyHeaders(exchange.getIn(), camelMessage, true); ByteArrayOutputStream bos = new ByteArrayOutputStream(); IOHelper.copyAndCloseInput(stream, bos); InternetHeaders headers = new InternetHeaders(); extractHeader(CONTENT_TYPE, camelMessage, headers); camelAttachment.addHeader(header.getName(), header.getValue()); camelMessage.addAttachmentObject(getAttachmentKey(bp), camelAttachment);
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws Exception { InputStream berOut = null; if (usingIterator) { if (clazzName != null) { Class<?> clazz = exchange.getContext().getClassResolver().resolveMandatoryClass(clazzName); encodeGenericTypeObject(exchange, clazz, stream); return; } Object record = exchange.getIn().getBody(); if (record instanceof ASN1Primitive) { ASN1Primitive asn1Primitive = ObjectHelper.cast(ASN1Primitive.class, record); berOut = new ByteArrayInputStream(asn1Primitive.getEncoded()); } else if (record instanceof byte[]) { berOut = new ByteArrayInputStream(ObjectHelper.cast(byte[].class, record)); } } else { byte[] byteInput = exchange.getContext().getTypeConverter().mandatoryConvertTo(byte[].class, exchange, graph); berOut = new ByteArrayInputStream(byteInput); } try { IOHelper.copy(berOut, stream); } finally { IOHelper.close(berOut, stream); } }
InputStream is = null; ByteArrayOutputStream baos = null; Object obj = exchange.getIn().getMandatoryBody(); PutObjectRequest putObjectRequest = null; is = new FileInputStream(filePayload); } else { is = exchange.getIn().getMandatoryBody(InputStream.class); baos = determineLengthInputStream(is); objectMetadata.setContentLength(baos.size()); String cannedAcl = exchange.getIn().getHeader(S3Constants.CANNED_ACL, String.class); if (cannedAcl != null) { CannedAccessControlList objectAcl = CannedAccessControlList.valueOf(cannedAcl); if (ObjectHelper.isNotEmpty(getConfiguration().getAwsKMSKeyId())) { keyManagementParams = new SSEAwsKeyManagementParams(getConfiguration().getAwsKMSKeyId()); } else { IOHelper.close(putObjectRequest.getInputStream()); IOHelper.close(is); FileUtil.deleteFile(filePayload);
void doProcess(Exchange exchange) throws Exception { Object body = exchange.getIn().getBody(); Object key = exchange.getIn().getHeader(HdfsHeader.KEY.name()); if (exchange.getIn().getHeader(Exchange.FILE_NAME) != null) { if (ostream != null) { IOHelper.close(ostream, "output stream", log); IOHelper.close(ostream, "output stream", log); ostream.append(key, body, exchange.getContext().getTypeConverter());
String partClassFromHeader = exchange.getIn().getHeader(JaxbConstants.JAXB_PART_CLASS, String.class); String partNamespaceFromHeader = exchange.getIn().getHeader(JaxbConstants.JAXB_PART_NAMESPACE, String.class); if ((partialClass != null || partClassFromHeader != null) && (partNamespaceOnDataFormat != null || partNamespaceFromHeader != null)) { if (partClassFromHeader != null) { try { partialClass = camelContext.getClassResolver().resolveMandatoryClass(partClassFromHeader, Object.class); } catch (ClassNotFoundException e) { throw new JAXBException(e); XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, exchange, stream); if (needFiltering(exchange)) { writer = new FilteringXmlStreamWriter(writer, charset); Object toMarshall = objectFactoryMethod.invoke(instance, element); if (asXmlStreamWriter(exchange)) { XMLStreamWriter writer = typeConverter.convertTo(XMLStreamWriter.class, exchange, stream); if (needFiltering(exchange)) { writer = new FilteringXmlStreamWriter(writer, charset); LOG.debug("Attempt to marshalling non JAXBElement with type {} as InputStream", ObjectHelper.classCanonicalName(graph)); InputStream is = exchange.getContext().getTypeConverter().mandatoryConvertTo(InputStream.class, exchange, graph); IOHelper.copyAndCloseInput(is, stream); } else { throw new InvalidPayloadException(exchange, JAXBElement.class);
@Override public void marshal(Exchange exchange, Object graph, OutputStream stream) throws NoTypeConversionAvailableException, MessagingException, IOException { if (multipartWithoutAttachment || headersInline || exchange.getIn().hasAttachments()) { ContentType contentType = getContentType(exchange); exchange.getOut().removeHeader(Exchange.CONTENT_TYPE); byte[] bodyContent = ExchangeHelper.convertToMandatoryType(exchange, byte[].class, graph); Session session = Session.getInstance(System.getProperties()); writeBodyPart(bodyContent, part, contentType); mp.addBodyPart(part); for (Map.Entry<String, Attachment> entry : exchange.getIn().getAttachmentObjects().entrySet()) { String attachmentFilename = entry.getKey(); Attachment attachment = entry.getValue(); IOHelper.copyAndCloseInput(is, stream);
String username = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_USERNAME, String.class); String password = exchange.getIn().getHeader(ShiroSecurityConstants.SHIRO_SECURITY_PASSWORD, String.class); if (username != null && password != null) { ShiroSecurityToken token = new ShiroSecurityToken(username, password); ByteSource bytes = ShiroSecurityHelper.encrypt(token, policy.getPassPhrase(), policy.getCipherService()); String base64 = bytes.toBase64(); exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, base64); } else { exchange.getIn().setHeader(ShiroSecurityConstants.SHIRO_SECURITY_TOKEN, token); encryptedToken = (ByteSource) token; } else { throw new CamelExchangeException("Shiro security header " + ShiroSecurityConstants.SHIRO_SECURITY_TOKEN + " is unsupported type: " + ObjectHelper.classCanonicalName(token), exchange); securityToken = (ShiroSecurityToken)objectInputStream.readObject(); } finally { IOHelper.close(objectInputStream, byteArrayInputStream);
@Override public boolean storeFile(String name, Exchange exchange, long size) throws GenericFileOperationFailedException { ObjectHelper.notNull(session, "session"); ScpConfiguration cfg = endpoint.getConfiguration(); if (exchange.getIn().getBody() == null) { is = exchange.getIn().getMandatoryBody(InputStream.class); } finally { IOHelper.close(is);
protected void doWriteDirectResponse(Message message, HttpServletResponse response, Exchange exchange) throws IOException { String contentType = message.getHeader(Exchange.CONTENT_TYPE, String.class); if (contentType != null && HttpConstants.CONTENT_TYPE_JAVA_SERIALIZED_OBJECT.equals(contentType)) { if (allowJavaSerializedObject || isTransferException()) { try { Object object = message.getMandatoryBody(Serializable.class); HttpHelper.writeObjectToServletResponse(response, object); is = message.getBody(InputStream.class); } else { is = exchange.getContext().getTypeConverter().tryConvertTo(InputStream.class, message.getBody()); IOHelper.close(is, os); if (data != null) { String charset = IOHelper.getCharsetName(exchange, true); final int dataByteLength = data.getBytes(charset).length; response.setCharacterEncoding(charset);