Java Code Examples for org.apache.camel.Exchange#getIn()

The following examples show how to use org.apache.camel.Exchange#getIn() . These examples are extracted from open source projects. 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 want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: syndesis   File: FhirSearchCustomizer.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void afterProducer(Exchange exchange) {
    Message in = exchange.getIn();
    Bundle bundle = in.getBody(Bundle.class);
    if (bundle == null) {
        return;
    }

    List<String> results = new ArrayList<>();
    for (Bundle.BundleEntryComponent entry: bundle.getEntry()) {
        String resource = fhirContext.newXmlParser().encodeResourceToString(entry.getResource());
        results.add(resource);
    }

    in.setBody(results);
}
 
Example 2
@Test
public void testThrottleDynamic() throws Exception {
    final int throttleRate = 3;
    final int messageCount = throttleRate + 2;

    getMockEndpoint("mock:unthrottled").expectedMessageCount(messageCount);
    getMockEndpoint("mock:throttled").expectedMessageCount(throttleRate);
    getMockEndpoint("mock:after").expectedMessageCount(throttleRate);

    for (int i = 0; i < messageCount; i++) {
        Exchange exchange = getMandatoryEndpoint("direct:start").createExchange();
        {
            Message in = exchange.getIn();
            in.setHeader("throttleRate", throttleRate);
            in.setBody("Camel Rocks");
        }
        template.asyncSend("direct:start", exchange);
    }

    // the test will stop once all of the conditions have been met
    // the only way this set of conditions can happen is if 2
    // messages are currently suspended for throttling
    assertMockEndpointsSatisfied();
}
 
Example 3
/**
 * Define how a message should be processed.
 *
 * @param exchange the current camel message exchange
 */
public void process(final Exchange exchange) throws Exception {
    final Message in = exchange.getIn();
    final String eventURIBase = in.getHeader(AuditHeaders.EVENT_BASE_URI, String.class);
    final String eventID = in.getHeader(FCREPO_EVENT_ID, String.class);
    final Resource eventURI = createResource(eventURIBase + "/" + eventID);

    // generate SPARQL Update
    final StringBuilder query = new StringBuilder("update=");
    query.append(ProcessorUtils.insertData(serializedGraphForMessage(in, eventURI), ""));

    // update exchange
    in.setBody(query.toString());
    in.setHeader(AuditHeaders.EVENT_URI, eventURI.toString());
    in.setHeader(Exchange.CONTENT_TYPE, "application/x-www-form-urlencoded");
    in.setHeader(Exchange.HTTP_METHOD, "POST");
}
 
Example 4
Source Project: syndesis   File: AggregateStepHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    final Message message = exchange.hasOut() ? exchange.getOut() : exchange.getIn();

    if (message != null && message.getBody() instanceof List) {
        try {
            List<String> unifiedBodies = new ArrayList<>();
            List<?> jsonBeans = message.getBody(List.class);
            for (Object unifiedJsonBean : jsonBeans) {
                JsonNode unifiedJson = JsonUtils.reader().readTree(String.valueOf(unifiedJsonBean));
                if (unifiedJson.isObject()) {
                    JsonNode body = unifiedJson.get("body");
                    if (body != null) {
                        unifiedBodies.add(JsonUtils.writer().writeValueAsString(body));
                    }
                }
            }

            message.setBody("{\"body\":" + JsonUtils.jsonBeansToArray(unifiedBodies) + "}");
        } catch (JsonParseException e) {
            LOG.warn("Unable to aggregate unified json array type", e);
        }
    }
}
 
Example 5
@Override
public Exchange invokeImplementationArtifactUndeployment(final Exchange exchange) {
    LOG.debug("Trying to undeploy IA on remote OpenTOSCA Container.");
    final Message message = exchange.getIn();

    // create empty request message (only headers needed)
    final CollaborationMessage requestBody = new CollaborationMessage(new KeyValueMap(), null);
    // perform remote undeployment
    final Exchange response = requestSender.sendRequestToRemoteContainer(message, RemoteOperations.INVOKE_IA_UNDEPLOYMENT, requestBody,
        0);

    // extract the undeployment state from the response
    final boolean state = response.getIn().getHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), boolean.class);
    LOG.debug("Result of remote undeployment: Success: {}", state);

    // add the header to the incoming exchange and return result
    message.setHeader(MBHeader.OPERATIONSTATE_BOOLEAN.toString(), state);
    return exchange;
}
 
Example 6
private void doAfterProducer(Exchange exchange) {
    Exception e = exchange.getException();
    if (e != null) {
        throw SyndesisConnectorException.wrap(ErrorCategory.CONNECTOR_ERROR, e);
    }
    final Message in = exchange.getIn();
    List<String> list = null;
    if (isRetrieveGeneratedKeys) {
        list = JSONBeanUtil.toJSONBeansFromHeader(in, autoIncrementColumnName);
    } else {
        list = JSONBeanUtil.toJSONBeans(in);
    }
    if (list != null) {
        in.setBody(list);
    }
}
 
Example 7
public String transform(Exchange exchange) {
    SessionID sessionID = exchange.getIn().getHeader(QuickfixjEndpoint.SESSION_ID_KEY, SessionID.class);
    Session session = Session.lookupSession(sessionID);
    DataDictionary dataDictionary = session.getDataDictionary();

    if (dataDictionary == null) {
        throw new IllegalStateException("No Data Dictionary. Exchange must reference an existing session");
    }

    StringBuilder sb = new StringBuilder();
    sb.append("\"event\": {\n");

    org.apache.camel.Message in = exchange.getIn();
    for (String key : in.getHeaders().keySet()) {
        sb.append("  \"").append(key).append("\": ").append(in.getHeader(key)).append(",\n");
    }

    sb.append(renderer.transform(in.getBody(Message.class), "  ", dataDictionary)).append("\n");
    sb.append("}\n");
    return sb.toString();
}
 
Example 8
@Override
public void invokePlan(Exchange exchange) {
    LOG.debug("Parsing Camel Exchange message to PlanInvocationArguments");

    final Message message = exchange.getIn();
    String correlationID = message.getHeader(MBHeader.PLANCORRELATIONID_STRING.toString(), String.class);
    LOG.trace("Correlation ID: {}", correlationID);
    // generate new unique correlation ID if no ID is passed
    if (Objects.isNull(correlationID)) {
        correlationID = PlanInstanceHandler.createCorrelationId();
        message.setHeader(MBHeader.PLANCORRELATIONID_STRING.toString(), correlationID);
    }

    final CsarId csarID = new CsarId(message.getHeader(MBHeader.CSARID.toString(), String.class));
    LOG.trace("CSARID: " + csarID.csarName());

    final URI serviceInstanceID = message.getHeader(MBHeader.SERVICEINSTANCEID_URI.toString(), URI.class);
    LOG.trace("csarInstanceID: {}", serviceInstanceID);

    final QName serviceTemplateID = message.getHeader(MBHeader.SERVICETEMPLATEID_QNAME.toString(), QName.class);
    LOG.debug("serviceTemplateID: {}", serviceTemplateID);

    final QName planID = message.getHeader(MBHeader.PLANID_QNAME.toString(), QName.class);
    LOG.debug("planID: {}", planID);

    // get the ServiceTemplateInstance ID Long from the serviceInstanceID URI
    final Long serviceTemplateInstanceID = Util.determineServiceTemplateInstanceId(serviceInstanceID);
    final Csar csar = storage.findById(csarID);

    internalInvokePlan(new PlanInvocationArguments(csar, serviceTemplateID, serviceTemplateInstanceID, planID, correlationID), exchange);
}
 
Example 9
Source Project: syndesis   File: BoxDownloadCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
private void beforeProducer(Exchange exchange) {
    Message in = exchange.getIn();
    // retrieve the BoxFileDownload object mapping if exists
    BoxFileDownload boxFileInfo = in.getBody(BoxFileDownload.class);
    if (boxFileInfo != null && boxFileInfo.getFileId() != null) {
        fileId = boxFileInfo.getFileId();
    }
    if (fileId != null) {
        in.setHeader("CamelBox.fileId", fileId);
        in.setBody(new ByteArrayOutputStream());
    } else {
        LOG.error("There is a missing CamelBox.fileId parameter, you should set the File ID parameter in the Box Download step parameter or add a data mapping step to set it.");
    }
}
 
Example 10
private Exchange createExchange(Object event) throws JsonProcessingException
{
    Exchange exchange = createExchange();

    Message in = exchange.getIn();
    if (!(event instanceof String))
    {
        event = messagingObjectMapper.writeValueAsString(event);
    }

    in.setBody(event);

    return exchange;
}
 
Example 11
Source Project: syndesis   File: ODataCreateCustomizer.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeProducer(Exchange exchange) throws IOException {
    Message in = exchange.getIn();

    String resource = in.getBody(String.class);
    if (! ObjectHelper.isEmpty(resource)) {
        in.setHeader(OLINGO4_PROPERTY_PREFIX + DATA, resource);
    }
}
 
Example 12
private static void afterProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    final Spreadsheet spreadsheet = in.getBody(Spreadsheet.class);

    GoogleSpreadsheet model = new GoogleSpreadsheet();

    if (ObjectHelper.isNotEmpty(spreadsheet)) {
        model.setSpreadsheetId(spreadsheet.getSpreadsheetId());

        SpreadsheetProperties spreadsheetProperties = spreadsheet.getProperties();
        if (ObjectHelper.isNotEmpty(spreadsheetProperties)) {
            model.setTitle(spreadsheetProperties.getTitle());
            model.setUrl(spreadsheet.getSpreadsheetUrl());
            model.setTimeZone(spreadsheetProperties.getTimeZone());
            model.setLocale(spreadsheetProperties.getLocale());
        }

        List<GoogleSheet> sheets = new ArrayList<>();
        if (ObjectHelper.isNotEmpty(spreadsheet.getSheets())) {
            spreadsheet.getSheets().stream()
                    .map(Sheet::getProperties)
                    .forEach(props -> {
                        GoogleSheet sheet = new GoogleSheet();
                        sheet.setSheetId(props.getSheetId());
                        sheet.setIndex(props.getIndex());
                        sheet.setTitle(props.getTitle());
                        sheets.add(sheet);
                    });

        }
        model.setSheets(sheets);
    }

    in.setBody(model);
}
 
Example 13
Source Project: mdw   File: MdwProducer.java    License: Apache License 2.0 5 votes vote down vote up
public void process(Exchange exchange) throws Exception {
    Message request = exchange.getIn();
    request.setHeader("MdwCamelRequestType", endpoint.getRequestType().toString());

    Object response = null;

    try {
        switch (endpoint.getRequestType()) {
            case process:
                response = launchProcess(request);
                break;
            case notify:
                response = notify(request);
                break;
            default:
                break;
        }

    }
    catch (Throwable t) {
        logger.error(t.getMessage(), t);
        exchange.setException(t);
    }

    if (exchange.getPattern().isOutCapable())
        handleResponse(exchange, response);
}
 
Example 14
Source Project: servicemix   File: Utils.java    License: 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();

    final List<Command<?>> commands = new ArrayList<Command<?>>(2);
    commands.add(CommandFactory.newInsert(body));
    commands.add(CommandFactory.newFireAllRules());

    Command<?> batch = CommandFactory.newBatchExecution(commands);
    in.setBody(batch);
}
 
Example 15
public void beforeConsumer(Exchange exchange) throws IOException {
    final Message in = exchange.getIn();
    final SQSMessage message = new SQSMessage();

    if (ObjectHelper.isNotEmpty(in.getBody())) {
        message.setMessage(in.getBody(String.class));
    }
    exchange.getIn().setBody(message);
}
 
Example 16
@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 Project: syndesis   File: SetHeader.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
    final Message in = exchange.getIn();
    in.setHeader(headerName, headerValue);
}
 
Example 18
private void beforeProducer(Exchange exchange) {
    final Message in = exchange.getIn();
    in.setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + SPREADSHEET_ID, spreadsheetId);
    in.setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "range", range);
    in.setHeader(GoogleSheetsConstants.PROPERTY_PREFIX + "majorDimension", majorDimension);
}
 
Example 19
Source Project: container   File: OutgoingProcessor.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {

    LOG.debug("Processing outgoing message...");
    final Message message = exchange.getIn();

    // only outgoing messages with body type CollaborationMessage are valid
    if (message.getBody() instanceof CollaborationMessage) {

        final CollaborationMessage collaborationMessage = (CollaborationMessage) message.getBody();
        final KeyValueMap headerObject = collaborationMessage.getHeaderMap();
        final List<KeyValueType> headerList = headerObject.getKeyValuePair();

        // copy exchange headers into the CollaborationMessage to transmit them over MQTT
        for (final Entry<String, Object> header : message.getHeaders().entrySet()) {
            if (header.getKey() != null && header.getValue() != null) {

                // The header fields must be converted to Strings because they are marshaled to
                // XML. After the transmission the original type is created again if possible.
                String stringRepresentation = "";
                if (header.getValue() instanceof Document) {
                    final Document headerValue = (Document) header.getValue();
                    stringRepresentation = toXMLString(headerValue);
                } else {
                    stringRepresentation = header.getValue().toString();
                }

                LOG.debug("Adding header field with key {} and value {}", header.getKey(),
                    stringRepresentation);

                final KeyValueType keyValue = new KeyValueType(header.getKey(), stringRepresentation);
                headerList.add(keyValue);
            }
        }
        collaborationMessage.setHeaderMap(headerObject);

        // factory to create Jaxb objects
        final ObjectFactory factory = new ObjectFactory();

        // transform CollaborationMessage to jaxb object
        final JAXBElement<CollaborationMessage> jaxbCollaborationMessage =
            factory.createCollaborationMessage(collaborationMessage);

        message.setBody(jaxbCollaborationMessage);

        LOG.trace("Forwarding message in XML format: {}", toXMLString(jaxbCollaborationMessage));
    }
}
 
Example 20
private void beforeProducer(Exchange exchange) {

        final Message in = exchange.getIn();

        in.setHeader("CamelGoogleCalendar.eventId", eventId);
        in.setHeader("CamelGoogleCalendar.calendarId", calendarId);
    }