Java Code Examples for org.apache.camel.ProducerTemplate#requestBody()

The following examples show how to use org.apache.camel.ProducerTemplate#requestBody() . 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: BeanValidatorIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testBeanValidationSuccess() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("bean-validator://validate");
        }
    });

    camelctx.start();

    try {
        CarWithAnnotations car = new CarWithAnnotations("BMW", "DD-AB-123");

        ProducerTemplate template = camelctx.createProducerTemplate();
        CarWithAnnotations result = template.requestBody("direct:start", car, CarWithAnnotations.class);

        Assert.assertSame(car, result);
    } finally {
        camelctx.close();
    }
}
 
Example 2
Source File: CamelCxfWsServlet.java    From wildfly-camel-examples with Apache License 2.0 6 votes vote down vote up
@Override
protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException {
    /**
     * Get message and name parameters sent on the POST request
     */
    String message = request.getParameter("message");
    String name = request.getParameter("name");

    /**
     * Create a ProducerTemplate to invoke the direct:start endpoint, which will
     * result in the greeting web service 'greet' method being invoked.
     *
     * The web service parameters are sent to camel as an object array which is
     * set as the request message body.
     *
     * The web service result string is returned back for display on the UI.
     */
    ProducerTemplate producer = camelContext.createProducerTemplate();
    Object[] serviceParams = new Object[] { message, name };
    String result = producer.requestBody("direct:start", serviceParams, String.class);

    request.setAttribute("greeting", result);
    request.getRequestDispatcher("/greeting.jsp").forward(request, response);
}
 
Example 3
Source File: LzfDataFormatTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testUnmarshal() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:unmarshalTextToLzf")
            .marshal().lzf()
            .unmarshal().lzf();
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:unmarshalTextToLzf", TEXT.getBytes("UTF-8"), String.class);
        Assert.assertEquals(TEXT, result);
    } finally {
        camelctx.close();
    }
}
 
Example 4
Source File: GoogleMailIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
private static Message createMessage(ProducerTemplate template, String subject)
        throws MessagingException, IOException {

    Profile profile = template.requestBody("google-mail://users/getProfile?inBody=userId", CURRENT_USERID,
            Profile.class);
    Session session = Session.getDefaultInstance(new Properties(), null);
    MimeMessage mm = new MimeMessage(session);
    mm.addRecipients(javax.mail.Message.RecipientType.TO, profile.getEmailAddress());
    mm.setSubject(subject);
    mm.setContent("Camel rocks!\n" //
            + DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(ZonedDateTime.now()) + "\n" //
            + "user: " + System.getProperty("user.name"), "text/plain");

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    mm.writeTo(baos);
    String encodedEmail = Base64.getUrlEncoder().encodeToString(baos.toByteArray());
    Message message = new Message();
    message.setRaw(encodedEmail);
    return message;
}
 
Example 5
Source File: JSONDataFormatTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMarshalGson() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .marshal().json(JsonLibrary.Gson);
        }
    });

    String expected = "{'firstName':'John','lastName':'Doe'}";

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:start", new Customer("John", "Doe"), String.class);
        Assert.assertEquals(expected.replace('\'', '"'), result);
    } finally {
        camelctx.close();
    }
}
 
Example 6
Source File: DigitalOceanIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testCreateMultipleDroplets() throws Exception {
    CamelContext camelctx = createCamelContext(oauthToken);
    camelctx.addRoutes(createRouteBuilder());

    camelctx.start();
    try {
        MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mockResult.expectedMinimumMessageCount(1);

        ProducerTemplate producer = camelctx.createProducerTemplate();
        List<Droplet> createDroplets = producer.requestBody("direct:createMultipleDroplets", null, List.class);

        mockResult.assertIsSatisfied();
        Assert.assertEquals(2, createDroplets.size());
        List<Droplet> getDroplets = producer.requestBody("direct:getDroplets", null, List.class);
        Assert.assertTrue("At least as many droplets as created", getDroplets.size() >= 2);

    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: XChangeMetadataIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCurrencyPairMetaData() throws Exception {

    try (CamelContext camelctx = new DefaultCamelContext()) {

        Assume.assumeTrue(checkAPIConnection());

        camelctx.addRoutes(createRouteBuilder());
        camelctx.start();

        ProducerTemplate template = camelctx.createProducerTemplate();
        CurrencyPairMetaData metadata = template.requestBody("direct:currencyPairMetaData", CurrencyPair.EOS_ETH, CurrencyPairMetaData.class);
        Assert.assertNotNull("CurrencyPairMetaData not null", metadata);

        metadata = template.requestBodyAndHeader("direct:currencyPairMetaData", null, HEADER_CURRENCY_PAIR, CurrencyPair.EOS_ETH, CurrencyPairMetaData.class);
        Assert.assertNotNull("CurrencyPairMetaData not null", metadata);
    }
}
 
Example 8
Source File: GitHubIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testGitHubComponent() throws Exception {
    String oauthKey = System.getenv("CAMEL_GITHUB_OAUTH_KEY");
    Assume.assumeNotNull("CAMEL_GITHUB_OAUTH_KEY not null", oauthKey);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .toF("github:GETCOMMITFILE?oauthToken=%s&repoOwner=%s&repoName=%s", oauthKey, GITHUB_REPO_OWNER, GITHUB_REPO_NAME);
        }
    });

    camelctx.start();
    try {
        CommitFile commitFile = new CommitFile();
        commitFile.setSha("29222e8ccbb39c3570aa1cd29388e737a930a88d");

        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBody("direct:start", commitFile, String.class);
        Assert.assertEquals("Hello Kermit", result.trim());
    } finally {
        camelctx.close();
    }
}
 
Example 9
Source File: JDBCIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJDBCEndpoint() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("jdbc:java:jboss/datasources/ExampleDS");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        List<HashMap<String, Object>> rows = template.requestBody("direct:start", "select name from information_schema.users", List.class);

        Assert.assertTrue("Expected at least one row returned from query", rows.size() > 0);

        String result = rows.get(0).get("NAME").toString();

        Assert.assertEquals("SA", result);
    } finally {
        camelctx.close();
    }
}
 
Example 10
Source File: CDIEarCamelContextImportResourceTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testCamelCdiEarImportResource() throws Exception {
    CamelContext camelctxA = contextRegistry.getCamelContext("import-resource-context-a");
    Assert.assertNotNull("Expected import-resource-context-a to not be null", camelctxA);

    CamelContext camelctxB = contextRegistry.getCamelContext("import-resource-context-b");
    Assert.assertNotNull("Expected import-resource-context-b to not be null", camelctxB);

    String moduleNameA = TestUtils.getClassLoaderModuleName(camelctxA.getApplicationContextClassLoader());
    Assert.assertEquals("deployment.import-resource.ear.import-resource-a.war", moduleNameA);

    String moduleNameB = TestUtils.getClassLoaderModuleName(camelctxB.getApplicationContextClassLoader());
    Assert.assertEquals("deployment.import-resource.ear.import-resource-b.war", moduleNameB);

    ProducerTemplate template = camelctxA.createProducerTemplate();
    String result = template.requestBody("direct:start", null, String.class);
    Assert.assertEquals("Hello from import-resource-context-a", result);

    template = camelctxB.createProducerTemplate();
    result = template.requestBody("direct:start", null, String.class);
    Assert.assertEquals("Hello from import-resource-context-b", result);
}
 
Example 11
Source File: IPFSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void ipfsGetSingle() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("ipfs:get?outdir=target");
        }
    });

    camelctx.start();
    try {
        assumeIPFSAvailable(camelctx);

        ProducerTemplate producer = camelctx.createProducerTemplate();
        Path res = producer.requestBody("direct:start", SINGLE_HASH, Path.class);
        Assert.assertEquals(Paths.get("target", SINGLE_HASH), res);
        verifyFileContent(new FileInputStream(res.toFile()));
    } finally {
        camelctx.close();
    }
}
 
Example 12
Source File: DigitalOceanIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void getSizes() throws Exception {
    CamelContext camelctx = createCamelContext(oauthToken);
    camelctx.addRoutes(createRouteBuilder());

    camelctx.start();
    try {
        MockEndpoint mockResult = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mockResult.expectedMinimumMessageCount(1);

        ProducerTemplate producer = camelctx.createProducerTemplate();
        List<Size> sizes = producer.requestBody("direct:getSizes", null, List.class);
        Assert.assertNotEquals(1, sizes.size());
        mockResult.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 13
Source File: XChangeMarketIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testTicker() throws Exception {

    try (CamelContext camelctx = new DefaultCamelContext()) {

        Assume.assumeTrue(checkAPIConnection());

        camelctx.addRoutes(createRouteBuilder());
        camelctx.start();

        ProducerTemplate template = camelctx.createProducerTemplate();
        Ticker ticker = template.requestBody("direct:ticker", CurrencyPair.EOS_ETH, Ticker.class);
        Assert.assertNotNull("Ticker not null", ticker);
        System.out.println(ticker);

        ticker = template.requestBodyAndHeader("direct:ticker", null, HEADER_CURRENCY_PAIR, CurrencyPair.EOS_ETH, Ticker.class);
        Assert.assertNotNull("Ticker not null", ticker);
        System.out.println(ticker);
    }
}
 
Example 14
Source File: IPFSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void ipfsCat() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("ipfs:cat");
        }
    });

    camelctx.start();
    try {
        assumeIPFSAvailable(camelctx);

        ProducerTemplate producer = camelctx.createProducerTemplate();
        InputStream res = producer.requestBody("direct:start", SINGLE_HASH, InputStream.class);
        verifyFileContent(res);
    } finally {
        camelctx.close();
    }
}
 
Example 15
Source File: ThreadingIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCustomThreadPoolFactory() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.getExecutorServiceManager().setThreadPoolFactory(wildFlyCamelThreadPoolFactory);

    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .log("Starting to process big file: ${header.CamelFileName}")
                .split(body().tokenize("\n")).streaming().parallelProcessing()
                .bean(InventoryService.class, "csvToObject")
                .to("direct:update")
                .end()
                .log("Done processing big file: ${header.CamelFileName}");

            from("direct:update")
                .bean(InventoryService.class, "updateInventory")
                .to("mock:end");
        }
    });
    camelctx.start();
    try {
        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:end", MockEndpoint.class);
        mockEndpoint.expectedMessageCount(100);

        ProducerTemplate producerTemplate = camelctx.createProducerTemplate();
        producerTemplate.requestBody("direct:start", getClass().getResource("/bigfile.csv"));

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 16
Source File: OrderServiceTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateAndGetOrder() throws Exception {
    ProducerTemplate template = context.createProducerTemplate();

    Order order = new Order();
    order.setAmount(1);
    order.setPartName("motor");
    order.setCustomerName("honda");

    // convert to XML which we support
    String xml = context.getTypeConverter().convertTo(String.class, order);

    LOG.info("Sending order using xml payload: {}", xml);

    // use http component to send the order
    String id = template.requestBody("http://localhost:8080/orders?" + auth, xml, String.class);
    assertNotNull(id);

    LOG.info("Created new order with id " + id);

    // should create a new order with id 4 (as 3 was created in the previous test method)
    assertEquals("4", id);

    // use restlet component to get the order
    String response = template.requestBody("http://localhost:8080/orders/" + id + "?" + auth, null, String.class);
    LOG.info("Response: {}", response);
}
 
Example 17
Source File: SpringLogIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCamelSpringLogging() throws Exception {
    CamelContext camelctx = contextRegistry.getCamelContext("spring-logging-context-a");
    Assert.assertNotNull("spring-logging-context-a is null", camelctx);

    ProducerTemplate producer = camelctx.createProducerTemplate();
    producer.requestBody("direct:log-endpoint", LOG_MESSAGE);
    assertLogFileContainsContent(LOG_ENDPOINT_REGEX);

    producer.requestBody("direct:log-dsl", LOG_MESSAGE);
    assertLogFileContainsContent(LOG_DSL_REGEX);
}
 
Example 18
Source File: SNMPIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSnmpEndpoint() throws Exception {
    int port = AvailablePortFinder.getNextAvailable();

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF("snmp://localhost:%d?protocol=tcp&type=TRAP", port)
            .to("mock:result");
        }
    });

    camelctx.start();
    try {
        String uri = String.format("snmp://localhost:%d?oids=%s&protocol=tcp", port, SNMP_OIDS);

        ProducerTemplate template = camelctx.createProducerTemplate();
        SnmpMessage message = template.requestBody(uri, null, SnmpMessage.class);
        PDU snmpMessage = message.getSnmpMessage();

        Assert.assertNotNull(snmpMessage);
        Assert.assertEquals(0, snmpMessage.getErrorStatus());
    } finally {
        camelctx.close();
    }
}
 
Example 19
Source File: SOAPServiceInterfaceStrategyIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSOAPServiceInterfaceStrategyMarshal() throws Exception {
    ServiceInterfaceStrategy strategy = new ServiceInterfaceStrategy(CustomerService.class, true);
    final SoapJaxbDataFormat format = new SoapJaxbDataFormat("org.wildfly.camel.test.common.types", strategy);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .marshal(format);
        }
    });

    camelctx.start();
    try (InputStream input = getClass().getResourceAsStream("/envelope.xml")) {
        Customer customer = new Customer();
        customer.setFirstName("Kermit");
        customer.setLastName("The Frog");

        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBody("direct:start", customer, String.class);
        Assert.assertEquals(XMLUtils.compactXML(input), XMLUtils.compactXML(result));
    } finally {
        camelctx.close();
    }
}
 
Example 20
Source File: CXFWSSecureConsumerIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testCXFSecureConsumer() throws Exception {
    CamelContext camelContext = new DefaultCamelContext();

    CxfComponent cxfComponent = camelContext.getComponent("cxf", CxfComponent.class);

    CxfEndpoint cxfProducer = createCxfEndpoint(SECURE_WS_ENDPOINT_URL, cxfComponent);
    cxfProducer.setSslContextParameters(createSSLContextParameters());

    CxfEndpoint cxfConsumer = createCxfEndpoint(SECURE_WS_ENDPOINT_URL, cxfComponent);

    camelContext.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to(cxfProducer);

            from(cxfConsumer)
            .transform(simple("Hello ${body}"));
        }
    });

    try {
        // Force WildFly to generate a self-signed SSL cert & keystore
        HttpRequest.get("https://localhost:8443").throwExceptionOnFailure(false).getResponse();

        camelContext.start();

        ProducerTemplate template = camelContext.createProducerTemplate();
        String result = template.requestBody("direct:start", "Kermit", String.class);

        Assert.assertEquals("Hello Kermit", result);

        // Verify that if we attempt to use HTTP, we get a 302 redirect to the HTTPS endpoint URL
        HttpResponse response = HttpRequest.get(INSECURE_WS_ENDPOINT_URL + "?wsdl")
            .throwExceptionOnFailure(false)
            .followRedirects(false)
            .getResponse();
        Assert.assertEquals(302, response.getStatusCode());
        Assert.assertEquals(response.getHeader("Location"), SECURE_WS_ENDPOINT_URL + "?wsdl");
    } finally {
        camelContext.stop();
    }
}