@Converter public static StAXSource toStAXSource(ByteBuf buffer, Exchange exchange) { InputStream is = toInputStream(buffer, exchange); return exchange.getContext().getTypeConverter().convertTo(StAXSource.class, exchange, is); }
private void doRun(final Exchange exchange, final AsyncCallback callback, IgniteCompute compute) throws Exception { Object job = exchange.getIn().getBody(); if (Collection.class.isAssignableFrom(job.getClass())) { Collection<?> col = (Collection<?>) job; TypeConverter tc = exchange.getContext().getTypeConverter(); Collection<IgniteRunnable> runnables = new ArrayList<>(col.size()); for (Object o : col) { runnables.add(tc.mandatoryConvertTo(IgniteRunnable.class, o)); } compute.run(runnables); } else if (IgniteRunnable.class.isAssignableFrom(job.getClass())) { compute.run((IgniteRunnable) job); } else { throw new RuntimeCamelException(String.format( "Ignite Compute endpoint with RUN executionType is only " + "supported for IgniteRunnable payloads, or collections of them. The payload type was: %s.", job.getClass().getName())); } }
private Function<Exchange, Object> createDoCount() { return exchange -> { BasicDBObject query = exchange.getContext().getTypeConverter().tryConvertTo(BasicDBObject.class, exchange, exchange.getIn().getBody()); if (query == null) { query = new BasicDBObject(); } return (Long) calculateCollection(exchange).count(query); }; }
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 protected void onExchange(Exchange exchange) throws Exception { StringWriter buffer = new StringWriter(); @SuppressWarnings("unchecked") Map<String, Object> variableMap = exchange.getIn().getHeader(StringTemplateConstants.STRINGTEMPLATE_VARIABLE_MAP, Map.class); if (variableMap == null) { variableMap = ExchangeHelper.createVariableMap(exchange); } // getResourceAsInputStream also considers the content cache String text = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, getResourceAsInputStream()); ST template = new ST(text, delimiterStart, delimiterStop); for (Map.Entry<String, Object> entry : variableMap.entrySet()) { template.add(entry.getKey(), entry.getValue()); } log.debug("StringTemplate is writing using attributes: {}", variableMap); template.write(new NoIndentWriter(buffer)); // now lets output the results to the exchange Message out = exchange.getOut(); out.setBody(buffer.toString()); out.setHeaders(exchange.getIn().getHeaders()); out.setHeader(StringTemplateConstants.STRINGTEMPLATE_RESOURCE_URI, getResourceUri()); out.setAttachments(exchange.getIn().getAttachments()); } }
@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); }
@Override public void process(Exchange exchange) throws Exception { String q = query; String location = exchange.getIn().getHeader(WeatherConstants.WEATHER_LOCATION, String.class); if (location != null) { q = getEndpoint().getConfiguration().getQuery(location); throw new IllegalStateException("Got the invalid http status value '" + method.getStatusLine() + "' as the result of the query '" + query + "'"); String weather = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo(String.class, method.getResponseBodyAsStream()); log.debug("Got back the Weather information {}", weather); if (ObjectHelper.isEmpty(weather)) { throw new IllegalStateException("Got the unexpected value '" + weather + "' as the result of the query '" + q + "'"); exchange.getIn().setHeader(header, weather); } else { exchange.getIn().setBody(weather); exchange.getIn().setHeader(WeatherConstants.WEATHER_QUERY, q);
protected static boolean hasParameter(String nextParam, Exchange exchange, Object body) { Map<?, ?> bodyMap = safeMap(exchange.getContext().getTypeConverter().tryConvertTo(Map.class, body)); Map<?, ?> headersMap = safeMap(exchange.getIn().getHeaders()); if ((nextParam.startsWith("$simple{") || nextParam.startsWith("${")) && nextParam.endsWith("}")) { return true; } else if (bodyMap.containsKey(nextParam)) { return true; } else if (headersMap.containsKey(nextParam)) { return true; } return false; }
@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); } }
@SuppressWarnings("unchecked") public ExecCommand readInput(Exchange exchange, ExecEndpoint endpoint) { ObjectHelper.notNull(exchange, "exchange"); ObjectHelper.notNull(endpoint, "endpoint"); // do not convert args as we do that manually later Object args = exchange.getIn().removeHeader(EXEC_COMMAND_ARGS); String cmd = getAndRemoveHeader(exchange.getIn(), EXEC_COMMAND_EXECUTABLE, endpoint.getExecutable(), String.class); String dir = getAndRemoveHeader(exchange.getIn(), EXEC_COMMAND_WORKING_DIR, endpoint.getWorkingDir(), String.class); long timeout = getAndRemoveHeader(exchange.getIn(), EXEC_COMMAND_TIMEOUT, endpoint.getTimeout(), Long.class); String outFilePath = getAndRemoveHeader(exchange.getIn(), EXEC_COMMAND_OUT_FILE, endpoint.getOutFile(), String.class); boolean useStderrOnEmptyStdout = getAndRemoveHeader(exchange.getIn(), EXEC_USE_STDERR_ON_EMPTY_STDOUT, endpoint.isUseStderrOnEmptyStdout(), Boolean.class); InputStream input = exchange.getIn().getBody(InputStream.class); // If the args is a list of strings already.. List<String> argsList = null; if (isListOfStrings(args)) { argsList = (List<String>) args; } if (argsList == null) { // no we could not do that, then parse it as a string to a list String s = endpoint.getArgs(); if (args != null) { // use args from header instead from endpoint s = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, args); } LOG.debug("Parsing argument String to a List: {}", s); argsList = splitToWhiteSpaceSeparatedTokens(s); } File outFile = outFilePath == null ? null : new File(outFilePath); return new ExecCommand(cmd, argsList, dir, timeout, input, outFile, useStderrOnEmptyStdout); }
exchange.setProperty(Exchange.SKIP_GZIP_ENCODING, Boolean.TRUE); String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); if (queryString != null) { skipRequestHeaders = URISupport.parseQuery(queryString, false, true); exchange.getIn().getHeaders().remove("host"); Message in = exchange.getIn(); String httpProtocolVersion = in.getHeader(Exchange.HTTP_PROTOCOL_VERSION, String.class); if (httpProtocolVersion != null) { final Iterator<?> it = ObjectHelper.createIterator(headerValue, null, true); String value = exchange.getContext().getTypeConverter().convertTo(String.class, it.next());
final String exchangeUri = UndertowHelper.createURL(camelExchange, getEndpoint()); uri = UndertowHelper.createURI(camelExchange, exchangeUri, getEndpoint()); method = UndertowHelper.createMethod(camelExchange, endpoint, camelExchange.getIn().getBody() != null); } catch (final URISyntaxException e) { camelExchange.setException(e); callback.done(true); return true; cookieHeaders = cookieHandler.loadCookies(camelExchange, uri); } catch (final IOException e) { camelExchange.setException(e); callback.done(true); return true; final Message message = camelExchange.getIn(); final String host = message.getHeader(Headers.HOST_STRING, String.class); requestHeaders.put(Headers.HOST, Optional.ofNullable(host).orElseGet(() -> uri.getAuthority())); final Object body = undertowHttpBinding.toHttpRequest(request, camelExchange.getIn()); final TypeConverter tc = endpoint.getCamelContext().getTypeConverter(); final ByteBuffer bodyAsByte = tc.tryConvertTo(ByteBuffer.class, body);
private static void getParamsFromHeaders( Exchange exchange, Collection<String> args) { Map<String, Object> headers = exchange.getIn().getHeaders(); for (Map.Entry<String, Object> header : headers.entrySet()) { Object headerValue = header.getValue(); if (headerValue != null) { String headerStringValue = exchange.getContext().getTypeConverter() .convertTo(String.class, exchange, headerValue); args.add("--context_param " + header.getKey() + '=' + headerStringValue); } } }
@SuppressWarnings("unchecked") public void marshal(Exchange exchange, Object body, OutputStream outputStream) throws Exception { BindyFixedLengthFactory factory = (BindyFixedLengthFactory) getFactory(); ObjectHelper.notNull(factory, "not instantiated"); Iterator<?> it = ObjectHelper.createIterator(body); while (it.hasNext()) { Object model = it.next(); Map<String, Object> headerRow = (Map<String, Object>) exchange.getIn().getHeader(CAMEL_BINDY_FIXED_LENGTH_HEADER); if (headerRow != null) { models.add(0, headerRow); Map<String, Object> footerRow = (Map<String, Object>) exchange.getIn().getHeader(CAMEL_BINDY_FIXED_LENGTH_FOOTER); if (footerRow != null) { models.add(models.size(), footerRow); byte[] bytes = exchange.getContext().getTypeConverter().convertTo(byte[].class, exchange, result); outputStream.write(bytes);
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);
private boolean processInBody(Exchange exchange, Map<String, Object> properties) { final String inBodyProperty = endpoint.getInBody(); if (inBodyProperty != null) { Object value = exchange.getIn().getBody(); try { value = getEndpoint().getCamelContext().getTypeConverter().mandatoryConvertTo( FacebookEndpointConfiguration.class.getDeclaredField(inBodyProperty).getType(), exchange, value); } catch (Exception e) { exchange.setException(new RuntimeCamelException(String.format( "Error converting value %s to property %s: %s", value, inBodyProperty, e.getMessage()), e)); return false; } LOG.debug("Property [{}] has message body value {}", inBodyProperty, value); properties.put(inBodyProperty, value); } return true; }
if (message.getBody() instanceof HttpRequest) { return (HttpRequest) message.getBody(); TypeConverter tc = message.getExchange().getContext().getTypeConverter(); final Iterator<?> it = ObjectHelper.createIterator(value, null, true); while (it.hasNext()) { String headerValue = tc.convertTo(String.class, it.next());
/** * helper method to construct the hdfsPath from the CamelFileName String or Expression * @param exchange * @return */ private StringBuilder getHdfsPathUsingFileNameHeader(Exchange exchange) { StringBuilder actualPath = new StringBuilder(hdfsPath); String fileName = ""; Object value = exchange.getIn().getHeader(Exchange.FILE_NAME); if (value instanceof String) { fileName = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, value); } else if (value instanceof Expression) { fileName = ((Expression) value).evaluate(exchange, String.class); } return actualPath.append(fileName); }
public void index(Exchange exchange) throws Exception { LOG.debug("Indexing {}", exchange); openIndexWriter(); Map<String, Object> headers = exchange.getIn().getHeaders(); add("exchangeId", exchange.getExchangeId(), true); for (Entry<String, Object> entry : headers.entrySet()) { String field = entry.getKey(); String value = exchange.getContext().getTypeConverter().mandatoryConvertTo(String.class, entry.getValue()); add(field, value, true); } add("contents", exchange.getIn().getMandatoryBody(String.class), true); closeIndexWriter(); }