public Object getHeader(String name) { Object answer = null; // we will exclude using JMS-prefixed headers here to avoid strangeness with some JMS providers // e.g. ActiveMQ returns the String not the Destination type for "JMSReplyTo"! // only look in jms message directly if we have not populated headers if (jmsMessage != null && !hasPopulatedHeaders() && !name.startsWith("JMS")) { try { // use binding to do the lookup as it has to consider using encoded keys answer = getBinding().getObjectProperty(jmsMessage, name); } catch (JMSException e) { throw new RuntimeExchangeException("Unable to retrieve header from JMS Message: " + name, getExchange(), e); } } // only look if we have populated headers otherwise there are no headers at all // if we do lookup a header starting with JMS then force a lookup if (answer == null && (hasPopulatedHeaders() || name.startsWith("JMS"))) { answer = super.getHeader(name); } return answer; }
void notify(T event) { logger.debug("Consuming CDI event [{}] with {}", event, this); Exchange exchange = getEndpoint().createExchange(); // TODO: would that be possible to propagate the event metadata? exchange.getIn().setBody(event); // Avoid infinite loop of exchange events if (event instanceof AbstractExchangeEvent) { exchange.setProperty(Exchange.NOTIFY_EVENT, Boolean.TRUE); } try { getProcessor().process(exchange); } catch (Exception cause) { throw new RuntimeExchangeException("Error while processing CDI event", exchange, cause); } finally { if (event instanceof AbstractExchangeEvent) { exchange.setProperty(Exchange.NOTIFY_EVENT, Boolean.FALSE); } } }
void notify(T event) { logger.debug("Consuming CDI event [{}] with {}", event, this); Exchange exchange = getEndpoint().createExchange(); // TODO: propagate the event metadata exchange.getIn().setBody(event); // Avoid infinite loop of exchange events if (event instanceof AbstractExchangeEvent) exchange.setProperty(Exchange.NOTIFY_EVENT, Boolean.TRUE); try { getProcessor().process(exchange); } catch (Exception cause) { throw new RuntimeExchangeException("Error while processing CDI event", exchange, cause); } finally { if (event instanceof AbstractExchangeEvent) exchange.setProperty(Exchange.NOTIFY_EVENT, Boolean.FALSE); } }
@Override public void onExchangeDone(Route route, Exchange exchange) { super.onExchangeDone(route, exchange); LOG.info("Exchange Done for route " + route.getId() + " exchange: " + exchange.getExchangeId() + " in: " + exchange.getIn().getBody(String.class)); try { stopRoute(route); } catch (Exception e) { throw new RuntimeExchangeException(e.getMessage(), exchange, e); } }
public Exchange receive() { // must be started if (!isRunAllowed() || !isStarted()) { throw new RejectedExecutionException(this + " is not started, but in state: " + getStatus().name()); } Exchange exchange = getEndpoint().createExchange(); try { processor.process(exchange); } catch (Exception e) { throw new RuntimeExchangeException("Error while processing exchange", exchange, e); } return exchange; }
/** * Creates a payload object with the information from the given exchange. * * @param exchange the exchange, must <b>not</b> be <tt>null</tt> * @param includeProperties whether or not to include exchange properties * @return the holder object with information copied form the exchange */ public static DefaultExchangeHolder marshal(Exchange exchange, boolean includeProperties) { ObjectHelper.notNull(exchange, "exchange"); // we do not support files Object body = exchange.getIn().getBody(); if (body instanceof WrappedFile || body instanceof File) { throw new RuntimeExchangeException("Message body of type " + body.getClass().getCanonicalName() + " is not supported by this marshaller.", exchange); } DefaultExchangeHolder payload = new DefaultExchangeHolder(); payload.exchangeId = exchange.getExchangeId(); payload.inBody = checkSerializableBody("in body", exchange, exchange.getIn().getBody()); payload.safeSetInHeaders(exchange, false); if (exchange.hasOut()) { payload.outBody = checkSerializableBody("out body", exchange, exchange.getOut().getBody()); payload.outFaultFlag = exchange.getOut().isFault(); payload.safeSetOutHeaders(exchange, false); } else { payload.inFaultFlag = exchange.getIn().isFault(); } if (includeProperties) { payload.safeSetProperties(exchange, false); } payload.exception = exchange.getException(); return payload; }
/** * Creates a payload object with the information from the given exchange. * * @param exchange the exchange, must <b>not</b> be <tt>null</tt> * @param includeProperties whether or not to include exchange properties * @param allowSerializedHeaders whether or not to include serialized headers * @return the holder object with information copied form the exchange */ public static DefaultExchangeHolder marshal(Exchange exchange, boolean includeProperties, boolean allowSerializedHeaders) { ObjectHelper.notNull(exchange, "exchange"); // we do not support files Object body = exchange.getIn().getBody(); if (body instanceof WrappedFile || body instanceof File) { throw new RuntimeExchangeException("Message body of type " + body.getClass().getCanonicalName() + " is not supported by this marshaller.", exchange); } DefaultExchangeHolder payload = new DefaultExchangeHolder(); payload.exchangeId = exchange.getExchangeId(); payload.inBody = checkSerializableBody("in body", exchange, exchange.getIn().getBody()); payload.safeSetInHeaders(exchange, allowSerializedHeaders); if (exchange.hasOut()) { payload.outBody = checkSerializableBody("out body", exchange, exchange.getOut().getBody()); payload.outFaultFlag = exchange.getOut().isFault(); payload.safeSetOutHeaders(exchange, allowSerializedHeaders); } else { payload.inFaultFlag = exchange.getIn().isFault(); } if (includeProperties) { payload.safeSetProperties(exchange, allowSerializedHeaders); } payload.exception = exchange.getException(); return payload; }
public void testFileNotSupported() throws Exception { Exchange exchange = new DefaultExchange(context); exchange.getIn().setBody(new File("src/test/resources/log4j.properties")); try { DefaultExchangeHolder.marshal(exchange); fail("Should have thrown exception"); } catch (RuntimeExchangeException e) { // expected } }
public void testBeanParameterInvalidValueA() throws Exception { getMockEndpoint("mock:result").expectedMessageCount(0); try { template.sendBody("direct:a", "World"); fail("Should have thrown exception"); } catch (CamelExecutionException e) { RuntimeExchangeException cause = assertIsInstanceOf(RuntimeExchangeException.class, e.getCause()); assertTrue(cause.getMessage().contains("echo(java.lang.String,int)")); assertTrue(cause.getMessage().contains("[World, null]")); assertIsInstanceOf(IllegalArgumentException.class, cause.getCause()); } assertMockEndpointsSatisfied(); }
/** * Creates the HttpMethod to use to call the remote server, often either its GET or POST. * * @param exchange the exchange * @return the created method * @throws URISyntaxException */ public static HttpMethods createMethod(Exchange exchange, HttpCommonEndpoint endpoint, boolean hasPayload) throws URISyntaxException { // is a query string provided in the endpoint URI or in a header (header overrules endpoint) String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); // We need also check the HTTP_URI header query part String uriString = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class); // resolve placeholders in uriString try { uriString = exchange.getContext().resolvePropertyPlaceholders(uriString); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uriString, exchange, e); } if (uriString != null) { // in case the URI string contains unsafe characters uriString = UnsafeUriCharactersEncoder.encodeHttpURI(uriString); URI uri = new URI(uriString); queryString = uri.getQuery(); } if (queryString == null) { queryString = endpoint.getHttpUri().getRawQuery(); } // compute what method to use either GET or POST HttpMethods answer; HttpMethods m = exchange.getIn().getHeader(Exchange.HTTP_METHOD, HttpMethods.class); if (m != null) { // always use what end-user provides in a header answer = m; } else if (queryString != null) { // if a query string is provided then use GET answer = HttpMethods.GET; } else { // fallback to POST if we have payload, otherwise GET answer = hasPayload ? HttpMethods.POST : HttpMethods.GET; } return answer; }
/** * Creates the HttpMethod to use to call the remote server, often either its GET or POST. * * @param exchange the exchange * @return the created method * @throws URISyntaxException */ public static HttpMethods createMethod(Exchange exchange, HttpEndpoint endpoint, boolean hasPayload) throws URISyntaxException { // is a query string provided in the endpoint URI or in a header (header // overrules endpoint) String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); // We need also check the HTTP_URI header query part String uriString = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class); // resolve placeholders in uriString try { uriString = exchange.getContext().resolvePropertyPlaceholders(uriString); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uriString, exchange, e); } if (uriString != null) { // in case the URI string contains unsafe characters uriString = UnsafeUriCharactersEncoder.encodeHttpURI(uriString); URI uri = new URI(uriString); queryString = uri.getQuery(); } if (queryString == null) { queryString = endpoint.getHttpUri().getRawQuery(); } // compute what method to use either GET or POST HttpMethods answer; HttpMethods m = exchange.getIn().getHeader(Exchange.HTTP_METHOD, HttpMethods.class); if (m != null) { // always use what end-user provides in a header answer = m; } else if (queryString != null) { // if a query string is provided then use GET answer = HttpMethods.GET; } else { // fallback to POST if we have payload, otherwise GET answer = hasPayload ? HttpMethods.POST : HttpMethods.GET; } return answer; }
@Override protected String createMessageId() { if (jmsMessage == null) { LOG.trace("No javax.jms.Message set so generating a new message id"); return super.createMessageId(); } try { String id = getDestinationAsString(jmsMessage.getJMSDestination()) + jmsMessage.getJMSMessageID(); return getSanitizedString(id); } catch (JMSException e) { throw new RuntimeExchangeException("Unable to retrieve JMSMessageID from JMS Message", getExchange(), e); } }
/** * Creates the URL to invoke. * * @param exchange the exchange * @param endpoint the endpoint * @return the URL to invoke */ public static String createURL(Exchange exchange, UndertowEndpoint endpoint) { String uri = uri = endpoint.getHttpURI().toASCIIString(); // resolve placeholders in uri try { uri = exchange.getContext().resolvePropertyPlaceholders(uri); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uri, exchange, e); } // append HTTP_PATH to HTTP_URI if it is provided in the header String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); // NOW the HTTP_PATH is just related path, we don't need to trim it if (path != null) { if (path.startsWith("/")) { path = path.substring(1); } if (path.length() > 0) { // make sure that there is exactly one "/" between HTTP_URI and // HTTP_PATH if (!uri.endsWith("/")) { uri = uri + "/"; } uri = uri.concat(path); } } // ensure uri is encoded to be valid uri = UnsafeUriCharactersEncoder.encodeHttpURI(uri); return uri; }
/** * Creates the HttpMethod to use to call the remote server, often either its GET or POST. * * @param exchange the exchange * @return the created method * @throws URISyntaxException */ public static HttpString createMethod(Exchange exchange, UndertowEndpoint endpoint, boolean hasPayload) throws URISyntaxException { // is a query string provided in the endpoint URI or in a header (header // overrules endpoint) String queryString = exchange.getIn().getHeader(Exchange.HTTP_QUERY, String.class); // We need also check the HTTP_URI header query part String uriString = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class); // resolve placeholders in uriString try { uriString = exchange.getContext().resolvePropertyPlaceholders(uriString); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uriString, exchange, e); } if (uriString != null) { URI uri = new URI(uriString); queryString = uri.getQuery(); } if (queryString == null) { queryString = endpoint.getHttpURI().getRawQuery(); } // compute what method to use either GET or POST HttpString answer; String m = exchange.getIn().getHeader(Exchange.HTTP_METHOD, String.class); if (m != null) { // always use what end-user provides in a header answer = new HttpString(m); } else if (queryString != null) { // if a query string is provided then use GET answer = Methods.GET; } else { // fallback to POST if we have payload, otherwise GET answer = hasPayload ? Methods.POST : Methods.GET; } return answer; }
private Folder getFolderOnPath(Exchange exchange, String path) throws Exception { try { return (Folder) getSessionFacade().getObjectByPath(path); } catch (CmisObjectNotFoundException e) { throw new RuntimeExchangeException("Path not found " + path, exchange, e); } }
@Test public void failCreatingFolderAtNonExistingPath() throws Exception { String existingFolderStructure = "/No/Path/Here"; Exchange exchange = createExchangeWithInBody(null); exchange.getIn().getHeaders().put(PropertyIds.NAME, "folder1"); exchange.getIn().getHeaders().put(PropertyIds.OBJECT_TYPE_ID, "cmis:folder"); exchange.getIn().getHeaders().put(CamelCMISConstants.CMIS_FOLDER_PATH, existingFolderStructure); template.send(exchange); assertTrue(exchange.getException() instanceof RuntimeExchangeException); }
private String getServiceName(Exchange exchange) { String serviceName = exchange.getIn().getHeader(OfbizConstants.CAMEL_OFBIZ_SERVICE, this.remaining, String.class); if (serviceName == null) { throw new RuntimeExchangeException("Missing Ofbiz service name", exchange); } return serviceName; }
@Metered public void attempt(Exchange exchange) { if (Math.random() < 0.5) { throw new RuntimeExchangeException("Random failure", exchange); } }
/** * Creates the URL to invoke. * * @param exchange the exchange * @param endpoint the endpoint * @return the URL to invoke */ public static String createURL(Exchange exchange, NettyHttpEndpoint endpoint) throws URISyntaxException { String uri = endpoint.getEndpointUri(); // resolve placeholders in uri try { uri = exchange.getContext().resolvePropertyPlaceholders(uri); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uri, exchange, e); } // append HTTP_PATH to HTTP_URI if it is provided in the header String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); // NOW the HTTP_PATH is just related path, we don't need to trim it if (path != null) { if (path.startsWith("/")) { path = path.substring(1); } if (path.length() > 0) { // inject the dynamic path before the query params, if there are any int idx = uri.indexOf("?"); // if there are no query params if (idx == -1) { // make sure that there is exactly one "/" between HTTP_URI and HTTP_PATH uri = uri.endsWith("/") ? uri : uri + "/"; uri = uri.concat(path); } else { // there are query params, so inject the relative path in the right place String base = uri.substring(0, idx); base = base.endsWith("/") ? base : base + "/"; base = base.concat(path); uri = base.concat(uri.substring(idx)); } } } // ensure uri is encoded to be valid uri = UnsafeUriCharactersEncoder.encodeHttpURI(uri); return uri; }
/** * Creates the URL to invoke. * * @param exchange the exchange * @param endpoint the endpoint * @return the URL to invoke */ public static String createURL(Exchange exchange, HttpCommonEndpoint endpoint) { String uri = null; if (!(endpoint.isBridgeEndpoint())) { uri = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class); } if (uri == null) { uri = endpoint.getHttpUri().toASCIIString(); } // resolve placeholders in uri try { uri = exchange.getContext().resolvePropertyPlaceholders(uri); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uri, exchange, e); } // append HTTP_PATH to HTTP_URI if it is provided in the header String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); // NOW the HTTP_PATH is just related path, we don't need to trim it if (path != null) { if (path.length() > 1 && path.startsWith("/")) { path = path.substring(1); } if (path.length() > 0) { // inject the dynamic path before the query params, if there are any int idx = uri.indexOf("?"); // if there are no query params if (idx == -1) { // make sure that there is exactly one "/" between HTTP_URI and HTTP_PATH uri = uri.endsWith("/") || path.startsWith("/") ? uri : uri + "/"; uri = uri.concat(path); } else { // there are query params, so inject the relative path in the right place String base = uri.substring(0, idx); base = base.endsWith("/") ? base : base + "/"; base = base.concat(path); uri = base.concat(uri.substring(idx)); } } } // ensure uri is encoded to be valid uri = UnsafeUriCharactersEncoder.encodeHttpURI(uri); return uri; }
protected boolean processInOut(final Exchange exchange, final AsyncCallback callback) { final org.apache.camel.Message in = exchange.getIn(); String destinationName = in.getHeader(JmsConstants.JMS_DESTINATION_NAME, String.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION_NAME); if (destinationName == null) { destinationName = endpoint.getDestinationName(); } Destination destination = in.getHeader(JmsConstants.JMS_DESTINATION, Destination.class); // remove the header so it wont be propagated in.removeHeader(JmsConstants.JMS_DESTINATION); if (destination == null) { destination = endpoint.getDestination(); } if (destination != null) { // prefer to use destination over destination name destinationName = null; } initReplyManager(); // the request timeout can be overruled by a header otherwise the endpoint configured value is used final long timeout = exchange.getIn().getHeader(JmsConstants.JMS_REQUEST_TIMEOUT, endpoint.getRequestTimeout(), long.class); // when using message id as correlation id, we need at first to use a provisional correlation id // which we then update to the real JMSMessageID when the message has been sent // this is done with the help of the MessageSentCallback final boolean msgIdAsCorrId = endpoint.getConfiguration().isUseMessageIDAsCorrelationID(); final String provisionalCorrelationId = msgIdAsCorrId ? getUuidGenerator().generateUuid() : null; MessageSentCallback messageSentCallback = null; if (msgIdAsCorrId) { messageSentCallback = new UseMessageIdAsCorrelationIdMessageSentCallback(replyManager, provisionalCorrelationId, timeout); } final String originalCorrelationId = in.getHeader("JMSCorrelationID", String.class); boolean generateFreshCorrId = (ObjectHelper.isEmpty(originalCorrelationId) && !msgIdAsCorrId) || (originalCorrelationId != null && originalCorrelationId.startsWith(GENERATED_CORRELATION_ID_PREFIX)); if (generateFreshCorrId) { // we append the 'Camel-' prefix to know it was generated by us in.setHeader("JMSCorrelationID", GENERATED_CORRELATION_ID_PREFIX + getUuidGenerator().generateUuid()); } MessageCreator messageCreator = new MessageCreator() { public Message createMessage(Session session) throws JMSException { Message answer = endpoint.getBinding().makeJmsMessage(exchange, in, session, null); Destination replyTo = null; String replyToOverride = endpoint.getConfiguration().getReplyToOverride(); if (replyToOverride != null) { replyTo = resolveOrCreateDestination(replyToOverride, session); } else { // get the reply to destination to be used from the reply manager replyTo = replyManager.getReplyTo(); } if (replyTo == null) { throw new RuntimeExchangeException("Failed to resolve replyTo destination", exchange); } JmsMessageHelper.setJMSReplyTo(answer, replyTo); replyManager.setReplyToSelectorHeader(in, answer); String correlationId = determineCorrelationId(answer, provisionalCorrelationId); replyManager.registerReply(replyManager, exchange, callback, originalCorrelationId, correlationId, timeout); if (LOG.isDebugEnabled()) { LOG.debug("Using JMSCorrelationID: {}, JMSReplyTo destination: {}, with request timeout: {} ms.", new Object[]{correlationId, replyTo, timeout}); } LOG.trace("Created javax.jms.Message: {}", answer); return answer; } }; doSend(true, destinationName, destination, messageCreator, messageSentCallback); // continue routing asynchronously (reply will be processed async when its received) return false; }
@Override public Iterator<?> createPopulateIterator(final String query, final String preparedQuery, final int expectedParams, final Exchange exchange, final Object value) throws SQLException { Map<?, ?> map = null; if (exchange.getIn().hasHeaders()) { if (exchange.getIn().getHeader(JdbcConstants.JDBC_PARAMETERS) != null) { // header JDBC_PARAMETERS takes precedence over regular headers map = exchange.getIn().getHeader(JdbcConstants.JDBC_PARAMETERS, Map.class); } else { map = exchange.getIn().getHeaders(); } } final Map<?, ?> headerMap = map; if (hasNamedParameters(query)) { // create an iterator that returns the value in the named order try { return new Iterator<Object>() { private NamedQueryParser parser = new NamedQueryParser(query); private Object next; private boolean done; private boolean preFetched; @Override public boolean hasNext() { if (!done && !preFetched) { next(); preFetched = true; } return !done; } @Override public Object next() { if (!preFetched) { String key = parser.next(); if (key == null) { done = true; return null; } // the key is expected to exist, if not report so end user can see this boolean contains = headerMap != null && headerMap.containsKey(key); if (!contains) { throw new RuntimeExchangeException("Cannot find key [" + key + "] in message body or headers to use when setting named parameter in query [" + query + "]", exchange); } next = headerMap.get(key); } preFetched = false; return next; } @Override public void remove() { // noop } }; } catch (Exception e) { throw new SQLException("Error iterating parameters for the query: " + query, e); } } else { // just use a regular iterator return exchange.getContext().getTypeConverter().convertTo(Iterator.class, headerMap != null ? headerMap.values() : null); } }
private static String doCreateURL(Exchange exchange, AhcEndpoint endpoint) { String uri = null; if (!(endpoint.isBridgeEndpoint())) { uri = exchange.getIn().getHeader(Exchange.HTTP_URI, String.class); } if (uri == null) { uri = endpoint.getHttpUri().toASCIIString(); } // resolve placeholders in uri try { uri = exchange.getContext().resolvePropertyPlaceholders(uri); } catch (Exception e) { throw new RuntimeExchangeException("Cannot resolve property placeholders with uri: " + uri, exchange, e); } // append HTTP_PATH to HTTP_URI if it is provided in the header String path = exchange.getIn().getHeader(Exchange.HTTP_PATH, String.class); if (path != null) { if (path.startsWith("/")) { URI baseURI; String baseURIString = exchange.getIn().getHeader(Exchange.HTTP_BASE_URI, String.class); try { if (baseURIString == null) { if (exchange.getFromEndpoint() != null) { baseURIString = exchange.getFromEndpoint().getEndpointUri(); } else { // will set a default one for it baseURIString = "/"; } } baseURI = new URI(baseURIString); String basePath = baseURI.getPath(); if (path.startsWith(basePath)) { path = path.substring(basePath.length()); if (path.startsWith("/")) { path = path.substring(1); } } else { throw new RuntimeExchangeException("Cannot analyze the Exchange.HTTP_PATH header, due to: cannot find the right HTTP_BASE_URI", exchange); } } catch (Throwable t) { throw new RuntimeExchangeException("Cannot analyze the Exchange.HTTP_PATH header, due to: " + t.getMessage(), exchange, t); } } if (path.length() > 0) { // make sure that there is exactly one "/" between HTTP_URI and // HTTP_PATH if (!uri.endsWith("/")) { uri = uri + "/"; } uri = uri.concat(path); } } // ensure uri is encoded to be valid uri = UnsafeUriCharactersEncoder.encodeHttpURI(uri); return uri; }
@Metered public void attempt(Exchange exchange) { if (Math.random() < 0.5) throw new RuntimeExchangeException("Random failure", exchange); }