/** * Program entry point */ public static void main(String[] args) throws Exception { CamelContext context = new DefaultCamelContext(); context.addRoutes(new RouteBuilder() { @Override public void configure() throws Exception { from("stream:in").to("direct:greetings"); from("direct:greetings").to("stream:out"); } }); context.start(); context.getRoutes().forEach(r -> LOGGER.info(r.toString())); context.stop(); } }
public <T> T evaluate(Exchange exchange, Class<T> tClass) { try { Expression expression = parseExpression(); EvaluationContext evaluationContext = createEvaluationContext(exchange); Object value = expression.getValue(evaluationContext); // Let Camel handle the type conversion return exchange.getContext().getTypeConverter().convertTo(tClass, value); } catch (Exception e) { throw new ExpressionEvaluationException(this, exchange, e); } }
/** * Publish to a kafka topic * based on the connection information * @param arr */ public void publish(INDArray arr) { if (producerTemplate == null) producerTemplate = camelContext.createProducerTemplate(); producerTemplate.sendBody("direct:start", arr); }
@Override public void start() throws Exception { vertx.eventBus().consumer("announce", message -> { System.out.println("ANNOUNCE >> " + message.body()); }); vertx.eventBus().consumer("errors", message -> { System.out.println("ERROR >> " + message.body()); }); SimpleRegistry registry = new SimpleRegistry(); registry.put("filterService", new ReleasePostFilter()); CamelContext camelContext = new DefaultCamelContext(registry); camelContext.addRoutes(createMyRoutes()); camelContext.start(); CamelBridge.create(vertx, new CamelBridgeOptions(camelContext) .addInboundMapping(fromCamel("seda:announce").toVertx("announce")) .addInboundMapping(fromCamel("seda:errors").toVertx("errors"))) .start(); }
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 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 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();
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); }; }
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 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); }
@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); } }
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 {
@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);
/** * 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(); }
@Test(timeout=60000) public void checkDefinedTimeout() throws Exception { System.getProperties().setProperty(CamelRpcClientPreProcessor.CAMEL_JMS_REQUEST_TIMEOUT_PROPERTY, "12345"); CamelContext context = getContext(); CamelRpcRequest<EchoRequest,EchoResponse> wrapper = new CamelRpcRequest<>(new EchoRpcModule(), new EchoRequest()); CamelRpcClientPreProcessor camelRpcClientPreProcessor = new CamelRpcClientPreProcessor(); DefaultExchange defaultExchange = new DefaultExchange(context); defaultExchange.getIn().setBody(wrapper); camelRpcClientPreProcessor.process(defaultExchange); context.stop(); assertEquals(12345L, defaultExchange.getIn().getHeader(CamelRpcConstants.CAMEL_JMS_REQUEST_TIMEOUT_HEADER)); }
private void sendData(CamelContext context, List<String> messages) { ProducerTemplate template = context.createProducerTemplate(); for (String message : messages) { Exchange exchange = context.getEndpoint(directEndpoint.toString()).createExchange(); Message msg = exchange.getIn(); msg.setBody(message); template.send(directEndpoint.toString(), exchange); } }
private void start() throws Exception { CamelContext camel = new DefaultCamelContext(); // add our custom component camel.addComponent("erp", new ERPComponent()); // add the route camel.addRoutes(new ERPRoute()); // and start Camel camel.start(); }
public static Map<?, ?> getItem(CamelContext camelctx) { HashMap<String, AttributeValue> key = new HashMap<>(); key.put("Id", new AttributeValue().withN("103")); Exchange exchange = new ExchangeBuilder(camelctx) .withHeader(DdbConstants.OPERATION, DdbOperations.GetItem) .withHeader(DdbConstants.KEY, key).build(); ProducerTemplate producer = camelctx.createProducerTemplate(); producer.send("direct:start", exchange); Assert.assertNull(exchange.getException()); return exchange.getIn().getHeader(DdbConstants.ATTRIBUTES, Map.class); }