@Override public void process(Exchange exchange) throws Exception { Message in = exchange.getIn(); String filename = in.getBody(String.class); List<String> lines = Files.readAllLines(Paths.get(filename), Charset.defaultCharset()); in.setBody(lines); }
private void extractHeader(String headerMame, Message camelMessage, InternetHeaders headers) { String h = camelMessage.getHeader(headerMame, String.class); if (h != null) { headers.addHeader(headerMame, h); camelMessage.removeHeader(headerMame); } }
public void testSendingAMessageUsingMulticastReceivesItsOwnExchangeParallel() throws Exception { MockEndpoint resultEndpoint = getMockEndpoint("mock:result"); resultEndpoint.expectsNoDuplicates(body()); resultEndpoint.expectedMessageCount(4); // InOnly template.send( "direct:parallel", new Processor() { public void process(Exchange exchange) { Message in = exchange.getIn(); in.setBody("James,Guillaume,Hiram,Rob"); in.setHeader("foo", "bar"); } }); assertMockEndpointsSatisfied(); List<Exchange> list = resultEndpoint.getReceivedExchanges(); Set<Integer> numbersFound = new TreeSet<Integer>(); final String[] names = {"James", "Guillaume", "Hiram", "Rob"}; for (int i = 0; i < 4; i++) { Exchange exchange = list.get(i); Message in = exchange.getIn(); Integer splitCounter = exchange.getProperty(Exchange.SPLIT_INDEX, Integer.class); numbersFound.add(splitCounter); assertEquals(names[splitCounter], in.getBody()); assertProperty(exchange, Exchange.SPLIT_SIZE, 4); } assertEquals(4, numbersFound.size()); }
public void testMessageDump() throws Exception { JAXBContext jaxb = JAXBContext.newInstance(MessageDump.class); Unmarshaller unmarshaller = jaxb.createUnmarshaller(); CamelContext context = new DefaultCamelContext(); context.start(); message = new DefaultExchange(context).getIn(); // xml message body message.setBody("Hello World"); message.setHeader("foo", 123); String out = MessageHelper.dumpAsXml(message, true); MessageDump dump = (MessageDump) unmarshaller.unmarshal(new StringReader(out)); assertNotNull(dump); assertEquals("java.lang.String", dump.getBody().getType()); assertEquals("Hello World", dump.getBody().getValue()); assertEquals(1, dump.getHeaders().size()); assertEquals("foo", dump.getHeaders().get(0).getKey()); assertEquals("java.lang.Integer", dump.getHeaders().get(0).getType()); assertEquals("123", dump.getHeaders().get(0).getValue()); }
public void process(Exchange exchange) throws Exception { exchange.getIn().getBody(String.class); Message output = exchange.getOut(); output.setHeader("sample.name", "myValue"); output.setBody(expectedBody); }
public void process(Exchange exchange) throws Exception { if (executor == null) { executor = exchange .getContext() .getExecutorServiceManager() .newFixedThreadPool(this, "CLAIM-CHECK", 4); } String id = tag.evaluate(exchange, String.class); exchange.setProperty(ClaimCheck.CLAIMCHECK_TAG_HEADER, id); final Producer conveyor = findDestination(exchange).createProducer(); final Exchange baggage = ExchangeHelper.createCorrelatedCopy(exchange, false); LOG.info("Checking in 'baggage'"); executor.submit( new Callable<Exchange>() { public Exchange call() throws Exception { try { LOG.debug("[claimcheck] {} {}", conveyor, baggage); conveyor.process(baggage); } catch (Throwable e) { LOG.warn( "Error occurred during processing " + baggage + " checked in at " + conveyor, e); } return baggage; }; }); LOG.info("Continue normal flow without 'baggage'"); Message out = exchange.getOut(); out.setBody(value.evaluate(exchange, Object.class)); }
public void testGetMessageId() { context.setUuidGenerator(new SimpleUuidGenerator()); Exchange exchange = new DefaultExchange(context); Message in = exchange.getIn(); assertEquals("1", in.getMessageId()); }
@Override public Source respond(SoapOperation invokedOperation, SoapMessage message) { Exchange exchange = new DefaultExchange(getCamelContext(), ExchangePattern.InOut); Document messageDocument = message.getDocument(); String requestBody = envelopeWrapper.unwrap(messageDocument, getCamelContext()); exchange.getIn().setBody(requestBody); exchange.getIn().setHeader(OPERATION, invokedOperation.getOperationName()); try { getProcessor().process(exchange); if (exchange.getException() != null) { throw exchange.getException(); } Message responseMessage = exchange.getOut(Message.class); if (responseMessage != null) { String responseBody = responseMessage.getBody(String.class); return envelopeWrapper.wrapToSource(responseBody, getCamelContext()); } else { throw new IllegalArgumentException( "Could not find output message, exchange: " + exchange); } } catch (Exception ex) { throw new SoapServerException(ex); } }
/** * Generate a "help" message. * * @param exchange the incoming message */ public void process(final Exchange exchange) throws IOException { final Message in = exchange.getIn(); final CamelContext context = exchange.getContext(); final String fedora; final String endpoint; try { fedora = context.resolvePropertyPlaceholders("{{fcrepo.baseUrl}}"); endpoint = InetAddress.getLocalHost().getHostName() + ":" + context.resolvePropertyPlaceholders("{{rest.port}}") + context.resolvePropertyPlaceholders("{{rest.prefix}}"); } catch (final Exception ex) { throw new RuntimeCamelException("Could not resolve property placeholders", ex); } final StringBuilder sb = new StringBuilder(); sb.append("Geneva Synchronization Service\n\n"); sb.append("\tConfigured Fedora Location: " + fedora + "\n"); sb.append("\tConfigured REST Endpoint: " + endpoint + "\n\n"); sb.append("You can POST to defined endpoint, and it will begin\n"); sb.append("a re-synchronization task with the configured datastore.\n\n"); sb.append("For example:\n\n"); sb.append("\tcurl -XPOST " + endpoint + "\n\n"); in.setBody(sb.toString()); }
@Test public void testCreateNotificationEmail() throws Exception { String expectedEmailBody = "Booking Name: Simpson, Homer<br/>Name in Parole case information: offenderName<br/>\n" + "SID: A9999999<br/>\n" + "DATE/TIME OF BOOKING: 2013-09-06<br/>\n" + "ARRESTING AGENCY: Honolulu PD<br/>ATTORNEY GENERAL CASE: false<br/>\n" + "ARREST CHARGES:<br/>\n" + "Description: Assault Severity: very severe, ARN: I-04679<br/>\n" + "<br/><br/>Positively identified by fingerprint."; EmailNotification email = new EmailNotification(); email.addToAddressee("po1@localhost"); email.setSubjectName("offenderName"); email.setSubscribingSystemIdentifier("{http://demostate.gov/SystemNames/1.0}SystemA"); email.setSubscriptionCategoryCode("default"); email.setNotificationRequest(new ArrestNotificationRequest(getNotificationMessage())); Exchange e = new DefaultExchange((CamelContext) null); Message inMessage = e.getIn(); inMessage.setHeader("notificationTopic", "arrest"); inMessage.setBody(email); arrestNotificationProcessor.createNotificationEmail(e); Object receivedEmailBody = e.getOut().getBody(); assertEquals(expectedEmailBody, receivedEmailBody); assertEquals("po1@localhost", e.getOut().getHeader(NotificationConstants.HEADER_TO)); }
public void process(Exchange exchange) throws Exception { Jaxp11XMLReaderCreator xmlCreator = new Jaxp11XMLReaderCreator(); DefaultValidationErrorHandler errorHandler = new DefaultValidationErrorHandler(); PropertyMapBuilder mapBuilder = new PropertyMapBuilder(); mapBuilder.put(ValidateProperty.XML_READER_CREATOR, xmlCreator); mapBuilder.put(ValidateProperty.ERROR_HANDLER, errorHandler); PropertyMap propertyMap = mapBuilder.toPropertyMap(); Validator validator = getSchema().createValidator(propertyMap); Message in = exchange.getIn(); SAXSource saxSource = in.getBody(SAXSource.class); if (saxSource == null) { Source source = exchange.getIn().getMandatoryBody(Source.class); saxSource = ExchangeHelper.convertToMandatoryType(exchange, SAXSource.class, source); } InputSource bodyInput = saxSource.getInputSource(); // now lets parse the body using the validator XMLReader reader = xmlCreator.createXMLReader(); reader.setContentHandler(validator.getContentHandler()); reader.setDTDHandler(validator.getDTDHandler()); reader.setErrorHandler(errorHandler); reader.parse(bodyInput); errorHandler.handleErrors(exchange, schema); }
@Override public void onAfterRoute(Route route, Exchange exchange) { // add the CORS headers after routing, but before the consumer writes the response Message msg = exchange.hasOut() ? exchange.getOut() : exchange.getIn(); // use default value if none has been configured String allowOrigin = corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Origin") : null; if (allowOrigin == null) { allowOrigin = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_ORIGIN; } String allowMethods = corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Methods") : null; if (allowMethods == null) { allowMethods = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_METHODS; } String allowHeaders = corsHeaders != null ? corsHeaders.get("Access-Control-Allow-Headers") : null; if (allowHeaders == null) { allowHeaders = RestConfiguration.CORS_ACCESS_CONTROL_ALLOW_HEADERS; } String maxAge = corsHeaders != null ? corsHeaders.get("Access-Control-Max-Age") : null; if (maxAge == null) { maxAge = RestConfiguration.CORS_ACCESS_CONTROL_MAX_AGE; } msg.setHeader("Access-Control-Allow-Origin", allowOrigin); msg.setHeader("Access-Control-Allow-Methods", allowMethods); msg.setHeader("Access-Control-Allow-Headers", allowHeaders); msg.setHeader("Access-Control-Max-Age", maxAge); }
private void populateRoutingInfoHeaders(final Message message, final Envelope envelope) { if (envelope != null) { message.setHeader(RabbitMQConstants.ROUTING_KEY, envelope.getRoutingKey()); message.setHeader(RabbitMQConstants.EXCHANGE_NAME, envelope.getExchange()); message.setHeader(RabbitMQConstants.DELIVERY_TAG, envelope.getDeliveryTag()); } }
/** * All headers except collection and database are non available for this operation. * * @param exchange * @throws Exception */ protected void doAggregate(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); DBObject query = exchange.getIn().getMandatoryBody(DBObject.class); // Impossible with java driver to get the batch size and number to skip Iterable<DBObject> dbIterator = null; AggregationOutput aggregationResult = null; // Allow body to be a pipeline // @see http://docs.mongodb.org/manual/core/aggregation/ if (query instanceof BasicDBList) { BasicDBList queryList = (BasicDBList) query; aggregationResult = dbCol.aggregate( (DBObject) queryList.get(0), queryList .subList(1, queryList.size()) .toArray(new BasicDBObject[queryList.size() - 1])); } else { aggregationResult = dbCol.aggregate(query); } dbIterator = aggregationResult.results(); Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.aggregate); resultMessage.setBody(dbIterator); }
public void testSetBodyType() throws Exception { Exchange exchange = new DefaultExchange(context); Message in = exchange.getIn(); in.setBody("123", Integer.class); assertIsInstanceOf(Integer.class, in.getBody()); }
protected void populateResponse( Exchange exchange, HttpMethod method, Message in, HeaderFilterStrategy strategy, int responseCode) throws IOException, ClassNotFoundException { // We just make the out message is not create when extractResponseBody throws exception, Object response = extractResponseBody(method, exchange); Message answer = exchange.getOut(); answer.setHeader(Exchange.HTTP_RESPONSE_CODE, responseCode); answer.setBody(response); // propagate HTTP response headers Header[] headers = method.getResponseHeaders(); for (Header header : headers) { String name = header.getName(); String value = header.getValue(); if (name.toLowerCase().equals("content-type")) { name = Exchange.CONTENT_TYPE; exchange.setProperty(Exchange.CHARSET_NAME, IOHelper.getCharsetNameFromContentType(value)); } // use http helper to extract parameter value as it may contain multiple values Object extracted = HttpHelper.extractHttpParameterValue(value); if (strategy != null && !strategy.applyFilterToExternalHeaders(name, extracted, exchange)) { HttpHelper.appendHeader(answer.getHeaders(), name, extracted); } } // preserve headers from in by copying any non existing headers // to avoid overriding existing headers with old values MessageHelper.copyHeaders(exchange.getIn(), answer, false); }
/** {@inheritDoc} */ @Override public void mapTo(Context context, CamelBindingData target) throws Exception { Message message = target.getMessage(); Exchange exchange = message.getExchange(); for (Property property : context.getProperties(Scope.MESSAGE)) { String name = property.getName(); if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) { Object value = property.getValue(); if (value != null) { message.setHeader(name, value); } } } if (exchange != null) { for (Property property : context.getProperties(Scope.EXCHANGE)) { String name = property.getName(); if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) { Object value = property.getValue(); if (value != null) { exchange.setProperty(name, value); } } } } }
/** {@inheritDoc} */ @Override public void mapFrom(CamelBindingData source, Context context) throws Exception { Message message = source.getMessage(); Exchange exchange = message.getExchange(); for (Map.Entry<String, Object> header : message.getHeaders().entrySet()) { String name = header.getKey(); if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) { Object value = header.getValue(); if (value != null) { context.setProperty(name, value, Scope.MESSAGE).addLabels(getCamelLabels()); } } } if (exchange != null) { for (Map.Entry<String, Object> property : exchange.getProperties().entrySet()) { String name = property.getKey(); if (matches(name) && !name.startsWith("org.switchyard.bus.camel")) { Object value = property.getValue(); if (value != null) { context.setProperty(name, value, Scope.EXCHANGE).addLabels(getCamelLabels()); } } } } }
private Message prepareResponseMessage(Exchange exchange, MongoDbOperation operation) { Message answer = exchange.getOut(); MessageHelper.copyHeaders(exchange.getIn(), answer, false); if (isWriteOperation(operation) && endpoint.isWriteResultAsHeader()) { answer.setBody(exchange.getIn().getBody()); } return answer; }
public void processDataSet(Exchange originalExchange, DataSet dataSet, int counter) throws Exception { Exchange exchange = originalExchange.copy(); Message in = exchange.getIn(); in.setBody(dataSet); in.setHeader("CamelFlatpackCounter", counter); loadBalancer.process(exchange); }
@Override protected void setUp() throws Exception { super.setUp(); Message in = exchange.getIn(); in.setBody("Hello there!"); in.setHeader("name", "James"); in.setHeader("location", "Islington,London,UK"); }
/** * Creates a JMS message from the Camel exchange and message * * @param exchange the current exchange * @param camelMessage the body to make a javax.jms.Message as * @param session the JMS session used to create the message * @param cause optional exception occurred that should be sent as reply instead of a regular body * @return a newly created JMS Message instance containing the * @throws JMSException if the message could not be created */ public Message makeJmsMessage( Exchange exchange, org.apache.camel.Message camelMessage, Session session, Exception cause) throws JMSException { Message answer = null; boolean alwaysCopy = endpoint != null && endpoint.getConfiguration().isAlwaysCopyMessage(); boolean force = endpoint != null && endpoint.getConfiguration().isForceSendOriginalMessage(); if (!alwaysCopy && camelMessage instanceof JmsMessage) { JmsMessage jmsMessage = (JmsMessage) camelMessage; if (!jmsMessage.shouldCreateNewMessage() || force) { answer = jmsMessage.getJmsMessage(); if (!force) { // answer must match endpoint type JmsMessageType type = endpoint != null ? endpoint.getConfiguration().getJmsMessageType() : null; if (type != null && answer != null) { if (type == JmsMessageType.Text) { answer = answer instanceof TextMessage ? answer : null; } else if (type == JmsMessageType.Bytes) { answer = answer instanceof BytesMessage ? answer : null; } else if (type == JmsMessageType.Map) { answer = answer instanceof MapMessage ? answer : null; } else if (type == JmsMessageType.Object) { answer = answer instanceof ObjectMessage ? answer : null; } else if (type == JmsMessageType.Stream) { answer = answer instanceof StreamMessage ? answer : null; } } } } } if (answer == null) { if (cause != null) { // an exception occurred so send it as response LOG.debug("Will create JmsMessage with caused exception: {}", cause); // create jms message containing the caused exception answer = createJmsMessage(cause, session); } else { ObjectHelper.notNull(camelMessage, "message"); // create regular jms message using the camel message body answer = createJmsMessage( exchange, camelMessage.getBody(), camelMessage.getHeaders(), session, exchange.getContext()); appendJmsProperties(answer, exchange, camelMessage); } } if (answer != null && messageCreatedStrategy != null) { messageCreatedStrategy.onMessageCreated(answer, session, exchange, null); } return answer; }
@SuppressWarnings("unchecked") protected void doUpdate(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); List<DBObject> saveObj = exchange.getIn().getMandatoryBody((Class<List<DBObject>>) (Class<?>) List.class); if (saveObj.size() != 2) { throw new CamelMongoDbException( "MongoDB operation = insert, failed because body is not a List of DBObject objects with size = 2"); } DBObject updateCriteria = saveObj.get(0); DBObject objNew = saveObj.get(1); Boolean multi = exchange.getIn().getHeader(MongoDbConstants.MULTIUPDATE, Boolean.class); Boolean upsert = exchange.getIn().getHeader(MongoDbConstants.UPSERT, Boolean.class); WriteResult result; WriteConcern wc = extractWriteConcern(exchange); // In API 2.7, the default upsert and multi values of update(DBObject, DBObject) are false, // false, so we unconditionally invoke the // full-signature method update(DBObject, DBObject, boolean, boolean). However, the default // behaviour may change in the future, // so it's safer to be explicit at this level for full determinism if (multi == null && upsert == null) { // for update with no multi nor upsert but with specific WriteConcern there is no update // signature without multi and upsert args, // so assume defaults result = wc == null ? dbCol.update(updateCriteria, objNew) : dbCol.update(updateCriteria, objNew, false, false, wc); } else { // we calculate the final boolean values so that if any of these // parameters is null, it is resolved to false result = wc == null ? dbCol.update( updateCriteria, objNew, calculateBooleanValue(upsert), calculateBooleanValue(multi)) : dbCol.update( updateCriteria, objNew, calculateBooleanValue(upsert), calculateBooleanValue(multi), wc); } Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.update); // we always return the WriteResult, because whether the getLastError was called or not, the // user will have the means to call it or // obtain the cached CommandResult processAndTransferWriteResult(result, exchange); resultMessage.setHeader(MongoDbConstants.RECORDS_AFFECTED, result.getN()); }
@Test public void testDefault() throws Exception { mock.expectedBodiesReceived("test1"); mock.expectedHeaderReceived("test", "test2"); producerTemplate.sendBodyAndHeader("direct:input", "test1", "test", "test2"); mock.assertIsSatisfied(); Message received = mock.getExchanges().get(0).getIn(); assertEquals("default", received.getHeader(GTaskBinding.GTASK_QUEUE_NAME)); assertEquals(0, received.getHeader(GTaskBinding.GTASK_RETRY_COUNT)); }
public NCSServicePath createPath( @JuniperXPath("//juniper:ServicePath") NodeList pathList, Exchange exchange) { Message in = exchange.getIn(); String nodeForeignSource = (String) in.getHeader("nodeForeignSource"); String serviceForeignSource = (String) in.getHeader("foreignSource"); Node servicePath = pathList.item(0); return new NCSServicePath( servicePath, m_dao, m_nodeDao, nodeForeignSource, serviceForeignSource); }
@Override public void process(Exchange exchange) { final Message in = exchange.getIn(); final Collection<?> list = in.getBody(AbstractCollection.class); BigDecimal total = BigDecimal.ZERO; for (Object value : list) { total = total.add(BigDecimal.valueOf((Integer) value)); } in.setBody(total.divide(new BigDecimal(list.size()), RoundingMode.HALF_UP)); }
public Exchange createMongoDbExchange(DBObject dbObj) { Exchange exchange = new DefaultExchange(this.getCamelContext(), getExchangePattern()); Message message = new DefaultMessage(); message.setHeader(MongoDbConstants.DATABASE, database); message.setHeader(MongoDbConstants.COLLECTION, collection); message.setHeader(MongoDbConstants.FROM_TAILABLE, true); message.setBody(dbObj); exchange.setIn(message); return exchange; }
@Test public void testNoFeedInHeader() throws Exception { MockEndpoint mock = getMockEndpoint("mock:result"); mock.expectedMessageCount(1); mock.assertIsSatisfied(); Exchange exchange = mock.getExchanges().get(0); Message in = exchange.getIn(); assertNotNull(in); assertNull(in.getHeader(RssConstants.RSS_FEED)); }
// START SNIPPET: e1 private Exchange createLetter() { Exchange exchange = context.getEndpoint("direct:a").createExchange(); Message msg = exchange.getIn(); msg.setHeader("firstName", "Claus"); msg.setHeader("lastName", "Ibsen"); msg.setHeader("item", "Camel in Action"); msg.setBody("PS: Next beer is on me, James"); return exchange; }
protected void doFindAll(Exchange exchange) throws Exception { DBCollection dbCol = calculateCollection(exchange); // do not use getMandatoryBody, because if the body is empty we want to retrieve all objects in // the collection DBObject query = null; // do not run around looking for a type converter unless there is a need for it if (exchange.getIn().getBody() != null) { query = exchange.getIn().getBody(DBObject.class); } DBObject fieldFilter = exchange.getIn().getHeader(MongoDbConstants.FIELDS_FILTER, DBObject.class); // get the batch size and number to skip Integer batchSize = exchange.getIn().getHeader(MongoDbConstants.BATCH_SIZE, Integer.class); Integer numToSkip = exchange.getIn().getHeader(MongoDbConstants.NUM_TO_SKIP, Integer.class); Integer limit = exchange.getIn().getHeader(MongoDbConstants.LIMIT, Integer.class); DBObject sortBy = exchange.getIn().getHeader(MongoDbConstants.SORT_BY, DBObject.class); DBCursor ret = null; try { if (query == null && fieldFilter == null) { ret = dbCol.find(new BasicDBObject()); } else if (fieldFilter == null) { ret = dbCol.find(query); } else { ret = dbCol.find(query, fieldFilter); } if (sortBy != null) { ret.sort(sortBy); } if (batchSize != null) { ret.batchSize(batchSize.intValue()); } if (numToSkip != null) { ret.skip(numToSkip.intValue()); } if (limit != null) { ret.limit(limit.intValue()); } Message resultMessage = prepareResponseMessage(exchange, MongoDbOperation.findAll); resultMessage.setBody(ret.toArray()); resultMessage.setHeader(MongoDbConstants.RESULT_TOTAL_SIZE, ret.count()); resultMessage.setHeader(MongoDbConstants.RESULT_PAGE_SIZE, ret.size()); } finally { // make sure the cursor is closed if (ret != null) { ret.close(); } } }