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

The following examples show how to use org.apache.camel.Message#setBody() . 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: SqlStartConnectorCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
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 2
Source File: ToArdulinkProtocol.java    From Ardulink-2 with Apache License 2.0 6 votes vote down vote up
@Override
public void process(Exchange exchange) {
	Message in = exchange.getIn();
	String topic = checkNotNull(topicFrom.evaluate(exchange, String.class),
			"topic must not be null");
	String body = checkNotNull(in.getBody(String.class),
			"body must not be null");
	Optional<String> message = createMessage(topic, body);

	if (message.isPresent()) {
		in.setBody(message.getOrThrow(
				"Cannot handle body %s with topic %s", body, topic),
				String.class);
	} else {
		exchange.setProperty(ROUTE_STOP, TRUE);
	}
}
 
Example 3
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 4
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void createCinderVolume() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    CinderEndpoint endpoint = Mockito.mock(CinderEndpoint.class);
    when(endpoint.getOperation()).thenReturn(OpenstackConstants.CREATE);
    msg.setBody(dummyVolume);

    Producer producer = new VolumeProducer(endpoint, client);
    producer.process(exchange);
    assertEqualVolumes(dummyVolume, msg.getBody(Volume.class));
}
 
Example 5
Source File: AbstractFaultSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) {
    final Exception exception = (Exception) exchange.getProperty(Exchange.EXCEPTION_CAUGHT);
    if (exception instanceof SoapFault) {

        SoapFault soapFault = (SoapFault) exception;
        final Message in = exchange.getIn();

        // get SOAP QNames from CxfPayload headers
        final SoapMessage soapMessage = in.getHeader("CamelCxfMessage", SoapMessage.class);
        final SoapVersion soapVersion = soapMessage.getVersion();

        try {

            // get CxfPayload body
            final CxfPayload<?> cxfPayload = in.getMandatoryBody(CxfPayload.class);

            final OutputStream outputStream = newOutputStream(in, cxfPayload);
            final XMLStreamWriter writer = newXmlStreamWriter(outputStream);

            handleFault(writer, soapFault, soapVersion);
            writer.writeEndDocument();

            final InputStream inputStream = getInputStream(outputStream, writer);

            // set the input stream as the Camel message body
            in.setBody(inputStream);

        } catch (InvalidPayloadException | XMLStreamException | IOException e) {
            throw new RuntimeCamelException("Error parsing CXF Payload: " + e.getMessage(), e);
        }
    }
}
 
Example 6
Source File: RestRouteBuilder.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private void switchAnalog(Exchange exchange) {
	Message message = exchange.getMessage();
	Object pinRaw = message.getHeader("pin");
	String valueRaw = message.getBody(String.class);
	int pin = tryParse(String.valueOf(pinRaw)).getOrThrow("Pin %s not parseable", pinRaw);
	int value = tryParse(valueRaw).getOrThrow("Value %s not parseable", valueRaw);
	message.setBody(alpProtocolMessage(ANALOG_PIN_READ).forPin(pin).withValue(value));
}
 
Example 7
Source File: ODataReadToCustomizer.java    From syndesis with Apache License 2.0 5 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));
    } else {
        //
        // Necessary to have a key predicate. Otherwise, read will try returning
        // all results which could very be painful for the running integration.
        //
        throw new RuntimeCamelException("Key Predicate value was empty");
    }

    in.setBody(EMPTY_STRING);
}
 
Example 8
Source File: ApacheCamelExample.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    // 因为很明确消息格式是http的,所以才使用这个类
    // 否则还是建议使用org.apache.camel.Message这个抽象接口
    HttpMessage message = (HttpMessage) exchange.getIn();
    InputStream bodyStream = (InputStream) message.getBody();
    String inputContext = this.analysisMessage(bodyStream);
    bodyStream.close();

    // 存入到 exchange的 out区域
    if (exchange.getPattern() == ExchangePattern.InOut) {
        Message outMessage = exchange.getOut();
        outMessage.setBody(inputContext + " || out");
    }
}
 
Example 9
Source File: DataShapeCustomizerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUnmarshallToSpecifiedInputType() throws Exception {
    final ComponentProxyComponent component = setUpComponent("salesforce-delete-sobject");
    final Exchange exchange = new DefaultExchange(context);
    final Message in = exchange.getIn();
    in.setBody("{}");

    component.getBeforeProducer().process(exchange);

    Assertions.assertThat(in.getBody()).isInstanceOf(SalesforceIdentifier.class);
}
 
Example 10
Source File: GoogleSheetsGetSpreadsheetCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static void beforeConsumer(Exchange exchange) {
    final Message in = exchange.getIn();
    final Spreadsheet spreadsheet = exchange.getIn().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 11
Source File: MongoCustomizersUtil.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * Used to convert any result MongoOperation (either {@link DeleteResult} or {@link UpdateResult}
 * to a {@link Long}
 */
static void convertMongoResultToLong(Exchange exchange) {
    Message in = exchange.getIn();
    if (in.getBody() instanceof DeleteResult) {
        Long docsDeleted = in.getBody(DeleteResult.class).getDeletedCount();
        in.setBody(docsDeleted);
    } else if (in.getBody() instanceof UpdateResult) {
        Long docsUpdated = in.getBody(UpdateResult.class).getModifiedCount();
        in.setBody(docsUpdated);
    } else {
        LOGGER.warn("Impossible to convert the body, type was {}", in.getBody() == null ? null : in.getBody().getClass());
    }
}
 
Example 12
Source File: RequestSoapPayloadConverter.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
protected void convertMessage(final Message in) {
    try {
        final Source body = bodyAsSource(in);

        // extract body as stream, and headers as elements in single DOM
        final XMLEventReader bodyReader = XML_INPUT_FACTORY.createXMLEventReader(body);
        final SoapPayloadReaderFilter payloadFilter = new SoapPayloadReaderFilter(soapVersion);
        final XMLEventReader eventReader = XML_INPUT_FACTORY.createFilteredReader(bodyReader, payloadFilter);

        // all the work is done in the filter, so we ignore the event writer output
        try (OutputStream bos = new ByteArrayOutputStream()) {
            XMLEventWriter target = XML_OUTPUT_FACTORY.createXMLEventWriter(bos);
            target.add(eventReader);
        }

        // convert filtered parts to CxfPayload
        final CxfPayload<Source> cxfPayload = payloadFilter.getCxfPayload();

        // add existing SOAP headers
        final List<?> existingHeaders = (List<?>) in.getHeader(Header.HEADER_LIST);
        if (existingHeaders != null) {
            final List<Source> headers = cxfPayload.getHeaders();
            for (Object header : existingHeaders) {
                if (header instanceof Source) {
                    headers.add((Source) header);
                } else {
                    // wrap dom node
                    headers.add(new DOMSource((Node)header));
                }
            }
        }

        in.setBody(cxfPayload);

    } catch (XMLStreamException | InvalidPayloadException | IOException e) {
        throw new RuntimeCamelException("Error creating SOAP message from request message: " + e.getMessage(), e);
    }
}
 
Example 13
Source File: RestRouteBuilder.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private void patch(Exchange exchange, ALPProtocolKey startKey, ALPProtocolKey stopKey) {
	Message message = exchange.getMessage();
	Object pinRaw = message.getHeader("pin");
	String stateRaw = message.getBody(String.class);

	String[] split = stateRaw.split("=");
	checkState(split.length == 2, "Could not split %s by =", stateRaw);
	checkState(split[0].equalsIgnoreCase("listen"), "Expected listen=${state} but was %s", stateRaw);

	int pin = tryParse(String.valueOf(pinRaw)).getOrThrow("Pin %s not parseable", pinRaw);
	boolean state = parseBoolean(split[1]);
	message.setBody(alpProtocolMessage(state ? startKey : stopKey).forPin(pin).withoutValue());
}
 
Example 14
Source File: BoxDownloadCustomizer.java    From syndesis with 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 15
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 16
Source File: HttpRequestUnwrapperProcessor.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void process(final Exchange exchange) throws Exception {
    final Message message = exchange.getIn();
    final Object body = message.getBody();

    final JsonNode data = parseBody(body);

    if (data == null) {
        return;
    }

    final JsonNode paramMap = data.get("parameters");
    final JsonNode bodyData = data.get("body");

    if (paramMap != null || bodyData != null) {
        if (paramMap != null) {
            for (final String key : parameters) {
                final JsonNode valueNode = paramMap.get(key);
                if (valueNode != null) {
                    final String val = valueNode.asText();
                    message.setHeader(key, val);
                }
            }
        }

        if (bodyData == null) {
            message.setBody(null);
            return;
        }

        if (bodyData.isContainerNode()) {
            message.setBody(JsonUtils.toString(bodyData));
            return;
        }

        message.setHeader(Exchange.CONTENT_TYPE, "text/plain");
        message.setBody(bodyData.asText());
    }
}
 
Example 17
Source File: CheeseCloningProcessor.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void process(Exchange exchange) throws Exception {
    Message in = exchange.getIn();
    Cheese cheese = in.getBody(Cheese.class);
    if (cheese != null) {
        in.setBody(cheese.clone());
    }
}
 
Example 18
Source File: DataShapeCustomizerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldUnmarshallToSpecifiedOutputType() throws Exception {
    final ComponentProxyComponent component = setUpComponent("salesforce-create-sobject");
    final Exchange exchange = new DefaultExchange(context);
    final Message out = exchange.getIn();
    out.setBody("{}");

    component.getAfterProducer().process(exchange);

    Assertions.assertThat(out.getBody()).isInstanceOf(AbstractDTOBase.class);
}
 
Example 19
Source File: GoogleBigQueryIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
private Exchange createExchangeWithBody(CamelContext camelContext, Object body) {
    Exchange exchange = new DefaultExchange(camelContext);
    Message message = exchange.getIn();
    message.setBody(body);
    return exchange;
}
 
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());
        }

    }