Java Code Examples for org.apache.camel.Message#getBody()

The following examples show how to use org.apache.camel.Message#getBody() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: MyProcessor.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    String result = "Unknown language";

    final Message inMessage = exchange.getIn();
    final String body = inMessage.getBody(String.class);
    final String language = inMessage.getHeader("language", String.class);

    if ("en".equals(language)) {
        result = "Hello " + body;
    } else if ("fr".equals(language)) {
        result = "Bonjour " + body;
    }

    inMessage.setBody(result);
}
 
Example 2
Source File: FhirTransactionCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
public void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    String body = in.getBody(String.class);

    if (body != null) {
        List<IBaseResource> resources = new ArrayList<>();
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
            Document doc = dbf.newDocumentBuilder().parse(new ByteArrayInputStream(body.getBytes("UTF-8")));
            Node transactionElement = doc.getFirstChild();
            NodeList childNodes = transactionElement.getChildNodes();
            IParser parser = fhirContext.newXmlParser();
            for (int i = 0; i < childNodes.getLength(); i++) {
                Node resourceNode = childNodes.item(i);
                Document resourceDocument = toDocument(resourceNode, dbf);
                String resourceXml = toXml(resourceDocument);
                IBaseResource resource = parser.parseResource(resourceXml);
                resources.add(resource);
            }
        } catch (SAXException | IOException | ParserConfigurationException | TransformerException e) {
            throw new RuntimeExchangeException("Cannot convert Transaction to a list of resources", exchange, e);
        }

        in.setHeader("CamelFhir.resources", resources);
    }
}
 
Example 3
Source File: SpringWsIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void consumeStockQuoteWebserviceInOnly() throws Exception {
    inOnlyEndpoint.expectedExchangePattern(ExchangePattern.InOnly);
    inOnlyEndpoint.expectedMessageCount(1);

    template.sendBodyAndHeader("direct:stockQuoteWebserviceInOnly", xmlRequestForGoogleStockQuote, "foo", "bar");

    inOnlyEndpoint.assertIsSatisfied();

    Message in = inOnlyEndpoint.getReceivedExchanges().get(0).getIn();

    Object result = in.getBody();
    Assert.assertNotNull(result);
    Assert.assertTrue(result instanceof String);
    String resultMessage = (String) result;
    Assert.assertTrue(resultMessage.contains("Google Inc."));

    Object bar = in.getHeader("foo");
    Assert.assertEquals("The header value should have been preserved", "bar", bar);
}
 
Example 4
Source File: EMailSendCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private void beforeProducer(Exchange exchange) throws MessagingException, IOException {
    final Message in = exchange.getIn();
    final EMailMessageModel mail = in.getBody(EMailMessageModel.class);
    if (mail == null) {
        return;
    }

    in.setHeader(MAIL_FROM, updateMail(from, mail.getFrom()));
    in.setHeader(MAIL_TO, updateMail(to, mail.getTo()));
    in.setHeader(MAIL_CC, updateMail(cc, mail.getCc()));
    in.setHeader(MAIL_BCC, updateMail(bcc, mail.getBcc()));
    in.setHeader(MAIL_SUBJECT, updateMail(subject, mail.getSubject()));

    Object content = updateMail(text, mail.getContent());
    in.setBody(content);
    setContentType(content, in);
}
 
Example 5
Source File: ODataDeleteCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
protected void beforeProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    String body = in.getBody(String.class);
    JsonNode node = OBJECT_MAPPER.readTree(body);
    JsonNode keyPredicateNode = node.get(KEY_PREDICATE);

    if (! ObjectHelper.isEmpty(keyPredicateNode)) {
        String keyPredicate = keyPredicateNode.asText();

        //
        // Change the resource path instead as there is a bug in using the
        // keyPredicate header (adds brackets around regardless of a subpredicate
        // being present). When that's fixed we can revert back to using keyPredicate
        // header instead.
        //
        in.setHeader(OLINGO4_PROPERTY_PREFIX + RESOURCE_PATH,
                     resourcePath + ODataUtil.formatKeyPredicate(keyPredicate, true));
    }

    in.setBody(EMPTY_STRING);
}
 
Example 6
Source File: ResponsePayloadMapper.java    From jbpm-work-items with Apache License 2.0 6 votes vote down vote up
@Override
public Map<String, Object> mapFromResponse(Exchange exchange) {
    Map<String, Object> results = new HashMap<String, Object>();
    if (exchange.hasOut()) {
        Message out = exchange.getOut();
        Object response = out.getBody();
        results.put(responseLocation,
                    response);
        Map<String, Object> headerValues = out.getHeaders();
        for (String headerLocation : this.headerLocations) {
            results.put(headerLocation,
                        headerValues.get(headerLocation));
        }
    }
    return results;
}
 
Example 7
Source File: TwitterMediaAction.java    From syndesis-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Builds JSON message body of the MediaEntities detected in the Twitter message. Removes
 * the Body of the message if no Entities are found
 *
 *
 * @param exchange 	The Camel Exchange object containing the Message, that in turn should
 * 					contain the MediaEntity and MediaURL
 */
private void process(Exchange exchange) {
	// validate input
	if (ObjectHelper.isEmpty(exchange)) {
		throw new NullPointerException("Exchange is empty. Should be impossible.");
	}

	Message message = exchange.getMessage();
	if (ObjectHelper.isEmpty(message)) {
		throw new NullPointerException("Message is empty. Should be impossible.");
	}

	Object incomingBody = message.getBody();

	if (incomingBody instanceof Status) {
		message.setBody((new TweetMedia((Status)incomingBody)).toJSON());
	} else {
		throw new ClassCastException("Body isn't Status, why are you using this component!?"
				+ (incomingBody != null ? incomingBody.getClass() : " empty"));
	}
}
 
Example 8
Source File: KnativeHttpConsumer.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
private Buffer computeResponseBody(Message message) throws NoTypeConversionAvailableException {
    Object body = message.getBody();
    Exception exception = message.getExchange().getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = sw.toString().getBytes(StandardCharsets.UTF_8);
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain");

        // and mark the exception as failure handled, as we handled it by returning
        // it as the response
        ExchangeHelper.setFailureHandled(message.getExchange());
    }

    return body != null
        ? Buffer.buffer(message.getExchange().getContext().getTypeConverter().mandatoryConvertTo(byte[].class, body))
        : null;
}
 
Example 9
Source File: DataMapperStepHandler.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Convert list typed message body to Json array String representation.
 */
private static void convertMessageJsonTypeBody(Exchange exchange, Message message) {
    if (message != null && message.getBody() instanceof List) {
        List<?> jsonBeans = message.getBody(List.class);
        message.setBody(JsonUtils.jsonBeansToArray(jsonBeans));

        // mark auto conversion so we can reconvert after data mapper is done
        exchange.setProperty(DATA_MAPPER_AUTO_CONVERSION, true);
    }
}
 
Example 10
Source File: ForUpdateCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public void beforeProducer(final Exchange exchange) throws IOException {
    // parse input json and extract Id field
    final Message in = exchange.getIn();
    final String body = in.getBody(String.class);

    if (body == null) {
        return;
    }

    final ObjectNode node = (ObjectNode) JsonUtils.reader().readTree(body);

    final JsonNode idProperty = node.remove(idPropertyName);
    if (idProperty == null) {
        exchange.setException(
            new SalesforceException("Missing option value for Id or " + SalesforceEndpointConfig.SOBJECT_EXT_ID_NAME, 404));

        return;
    }

    final String idValue = idProperty.textValue();
    if ("Id".equals(idPropertyName)) {
        in.setHeader(SalesforceEndpointConfig.SOBJECT_ID, idValue);
    } else {
        in.setHeader(SalesforceEndpointConfig.SOBJECT_EXT_ID_VALUE, idValue);
    }

    // base fields are not allowed to be updated
    clearBaseFields(node);

    // update input json
    in.setBody(JsonUtils.writer().writeValueAsString(node));
}
 
Example 11
Source File: DroolsCommandHelper.java    From servicemix with Apache License 2.0 5 votes vote down vote up
public void insertAndFireAll(Exchange exchange) {
	final Message in = exchange.getIn();
	final Object body = in.getBody();

	// TODO: add type checking to handle arrays of objects

	BatchExecutionCommandImpl command = new BatchExecutionCommandImpl();
	final List<GenericCommand<?>> commands = command.getCommands();
	commands.add(new InsertObjectCommand(body, "obj1"));
	commands.add(new FireAllRulesCommand());

	in.setBody(command);
}
 
Example 12
Source File: FhirSearchCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();

    if (ObjectHelper.isNotEmpty(query)) {
        in.setBody(resourceType + "?" + query);
    }

    FhirResourceQuery body = in.getBody(FhirResourceQuery.class);
    if (body != null && ObjectHelper.isNotEmpty(body.getQuery())) {
        in.setBody(resourceType + "?" + body.getQuery());
    }
}
 
Example 13
Source File: KuduInsertCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final String body = in.getBody(String.class);

    if (ObjectHelper.isNotEmpty(body)) {
        in.setBody(body);
    } else {
        in.setBody("{}");
    }
}
 
Example 14
Source File: ExpectingIdCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public void beforeProducer(final Exchange exchange) {
    final Message in = exchange.getIn();
    final SalesforceIdentifier id = in.getBody(SalesforceIdentifier.class);

    if (id != null) {
        in.setBody(id.getId());
    }
}
 
Example 15
Source File: QuarkusPlatformHttpConsumer.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
static Object toHttpResponse(HttpServerResponse response, Message message, HeaderFilterStrategy headerFilterStrategy) {
    final Exchange exchange = message.getExchange();

    final int code = determineResponseCode(exchange, message.getBody());
    response.setStatusCode(code);

    final TypeConverter tc = exchange.getContext().getTypeConverter();

    // copy headers from Message to Response
    if (headerFilterStrategy != null) {
        for (Map.Entry<String, Object> entry : message.getHeaders().entrySet()) {
            final String key = entry.getKey();
            final Object value = entry.getValue();
            // use an iterator as there can be multiple values. (must not use a delimiter)
            final Iterator<?> it = ObjectHelper.createIterator(value, null);
            String firstValue = null;
            List<String> values = null;
            while (it.hasNext()) {
                final String headerValue = tc.convertTo(String.class, it.next());
                if (headerValue != null
                        && !headerFilterStrategy.applyFilterToCamelHeaders(key, headerValue, exchange)) {
                    if (firstValue == null) {
                        firstValue = headerValue;
                    } else {
                        if (values == null) {
                            values = new ArrayList<String>();
                            values.add(firstValue);
                        }
                        values.add(headerValue);
                    }
                }
            }
            if (values != null) {
                response.putHeader(key, values);
            } else if (firstValue != null) {
                response.putHeader(key, firstValue);
            }
        }
    }

    Object body = message.getBody();
    final Exception exception = exchange.getException();

    if (exception != null) {
        // we failed due an exception so print it as plain text
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw);
        exception.printStackTrace(pw);

        // the body should then be the stacktrace
        body = ByteBuffer.wrap(sw.toString().getBytes(StandardCharsets.UTF_8));
        // force content type to be text/plain as that is what the stacktrace is
        message.setHeader(Exchange.CONTENT_TYPE, "text/plain; charset=utf-8");

        // and mark the exception as failure handled, as we handled it by returning it as the response
        ExchangeHelper.setFailureHandled(exchange);
    }

    // set the content-length if it can be determined, or chunked encoding
    final Integer length = determineContentLength(exchange, body);
    if (length != null) {
        response.putHeader("Content-Length", String.valueOf(length));
    } else {
        response.setChunked(true);
    }

    // set the content type in the response.
    final String contentType = MessageHelper.getContentType(message);
    if (contentType != null) {
        // set content-type
        response.putHeader("Content-Type", contentType);
    }
    return body;
}
 
Example 16
Source File: UndertowWsIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void fireWebSocketChannelEvents() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            final int port = getPort();
            /* sendToAll */
            from("undertow:ws://localhost:" + port + "/app5?fireWebSocketChannelEvents=true") //
                    .to("mock:result5") //
                    .to("undertow:ws://localhost:" + port + "/app5");
        }

    });

    camelctx.start();
    try {

        MockEndpoint result = camelctx.getEndpoint("mock:result5", MockEndpoint.class);
        result.expectedMessageCount(6);

        TestClient wsclient1 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        TestClient wsclient2 = new TestClient("ws://localhost:" + getPort() + "/app5", 2);
        wsclient1.connect();
        wsclient2.connect();

        wsclient1.sendTextMessage("Gambas");
        wsclient2.sendTextMessage("Calamares");

        wsclient1.close();
        wsclient2.close();

        result.await(60, TimeUnit.SECONDS);

        final List<Exchange> exchanges = result.getReceivedExchanges();
        final Map<String, List<String>> connections = new HashMap<>();
        for (Exchange exchange : exchanges) {
            final Message in = exchange.getIn();
            final String key = (String) in.getHeader(UndertowConstants.CONNECTION_KEY);
            Assert.assertNotNull(key);
            List<String> messages = connections.get(key);
            if (messages == null) {
                messages = new ArrayList<String>();
                connections.put(key, messages);
            }
            String body = in.getBody(String.class);
            if (body != null) {
                messages.add(body);
            } else {
                messages.add(in.getHeader(UndertowConstants.EVENT_TYPE_ENUM, EventType.class).name());
            }
        }

        final List<String> expected1 = Arrays.asList(EventType.ONOPEN.name(), "Gambas", EventType.ONCLOSE.name());
        final List<String> expected2 = Arrays.asList(EventType.ONOPEN.name(), "Calamares",
                EventType.ONCLOSE.name());

        Assert.assertEquals(2, connections.size());
        final Iterator<List<String>> it = connections.values().iterator();
        final List<String> actual1 = it.next();
        Assert.assertTrue("actual " + actual1, actual1.equals(expected1) || actual1.equals(expected2));
        final List<String> actual2 = it.next();
        Assert.assertTrue("actual " + actual2, actual2.equals(expected1) || actual2.equals(expected2));
    } finally {
        camelctx.close();
    }

}
 
Example 17
Source File: ManagementBusInvocationPluginRemote.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public Exchange invoke(final Exchange exchange) {

    LOG.debug("Invoking IA on remote OpenTOSCA Container.");
    final Message message = exchange.getIn();
    final Object body = message.getBody();

    // IA invocation request containing the input parameters
    final IAInvocationRequest invocationRequest = parseBodyToInvocationRequest(body);

    // create request message and add the input parameters as body
    final BodyType requestBody = new BodyType(invocationRequest);
    final CollaborationMessage request = new CollaborationMessage(new KeyValueMap(), requestBody);

    // perform remote IA operation
    final Exchange responseExchange = requestSender.sendRequestToRemoteContainer(message, RemoteOperations.INVOKE_IA_OPERATION, request, 0);

    LOG.debug("Received a response for the invocation request!");

    if (!(responseExchange.getIn().getBody() instanceof CollaborationMessage)) {
        LOG.error("Received message has invalid class: {}", responseExchange.getIn().getBody().getClass());
        return exchange;
    }

    // extract the body and process the contained response
    final CollaborationMessage responseMessage = responseExchange.getIn().getBody(CollaborationMessage.class);
    final BodyType responseBody = responseMessage.getBody();

    if (Objects.isNull(responseBody)) {
        LOG.error("Collaboration message contains no body.");
        return exchange;
    }

    final IAInvocationRequest invocationResponse = responseBody.getIAInvocationRequest();

    if (Objects.isNull(invocationResponse)) {
        LOG.error("Body contains no IAInvocationRequest object with the result.");
        return exchange;
    }

    // process output of the response
    if (invocationResponse.getParams() != null) {
        LOG.debug("Response contains output as HashMap:");

        final HashMap<String, String> outputParamMap = new HashMap<>();

        for (final KeyValueType outputParam : invocationResponse.getParams().getKeyValuePair()) {
            LOG.debug("Key: {}, Value: {}", outputParam.getKey(), outputParam.getValue());
            outputParamMap.put(outputParam.getKey(), outputParam.getValue());
        }
        message.setBody(outputParamMap, HashMap.class);
    } else {
        if (invocationResponse.getDoc() != null) {
            LOG.debug("Response contains output as Document");

            try {
                final DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
                final DocumentBuilder build = dFact.newDocumentBuilder();
                final Document document = build.newDocument();

                final Element element = invocationResponse.getDoc().getAny();

                document.adoptNode(element);
                document.appendChild(element);

                message.setBody(document, Document.class);
            } catch (final Exception e) {
                LOG.error("Unable to parse Document: {}", e.getMessage());
            }
        } else {
            LOG.warn("Response contains no output.");
            message.setBody(null);
        }
    }

    return exchange;
}
 
Example 18
Source File: DefaultNotifyHandler.java    From mdw with Apache License 2.0 4 votes vote down vote up
public Object initializeRequestDocument(Message request) throws MdwCamelException {
    return request.getBody(String.class);
}
 
Example 19
Source File: RequestReceiver.java    From container with Apache License 2.0 4 votes vote down vote up
/**
 * Perform instance data matching with the transferred NodeType and properties and the instance data of the local
 * OpenTOSCA Container. NodeType and properties have to be passed as part of the {@link CollaborationMessage} in the
 * message body of the exchange. The method sends a reply to the topic specified in the headers of the incoming
 * exchange if the matching is successful and adds the deployment location as header to the outgoing exchange.
 * Otherwise no response is send.
 *
 * @param exchange the exchange containing the needed information as headers and body
 */
public void invokeInstanceDataMatching(final Exchange exchange) {

    LOG.debug("Received remote operation call for instance data matching.");
    final Message message = exchange.getIn();

    // check whether the request contains the needed header fields to send a response
    final Map<String, Object> headers = getResponseHeaders(message);
    if (Objects.isNull(headers)) {
        LOG.error("Request does not contain all needed header fields to send a response. Aborting operation!");
        return;
    }

    if (!(message.getBody() instanceof CollaborationMessage)) {
        LOG.error("Message body has invalid class: {}. Aborting operation!", message.getBody().getClass());
        return;
    }

    final CollaborationMessage collMsg = (CollaborationMessage) message.getBody();
    final BodyType body = collMsg.getBody();

    if (Objects.isNull(body)) {
        LOG.error("Collaboration message contains no body. Aborting operation!");
        return;
    }

    final InstanceDataMatchingRequest request = body.getInstanceDataMatchingRequest();

    if (Objects.isNull(request)) {
        LOG.error("Body contains no InstanceDataMatchingRequest. Aborting operation!");
        return;
    }

    LOG.debug("InstanceDataMatchingRequest contained in incoming message. Processing it...");

    // get NodeType and properties from the request
    final QName nodeType = request.getNodeType();
    final Map<String, String> properties = new HashMap<>();
    for (final KeyValueType property : request.getProperties().getKeyValuePair()) {
        properties.put(property.getKey(), property.getValue());
    }

    LOG.debug("Performing matching with NodeType: {} and properties: {}", nodeType, properties.toString());

    // perform instance data matching
    final String deploymentLocation = decisionMaker.performInstanceDataMatching(nodeType, properties);
    if (deploymentLocation != null) {
        LOG.debug("Instance data matching was successful. Sending response to requestor...");
        LOG.debug("Broker: {} Topic: {} Correlation: {}",
            headers.get(MBHeader.MQTTBROKERHOSTNAME_STRING.toString()),
            headers.get(MBHeader.MQTTTOPIC_STRING.toString()),
            headers.get(MBHeader.CORRELATIONID_STRING.toString()));

        // add the deployment location as operation result to the headers
        headers.put(MBHeader.DEPLOYMENTLOCATION_STRING.toString(), deploymentLocation);

        // create empty reply message and transmit it with the headers
        final CollaborationMessage replyBody = new CollaborationMessage(new KeyValueMap(), null);
        collaborationContext.getProducer().sendBodyAndHeaders("direct:SendMQTT", replyBody, headers);
    } else {
        // if matching is not successful, no response is needed
        LOG.debug("Instance data matching was not successful.");
    }
}
 
Example 20
Source File: SlackChannelCustomizer.java    From syndesis with Apache License 2.0 3 votes vote down vote up
private static void beforeProducer(Exchange exchange) {

        final Message in = exchange.getIn();
        final SlackPlainMessage message = in.getBody(SlackPlainMessage.class);

        if (message != null) {
            in.setBody(message.getMessage());
        }

    }