org.apache.camel.converter.jaxb.JaxbDataFormat Java Examples

The following examples show how to use org.apache.camel.converter.jaxb.JaxbDataFormat. 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: JaxbRoute.java    From camel-quarkus with Apache License 2.0 7 votes vote down vote up
@Override
public void configure() throws Exception {
    JaxbDataFormat jaxb = new JaxbDataFormat("org.apache.camel.quarkus.component.jaxb.it.model");

    JaxbDataFormat xml = new JaxbDataFormat();
    JAXBContext context = JAXBContext.newInstance(Person.class);
    xml.setContext(context);

    JaxbDataFormat jaxbFromScheme = new JaxbDataFormat();
    jaxbFromScheme.setSchema("classpath:person.xsd");

    from("direct:unmarshal")
            .unmarshal(jaxb);

    from("direct:unmarshal-2")
            .unmarshal(xml);

    from("direct:marshal")
            .marshal(jaxbFromScheme);

    from("direct:marshal-2")
            .marshal(xml);

}
 
Example #2
Source File: InventoryRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    JaxbDataFormat jaxb = new JaxbDataFormat();
    jaxb.setContextPath("camelinaction");

    from("direct:inventory")
        .log("Calling inventory service using JMS")
        .hystrix()
            // call the legacy system using JMS (via activemq)
            .to("activemq:queue:inventory")
            // the returned data is in XML format so convert that to POJO using JAXB
            .unmarshal(jaxb)
        .onFallback()
            .log("Circuit breaker failed so using fallback response")
            // fallback and read inventory from classpath which is in XML format
            .transform().constant("resource:classpath:fallback-inventory.xml");
}
 
Example #3
Source File: InventoryRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    JaxbDataFormat jaxb = new JaxbDataFormat();
    jaxb.setContextPath("camelinaction");

    from("direct:inventory")
        .log("Calling inventory service using JMS")
        .hystrix()
            // call the legacy system using JMS (via activemq)
            .to("activemq:queue:inventory")
            // the returned data is in XML format so convert that to POJO using JAXB
            .unmarshal(jaxb)
        .onFallback()
            .log("Circuit breaker failed so using fallback response")
            // fallback and read inventory from classpath which is in XML format
            .transform().constant("resource:classpath:fallback-inventory.xml");
}
 
Example #4
Source File: InventoryRoute.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    JaxbDataFormat jaxb = new JaxbDataFormat();
    jaxb.setContextPath("camelinaction");

    from("direct:inventory")
        .log("Calling inventory service using JMS")
        .hystrix()
            // call the legacy system using JMS
            .to("jms:queue:inventory")
            // the returned data is in XML format so convert that to POJO using JAXB
            .unmarshal(jaxb)
        .onFallback()
            // fallback and read inventory from classpath which is in XML format
            .transform().constant("resource:classpath:fallback-inventory.xml");
}
 
Example #5
Source File: SendRequestResponseRoute.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {

    // MQTT endpoint where this route publishes messages
    final String producerEndpoint = "mqtt:send?host=${header." + MBHeader.MQTTBROKERHOSTNAME_STRING.toString()
        + "}&userName=" + this.username + "&password=" + this.password + "&publishTopicName=${header."
        + MBHeader.MQTTTOPIC_STRING.toString() + "}&qualityOfService=ExactlyOnce";

    // print broker host name and topic for incoming messages
    final String loggerMessage =
        "Sending Exchange to MQTT topic. Host: ${header." + MBHeader.MQTTBROKERHOSTNAME_STRING.toString()
            + "} Topic: ${header." + MBHeader.MQTTTOPIC_STRING.toString() + "}";

    // print broker host name and topic for incoming messages
    final String exception = "Unable to marshal given object. Exchange will not be send!";

    // JAXB definitions to marshal the outgoing message body
    final ClassLoader classLoader =
        ObjectFactory.class.getClassLoader();
    final JAXBContext jc =
        JAXBContext.newInstance("org.opentosca.bus.management.service.impl.collaboration.model", classLoader);
    final JaxbDataFormat jaxb = new JaxbDataFormat(jc);

    // extracts exchange headers and adds them to the marshaled object
    final Processor outgoingProcessor = new OutgoingProcessor();

    // @formatter:off
    this.from("direct:SendMQTT")
        .log(LoggingLevel.DEBUG, LoggerFactory.getLogger(SendRequestResponseRoute.class), loggerMessage)
        .process(outgoingProcessor)
        .doTry()
        .marshal(jaxb)
        .recipientList(this.simple(producerEndpoint))
        .endDoTry()
        .doCatch(Exception.class)
        .log(LoggingLevel.ERROR, LoggerFactory.getLogger(SendRequestResponseRoute.class), exception)
        .end();
}
 
Example #6
Source File: Route.java    From container with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {

    final URL wsdlURL = this.getClass().getClassLoader().getResource("wsdl/SoapAPI.wsdl");

    // CXF Endpoint
    final String SOAP_ENDPOINT = "cxf:" + ENDPOINT + "?wsdlURL=" + wsdlURL.toString()
        + "&serviceName={http://opentosca.org/appinvoker/}AppInvokerSoapWebServiceService&portName="
        + PORT.toString() + "&dataFormat=PAYLOAD&loggingFeatureEnabled=true";

    final ValueBuilder APP_BUS_ENDPOINT =
        new ValueBuilder(method(ApplicationBusServiceHandler.class, "getApplicationBusRoutingEndpoint"));
    final Predicate APP_BUS_ENDPOINT_EXISTS = PredicateBuilder.isNotNull(APP_BUS_ENDPOINT);

    final ClassLoader cl = org.opentosca.bus.application.api.soaphttp.model.ObjectFactory.class.getClassLoader();
    final JAXBContext jc = JAXBContext.newInstance("org.opentosca.bus.application.api.soaphttp.model", cl);
    final JaxbDataFormat jaxb = new JaxbDataFormat(jc);

    final Processor requestProcessor = new RequestProcessor();
    final Processor responseProcessor = new ResponseProcessor();

    from(SOAP_ENDPOINT).unmarshal(jaxb).process(requestProcessor).choice().when(APP_BUS_ENDPOINT_EXISTS)
        //FIXME this recipientList should be replaced with a directly injected service reference
        .recipientList(APP_BUS_ENDPOINT).to("direct:handleResponse").endChoice().otherwise()
        .to("direct:handleException");

    // handle exception if Application Bus is not running or wasn't bound
    from("direct:handleException")
        .throwException(new ApplicationBusInternalException("It seems like the Application Bus is not running."))
        .to("direct:handleResponse");

    // handle response
    from("direct:handleResponse").process(responseProcessor).marshal(jaxb);
}
 
Example #7
Source File: NormalizerRoute.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    final DataFormat bindy = new BindyCsvDataFormat(org.camelcookbook.transformation.csv.model.BookModel.class);
    final DataFormat jaxb = new JaxbDataFormat("org.camelcookbook.transformation.myschema");

    final XmlJsonDataFormat xmlJsonFormat = new XmlJsonDataFormat();
    xmlJsonFormat.setRootName("bookstore");
    xmlJsonFormat.setElementName("book");
    xmlJsonFormat.setExpandableProperties(Arrays.asList("author", "author"));

    from("direct:start")
        .choice()
        .when(header(Exchange.FILE_NAME).endsWith(".csv"))
            .unmarshal(bindy)
            .bean(MyNormalizer.class, "bookModelToJaxb")
            .to("mock:csv")
        .when(header(Exchange.FILE_NAME).endsWith(".json"))
            .unmarshal(xmlJsonFormat)
            .to("mock:json")
        .when(header(Exchange.FILE_NAME).endsWith(".xml"))
            .unmarshal(jaxb)
            .to("mock:xml")
        .otherwise()
            .to("mock:unknown")
            .stop()
        .end()
        .to("mock:normalized");
}
 
Example #8
Source File: JaxbRoute.java    From camel-cookbook-examples with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    DataFormat myJaxb = new JaxbDataFormat("org.camelcookbook.transformation.myschema");

    from("direct:marshal")
        .marshal(myJaxb)
        .to("mock:marshalResult");

    from("direct:unmarshal")
        .unmarshal(myJaxb)
        .to("mock:unmarshalResult");
}
 
Example #9
Source File: RestSwaggerIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestSwaggerXML() throws Exception {
    JAXBContext jaxbContext = JAXBContext.newInstance(Customer.class);
    JaxbDataFormat jaxb = new JaxbDataFormat(jaxbContext);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:getCustomerById")
            .to("customer:getCustomerById")
            .unmarshal(jaxb);
        }
    });

    RestSwaggerComponent restSwaggerComponent = new RestSwaggerComponent();
    restSwaggerComponent.setSpecificationUri(new URI("http://localhost:8080/api/swagger"));
    restSwaggerComponent.setComponentName("undertow");
    restSwaggerComponent.setConsumes(MediaType.APPLICATION_XML);
    restSwaggerComponent.setProduces(MediaType.APPLICATION_XML);

    camelctx.addComponent("customer", restSwaggerComponent);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        Customer customer = template.requestBodyAndHeader("direct:getCustomerById", null, "id", 1, Customer.class);
        Assert.assertNotNull(customer);
        Assert.assertEquals(1, customer.getId());
    } finally {
        camelctx.close();
    }
}
 
Example #10
Source File: JaxbDataFormatAutoConfiguration.java    From camel-spring-boot with Apache License 2.0 4 votes vote down vote up
@Bean(name = "jaxb-dataformat-factory")
@ConditionalOnMissingBean(JaxbDataFormat.class)
public DataFormatFactory configureJaxbDataFormatFactory() throws Exception {
    return new DataFormatFactory() {
        @Override
        public DataFormat newInstance() {
            JaxbDataFormat dataformat = new JaxbDataFormat();
            if (CamelContextAware.class
                    .isAssignableFrom(JaxbDataFormat.class)) {
                CamelContextAware contextAware = CamelContextAware.class
                        .cast(dataformat);
                if (contextAware != null) {
                    contextAware.setCamelContext(camelContext);
                }
            }
            try {
                Map<String, Object> parameters = new HashMap<>();
                IntrospectionSupport.getProperties(configuration,
                        parameters, null, false);
                CamelPropertiesHelper.setCamelProperties(camelContext,
                        dataformat, parameters, false);
            } catch (Exception e) {
                throw new RuntimeCamelException(e);
            }
            if (ObjectHelper.isNotEmpty(customizers)) {
                for (DataFormatCustomizer<JaxbDataFormat> customizer : customizers) {
                    boolean useCustomizer = (customizer instanceof HasId)
                            ? HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.jaxb.customizer",
                                    ((HasId) customizer).getId())
                            : HierarchicalPropertiesEvaluator.evaluate(
                                    applicationContext.getEnvironment(),
                                    "camel.dataformat.customizer",
                                    "camel.dataformat.jaxb.customizer");
                    if (useCustomizer) {
                        LOGGER.debug(
                                "Configure dataformat {}, with customizer {}",
                                dataformat, customizer);
                        customizer.customize(dataformat);
                    }
                }
            }
            return dataformat;
        }
    };
}
 
Example #11
Source File: Route.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() throws Exception {
    final URL wsdlURL = this.getClass().getClassLoader().getResource("wsdl/invoker.wsdl");

    // CXF Endpoints
    final String INVOKE_ENDPOINT = "cxf:" + ENDPOINT + "?wsdlURL=" + wsdlURL.toString()
        + "&serviceName={http://siserver.org/wsdl}InvokerService&portName=" + Route.PORT.toString()
        + "&dataFormat=PAYLOAD&loggingFeatureEnabled=true";
    final String CALLBACK_ENDPOINT = "cxf:${header[ReplyTo]}?wsdlURL=" + wsdlURL.toString()
        + "&headerFilterStrategy=#dropAllMessageHeadersStrategy"
        + "&serviceName={http://siserver.org/wsdl}CallbackService&portName={http://siserver.org/wsdl}CallbackPort"
        + "&dataFormat=PAYLOAD&loggingFeatureEnabled=true";

    // Checks if invoke is sync or async
    final Predicate MESSAGEID = header("MessageID").isNotNull();
    final Predicate REPLYTO = header("ReplyTo").isNotNull();
    final Predicate ASYNC = PredicateBuilder.and(MESSAGEID, REPLYTO);

    final ClassLoader cl = org.opentosca.bus.management.api.soaphttp.model.ObjectFactory.class.getClassLoader();
    final JAXBContext jc = JAXBContext.newInstance("org.opentosca.bus.management.api.soaphttp.model", cl);
    final JaxbDataFormat requestJaxb = new JaxbDataFormat(jc);
    final JaxbDataFormat responseJaxb = new JaxbDataFormat(jc);
    responseJaxb.setPartClass("org.opentosca.bus.management.api.soaphttp.model.InvokeResponse");
    responseJaxb.setPartNamespace(new QName("http://siserver.org/schema", "invokeResponse"));

    final Processor requestProcessor = new RequestProcessor(csarStorageService, containerEngine);
    final Processor responseProcessor = new ResponseProcessor();

    this.from(INVOKE_ENDPOINT)
        .unmarshal(requestJaxb)
        .process(requestProcessor)
        .choice().when(IS_INVOKE_IA)
        .bean(managementBusService, "invokeIA")
        .when(IS_INVOKE_PLAN)
        .bean(managementBusService, "invokePlan")
        .end();

    this.from("direct-vm:" + RequestProcessor.MB_MANAGEMENT_SOAPHTTP_API_ID).process(responseProcessor).marshal(responseJaxb).choice().when(ASYNC)
        .recipientList(this.simple(CALLBACK_ENDPOINT)).end();
}
 
Example #12
Source File: ReceiveResponseRoute.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() throws Exception {

    // header field which is used as routing criteria
    final String correlationHeader = MBHeader.CORRELATIONID_STRING.toString();

    // MQTT endpoint where this route waits for messages
    final String consumerEndpoint = "mqtt:response?host=" + this.host + "&userName=" + this.username + "&password="
        + this.password + "&subscribeTopicNames=" + this.topic + "&qualityOfService=ExactlyOnce";

    final String producerEndpoint = "direct:Callback-${header." + correlationHeader + "}";

    // JAXB definitions to unmarshal the incoming message body
    final ClassLoader classLoader =
        ObjectFactory.class.getClassLoader();
    final JAXBContext jc =
        JAXBContext.newInstance("org.opentosca.bus.management.service.impl.collaboration.model", classLoader);
    final JaxbDataFormat jaxb = new JaxbDataFormat(jc);

    // extracts headers from the marshaled object and adds them to the exchange
    final Processor headerProcessor = new IncomingProcessor();

    // log messages to increase the readability of the route
    final String messageReceived = "Received response message via MQTT topic. Unmarshaling...";
    final String correlationID = "Message has correlation ID: ${header." + correlationHeader + "}";
    final String correlationNotNull = "Message will be routed to corresponding callback!";
    final String noDirectException = "No direct receiver for this correlation ID registered."
        + "This could be due to a delayed message where the corresponding receiver has already timed out or if multiple receiver answer a request.";
    final String noCorrelation = "Correlation ID is null. Ignoring message!";
    final String noMarshalling = "Unable to unmarshal message. Ignoring it!";

    // @formatter:off
    this.from(consumerEndpoint)
        .log(LoggingLevel.DEBUG, LOG, messageReceived)
        .doTry()
        .unmarshal(jaxb)
        .process(headerProcessor)
        .log(LoggingLevel.DEBUG, LOG, correlationID)
        .choice()
        .when(header(correlationHeader).isNotNull())
        .log(LoggingLevel.DEBUG, LOG, correlationNotNull)
        .recipientList(this.simple(producerEndpoint))
        .endChoice()
        .otherwise()
        .log(LoggingLevel.WARN, LOG, noCorrelation)
        .endChoice()
        .endDoTry()
        .doCatch(DirectConsumerNotAvailableException.class)
        .log(LoggingLevel.ERROR, LOG, noDirectException)
        .doCatch(Exception.class)
        .log(LoggingLevel.ERROR, LOG, noMarshalling)
        .end();
}
 
Example #13
Source File: ReceiveRequestRoute.java    From container with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() throws Exception {

    // MQTT endpoint where this route waits for messages
    final String consumerEndpoint = "mqtt:request?host=" + this.host + "&userName=" + this.username + "&password="
        + this.password + "&subscribeTopicNames=" + this.topic + "&qualityOfService=ExactlyOnce";

    // endpoints to invoke the methods corresponding to requests
    final String instanceMatchingEndpoint =
        "bean:org.opentosca.bus.management.service.impl.collaboration.RequestReceiver?method=invokeInstanceDataMatching";
    final String deploymentEndpoint =
        "bean:org.opentosca.bus.management.service.impl.collaboration.RequestReceiver?method=invokeIADeployment";
    final String undeploymentEndpoint =
        "bean:org.opentosca.bus.management.service.impl.collaboration.RequestReceiver?method=invokeIAUndeployment";
    final String invocationEndpoint =
        "bean:org.opentosca.bus.management.service.impl.collaboration.RequestReceiver?method=invokeIAOperation";

    // JAXB definitions to unmarshal the incoming message body
    final ClassLoader classLoader =
        ObjectFactory.class.getClassLoader();
    final JAXBContext jc =
        JAXBContext.newInstance("org.opentosca.bus.management.service.impl.collaboration.model", classLoader);
    final JaxbDataFormat jaxb = new JaxbDataFormat(jc);

    // extracts headers from the marshaled object and adds them to the exchange
    final Processor headerProcessor = new IncomingProcessor();

    // header field which is used as routing criteria
    final String remoteOperationHeader = MBHeader.REMOTEOPERATION_STRING.toString();

    // log messages to increase the readability of the route
    final String messageReceived = "Received request message via MQTT topic. Unmarshaling...";
    final String operation = "Message has remote operation header: ${header." + remoteOperationHeader + "}";
    final String noMarshalling = "Unable to unmarshal message. Ignoring it!";
    final String invalidOperation = "Remote operation header is either null or contains an invalid operation!";
    final String invokeInstanceDataMatching = "Invoking instance data matching on local OpenTOSCA Container";
    final String invokeIADeployment = "Invoking IA deployment on local OpenTOSCA Container";
    final String invokeIAUndeployment = "Invoking IA undeployment on local OpenTOSCA Container";
    final String invokeIAOperation = "Invoking IA operation on local OpenTOSCA Container";

    // @formatter:off
    this.from(consumerEndpoint)
        .threads(2, 5)
        .log(LoggingLevel.DEBUG, LOG, messageReceived)
        .doTry()
        .unmarshal(jaxb)
        .process(headerProcessor)
        .log(LoggingLevel.DEBUG, LOG, operation)
        .choice()
        .when(header(remoteOperationHeader).isEqualTo(RemoteOperations.INVOKE_INSTANCE_DATA_MATCHING))
        .log(LoggingLevel.DEBUG, LOG, invokeInstanceDataMatching)
        .to(instanceMatchingEndpoint)
        .endChoice()
        .when(header(remoteOperationHeader).isEqualTo(RemoteOperations.INVOKE_IA_DEPLOYMENT))
        .log(LoggingLevel.DEBUG, LOG, invokeIADeployment)
        .to(deploymentEndpoint)
        .endChoice()
        .when(header(remoteOperationHeader).isEqualTo(RemoteOperations.INVOKE_IA_UNDEPLOYMENT))
        .log(LoggingLevel.DEBUG, LOG, invokeIAUndeployment)
        .to(undeploymentEndpoint)
        .endChoice()
        .when(header(remoteOperationHeader).isEqualTo(RemoteOperations.INVOKE_IA_OPERATION))
        .log(LoggingLevel.DEBUG, LOG, invokeIAOperation)
        .to(invocationEndpoint)
        .endChoice()
        .otherwise()
        .log(LoggingLevel.WARN, LOG, invalidOperation)
        .endChoice()
        .endDoTry()
        .doCatch(Exception.class)
        .log(LoggingLevel.ERROR, LOG, noMarshalling)
        .end();
}