Java Code Examples for org.apache.camel.CamelContext#start()

The following examples show how to use org.apache.camel.CamelContext#start() . 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: HttpServer.java    From camelinaction2 with Apache License 2.0 7 votes vote down vote up
public void server() throws Exception {
    CamelContext camel = new DefaultCamelContext();
    camel.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jetty:" + url)
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String body = exchange.getIn().getBody(String.class);

                        System.out.println("Received message: " + body);

                        if (body != null && body.contains("Kabom")) {
                            throw new Exception("ILLEGAL DATA");
                        }
                        exchange.getOut().setBody("OK");
                    }
                });
        }
    });
    camel.start();

}
 
Example 2
Source File: TidyMarkupIntegrationTest.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:start")
            .unmarshal().tidyMarkup();
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:start", "<body><a href=foo></body>", String.class).trim();
        Assert.assertTrue("Starts with html: " + result, result.startsWith("<html "));
        Assert.assertTrue("Contains end link: " + result, result.contains("</a>"));
        Assert.assertTrue("Ends with html: " + result, result.endsWith("</html>"));
    } finally {
        camelctx.close();
    }
}
 
Example 3
Source File: SOAPIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSoapV1_2Unmarshal() throws Exception {

    final SoapJaxbDataFormat format = new SoapJaxbDataFormat();
    format.setContextPath("org.wildfly.camel.test.jaxb.model");
    format.setVersion("1.2");

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

    camelctx.start();
    try (InputStream input = getClass().getResourceAsStream("/envelope-1.2-unmarshal.xml")) {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        Element response = producer.requestBody("direct:start", input, Element.class);
        Assert.assertEquals("Customer", response.getLocalName());
    } finally {
        camelctx.close();
    }
}
 
Example 4
Source File: SSHIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSSHConsumer() throws Exception {

    String conUrl = TestUtils.getResourceValue(getClass(), "/ssh-connection");

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF("ssh://admin@%s?username=admin&password=admin&pollCommand=echo Hello Kermit", conUrl)
            .to("mock:end");
        }
    });

    camelctx.start();
    try {
        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:end", MockEndpoint.class);
        mockEndpoint.expectedMessageCount(1);
        mockEndpoint.setAssertPeriod(100);
        mockEndpoint.expectedBodiesReceived("Hello Kermit" + System.lineSeparator());
    } finally {
        camelctx.close();
    }
}
 
Example 5
Source File: CamelDSLRoute.java    From java-course-ee with MIT License 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    CamelContext camelContext = new DefaultCamelContext();

    final InputGenerator inputGenerator = new InputGenerator();

    camelContext.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("timer:1s?fixedRate=true&period=1000").process(inputGenerator).transform(simple("${body.toUpperCase()}")).to("log:edu.javacourse.camel?level=INFO");
        }
    });

    camelContext.start();
    Thread.sleep(10000);
    camelContext.stop();
}
 
Example 6
Source File: MicrometerCounterIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testUsingScriptEvaluation() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.start();
    try {
        MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:out", MockEndpoint.class);
        mockEndpoint.expectedMessageCount(1);

        String message = "Hello from Camel Metrics!";
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBodyAndHeader("direct:in-4", message, HEADER_COUNTER_DECREMENT, 7.0D);

        Counter counter = metricsRegistry.find("D").counter();
        Assert.assertEquals(message.length(), counter.count(), 0.01D);
        Assert.assertEquals(Integer.toString(message.length()), counter.getId().getTag("a"));
        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: ReactorIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testTo() throws Exception {
    CamelContext camelctx = createWildFlyCamelContext();
    camelctx.start();
    try {
        CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);

        Set<String> values = Collections.synchronizedSet(new TreeSet<>());
        CountDownLatch latch = new CountDownLatch(3);

        Flux.just(1, 2, 3)
            .flatMap(e -> crs.to("bean:hello", e, String.class))
            .doOnNext(res -> values.add(res))
            .doOnNext(res -> latch.countDown())
            .subscribe();

        Assert.assertTrue(latch.await(2, TimeUnit.SECONDS));
        Assert.assertEquals(new TreeSet<>(Arrays.asList("Hello 1", "Hello 2", "Hello 3")), values);
    } finally {
        camelctx.close();
    }
}
 
Example 8
Source File: JingIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJingRngSchemaValidationSuccess() throws Exception {
    CamelContext camelctx = createCamelContext(false);

    MockEndpoint mockEndpointValid = camelctx.getEndpoint("mock:valid", MockEndpoint.class);
    mockEndpointValid.expectedMessageCount(1);

    MockEndpoint mockEndpointInvalid = camelctx.getEndpoint("mock:invalid", MockEndpoint.class);
    mockEndpointInvalid.expectedMessageCount(0);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", ORDER_XML_VALID);

        mockEndpointValid.assertIsSatisfied();
        mockEndpointInvalid.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 9
Source File: UndertowIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void overwriteCamelUndertowContextPathTest() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("undertow:http://localhost/test-servlet")
            .setBody(constant("Hello Kermit"));
        }
    });

    camelctx.start();
    try {
        // WAR deployment should fail as the context path is already registered by camel-undertow
        expectedException.expect(RuntimeException.class);
        deployer.deploy(TEST_SERVLET_WAR);
    } finally {
        camelctx.close();
        deployer.undeploy(TEST_SERVLET_WAR);
    }
}
 
Example 10
Source File: WordpressIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testUpdateUser() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            configureComponent(getContext());

            from("direct:updateUser").to("wordpress:user?id=9&user=ben&password=password123")
            .to("mock:resultUpdate");

        }
    });

    camelctx.start();
    try {
        MockEndpoint mock = camelctx.getEndpoint("mock:resultUpdate", MockEndpoint.class);
        mock.expectedBodyReceived().body(User.class);
        mock.expectedMessageCount(1);

        final User request = new User();
        request.setEmail("[email protected]");

        ProducerTemplate template = camelctx.createProducerTemplate();
        final User response = (User) template.requestBody("direct:updateUser", request);
        Assert.assertEquals(response.getId(), Integer.valueOf(1));
        Assert.assertEquals(response.getEmail(), "[email protected]");

        mock.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 11
Source File: JGroupsIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMasterElection() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);

    CamelContext camelcxt = new DefaultCamelContext();
    camelcxt.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            String jgroupsEndpoint = String.format("jgroups:%s?enableViewMessages=true", UUID.randomUUID());
            from(jgroupsEndpoint).filter(JGroupsFilters.dropNonCoordinatorViews()).process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    String camelContextName = exchange.getContext().getName();
                    if (!camelContextName.equals(master)) {
                        master = camelContextName;
                        System.out.println("ELECTED MASTER: " + master);
                        latch.countDown();
                    }
                }
            });
        }
    });

    camelcxt.start();
    try {
        Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
        Assert.assertEquals(camelcxt.getName(), master);
    } finally {
        camelcxt.stop();
    }
}
 
Example 12
Source File: HazelcastMapProducerIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test(expected = CamelExecutionException.class)
public void testWithInvalidOperation() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:putInvalid", "my-foo");
    } finally {
        camelctx.close();
    }
}
 
Example 13
Source File: ElasticsearchIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetWithHeaders() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
                .to("elasticsearch-rest://elasticsearch?operation=Index&hostAddresses=" + getElasticsearchHost());
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();

        //first, Index a value
        Map<String, String> map = createIndexedData("testGetWithHeaders");
        Map<String, Object> headers = new HashMap<>();
        headers.put(ElasticsearchConstants.PARAM_OPERATION, ElasticsearchOperation.Index);
        headers.put(ElasticsearchConstants.PARAM_INDEX_NAME, "twitter");

        String indexId = template.requestBodyAndHeaders("direct:start", map, headers, String.class);

        //now, verify GET
        headers.put(ElasticsearchConstants.PARAM_OPERATION, ElasticsearchOperation.GetById);
        GetResponse response = template.requestBodyAndHeaders("direct:start", indexId, headers, GetResponse.class);
        Assert.assertNotNull("response should not be null", response);
        Assert.assertNotNull("response source should not be null", response.getSource());
    } finally {
        camelctx.close();
    }
}
 
Example 14
Source File: CryptoCmsIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testCryptoCmsDecryptVerifyBinary() throws Exception {
    Assume.assumeFalse("[#2241] CryptoCmsIntegrationTest fails on IBM JDK", EnvironmentUtils.isIbmJDK() || EnvironmentUtils.isOpenJDK());

    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("crypto-cms:decrypt://testdecrypt?fromBase64=true&keyStoreParameters=#keyStoreParameters")
            .to("crypto-cms:verify://testverify?keyStoreParameters=#keyStoreParameters")
            .to("mock:result");
        }
    });

    KeyStoreParameters keyStoreParameters = new KeyStoreParameters();
    keyStoreParameters.setType("JCEKS");
    keyStoreParameters.setResource("/crypto.keystore");
    keyStoreParameters.setPassword("Abcd1234");
    context.bind("keyStoreParameters", keyStoreParameters);

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedBodiesReceived("Testmessage");

    camelctx.start();
    try {
        InputStream input = CryptoCmsIntegrationTest.class.getResourceAsStream("/signed.bin");

        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBody("direct:start", input);

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
        context.unbind("keyStoreParameters");
    }
}
 
Example 15
Source File: ZipkinIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testZipkin() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("seda:dude").routeId("dude")
            .log("routing at ${routeId}")
            .delay(simple("${random(1000,2000)}"));
        }
    });

    ZipkinTracer zipkin = new ZipkinTracer();
    zipkin.setServiceName("dude");
    zipkin.setSpanReporter(new LoggingReporter());
    zipkin.init(camelctx);

    NotifyBuilder notify = new NotifyBuilder(camelctx).whenDone(5).create();

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        for (int i = 0; i < 5; i++) {
            template.sendBody("seda:dude", "Hello World");
        }
        Assert.assertTrue(notify.matches(30, TimeUnit.SECONDS));
    } finally {
        camelctx.close();
    }
}
 
Example 16
Source File: FlatpackIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testUnmarshal() throws Exception {

    final FlatpackDataFormat format = new FlatpackDataFormat();
    format.setDefinition(FLATPACK_MAPPING_XML);
    format.setFixed(true);

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

    camelctx.start();
    try (InputStream input = getClass().getClassLoader().getResourceAsStream(FLATPACK_INPUT_TXT)) {
        Assert.assertNotNull("Input not null", input);
        ProducerTemplate producer = camelctx.createProducerTemplate();
        List<Map<String, String>> result = producer.requestBody("direct:start", input, List.class);
        Assert.assertEquals("Expected size 4: " + result, 4, result.size());
        Assert.assertEquals("JOHN", result.get(0).get("FIRSTNAME"));
        Assert.assertEquals("JIMMY", result.get(1).get("FIRSTNAME"));
        Assert.assertEquals("JANE", result.get(2).get("FIRSTNAME"));
        Assert.assertEquals("FRED", result.get(3).get("FIRSTNAME"));
    } finally {
        camelctx.close();
    }
}
 
Example 17
Source File: CamelToCamelRequestReply.java    From hazelcastmq with Apache License 2.0 4 votes vote down vote up
@Override
public void start() throws Exception {

  // Create a Hazelcast instance.
  Config config = new Config();
  config.getNetworkConfig().getJoin().getMulticastConfig().setEnabled(false);
  HazelcastInstance hazelcast = Hazelcast.newHazelcastInstance(config);

  try {
    // Create the HazelcaseMQ instance.
    HazelcastMQConfig mqConfig = new HazelcastMQConfig();
    mqConfig.setHazelcastInstance(hazelcast);
    HazelcastMQInstance mqInstance = HazelcastMQ
        .newHazelcastMQInstance(mqConfig);

    // Create the camel component.
    HazelcastMQCamelConfig mqCamelConfig = new HazelcastMQCamelConfig();
    mqCamelConfig.setHazelcastMQInstance(mqInstance);

    HazelcastMQCamelComponent mqCamelComponent =
        new HazelcastMQCamelComponent();
    mqCamelComponent.setConfiguration(mqCamelConfig);

    // Create the Camel context. This could be done via a Spring XML file.
    CamelContext camelContext = new DefaultCamelContext();
    camelContext.addComponent("hazelcastmq", mqCamelComponent);

    camelContext.addRoutes(new RouteBuilder() {
      @Override
      public void configure() {
        from("direct:primo.test")
            .to(ExchangePattern.InOut, "hazelcastmq:queue:secondo.test");

        from("hazelcastmq:queue:secondo.test").delay(1500)
            .setBody(constant("Goodbye World!"));
      }
    });

    camelContext.start();

    // Create a Camel producer.
    ProducerTemplate camelProducer = camelContext.createProducerTemplate();
    camelProducer.start();

    // Send a message to the direct endpoint.
    String reply = (String) camelProducer.sendBody("direct:primo.test",
        ExchangePattern.InOut, "Hello World!");

    if (reply == null) {
      log.warn("Did not get expected message!");
    }
    else {
      log.info("Got reply message: " + reply);
    }
    camelContext.stop();
  }
  finally {
    // Shutdown Hazelcast.
    hazelcast.getLifecycleService().shutdown();
  }
}
 
Example 18
Source File: RxJava2IntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testSubscriber() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("reactive-streams:sub1")
                .to("mock:sub1");
            from("reactive-streams:sub2")
                .to("mock:sub2");
            from("timer:tick?period=50")
                .setBody()
                .simple("${random(500)}")
                .to("mock:sub3")
                .to("reactive-streams:pub");
        }
    });

    CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);
    Subscriber<Integer> sub1 = crs.streamSubscriber("sub1", Integer.class);
    Subscriber<Integer> sub2 = crs.streamSubscriber("sub2", Integer.class);
    Publisher<Integer> pub = crs.fromStream("pub", Integer.class);

    pub.subscribe(sub1);
    pub.subscribe(sub2);

    camelctx.start();
    try {
        int count = 2;

        MockEndpoint e1 = camelctx.getEndpoint("mock:sub1", MockEndpoint.class);
        e1.expectedMinimumMessageCount(count);
        e1.assertIsSatisfied();

        MockEndpoint e2 = camelctx.getEndpoint("mock:sub2", MockEndpoint.class);
        e2.expectedMinimumMessageCount(count);
        e2.assertIsSatisfied();

        MockEndpoint e3 = camelctx.getEndpoint("mock:sub3", MockEndpoint.class);
        e3.expectedMinimumMessageCount(count);
        e3.assertIsSatisfied();

        for (int i = 0; i < count; i++) {
            Exchange ex1 = e1.getExchanges().get(i);
            Exchange ex2 = e2.getExchanges().get(i);
            Exchange ex3 = e3.getExchanges().get(i);

            Assert.assertEquals(ex1.getIn().getBody(), ex2.getIn().getBody());
            Assert.assertEquals(ex1.getIn().getBody(), ex3.getIn().getBody());
        }
    } finally {
        camelctx.close();
    }
}
 
Example 19
Source File: TikaIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void parseDoc() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("tika:parse").to("mock:result");
        }
    });
    MockEndpoint resultEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);

    try {
        camelctx.start();

        ProducerTemplate template = camelctx.createProducerTemplate();

        File document = new File("src/test/resources/tika/test.doc");
        template.sendBody("direct:start", document);

        resultEndpoint.setExpectedMessageCount(1);
        resultEndpoint.expectedMessagesMatches(new Predicate() {
            @Override
            public boolean matches(Exchange exchange) {
                Object body = exchange.getIn().getBody(String.class);
                Map<String, Object> headerMap = exchange.getIn().getHeaders();
                Assert.assertThat(body, instanceOf(String.class));

                Charset detectedCharset = null;
                try {
                    InputStream bodyIs = new ByteArrayInputStream(((String) body).getBytes());
                    UniversalEncodingDetector encodingDetector = new UniversalEncodingDetector();
                    detectedCharset = encodingDetector.detect(bodyIs, new Metadata());
                } catch (IOException e1) {
                    throw new RuntimeException(e1);
                }

                Assert.assertThat((String) body, containsString("test"));
                Assert.assertThat(detectedCharset.name(), startsWith(Charset.defaultCharset().name()));

                Assert.assertThat(headerMap.get(Exchange.CONTENT_TYPE), equalTo("application/msword"));
                return true;
            }
        });
        resultEndpoint.assertIsSatisfied();

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

    Assume.assumeTrue(hasSalesforceEnvVars());

    SalesforceLoginConfig loginConfig = new SalesforceLoginConfig();
    IntrospectionSupport.setProperties(loginConfig, salesforceOptions);

    SalesforceComponent component = new SalesforceComponent();
    component.setPackages("org.wildfly.camel.test.salesforce.dto");
    component.setLoginConfig(loginConfig);

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addComponent("salesforce",  component);
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:opportunity")
            .to("salesforce:query?sObjectQuery=SELECT Id,Name from Opportunity&sObjectClass=" + QueryRecordsOpportunity.class.getName());

            from("direct:account")
            .to("salesforce:query?sObjectQuery=SELECT Id,AccountNumber from Account&sObjectClass=" + QueryRecordsAccount.class.getName());
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();

        QueryRecordsOpportunity oppRecords = template.requestBody("direct:opportunity", null, QueryRecordsOpportunity.class);
        Assert.assertNotNull("Expected query records result to not be null", oppRecords);
        Assert.assertTrue("Expected some records", oppRecords.getRecords().size() > 0);

        Opportunity oppItem = oppRecords.getRecords().get(0);
        Assert.assertNotNull("Expected Oportunity Id", oppItem.getId());
        Assert.assertNotNull("Expected Oportunity Name", oppItem.getName());

        QueryRecordsAccount accRecords = template.requestBody("direct:account", null, QueryRecordsAccount.class);
        Assert.assertNotNull("Expected query records result to not be null", accRecords);
        Assert.assertTrue("Expected some records", accRecords.getRecords().size() > 0);

        Account accItem = accRecords.getRecords().get(0);
        Assert.assertNotNull("Expected Account Id", accItem.getId());
        Assert.assertNotNull("Expected Account Number", accItem.getAccountNumber());
    } finally {
        camelctx.close();
    }
}