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

The following examples show how to use org.apache.camel.CamelContext#getComponent() . 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: JPATransactionManagerIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJpaTransactionManagerRouteRoute() throws Exception {

    CamelContext camelctx = contextRegistry.getCamelContext("jpa-context");
    Assert.assertNotNull("Expected jpa-context to not be null", camelctx);

    // Persist a new account entity
    Account account = new Account(1, 500);
    camelctx.createProducerTemplate().sendBody("direct:start", account);

    JpaComponent component = camelctx.getComponent("jpa", JpaComponent.class);
    EntityManagerFactory entityManagerFactory = component.getEntityManagerFactory();

    // Read the saved entity back from the database
    EntityManager em = entityManagerFactory.createEntityManager();
    Account result = em.getReference(Account.class, 1);
    Assert.assertEquals(account, result);
}
 
Example 2
Source File: AhcWSSIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testAsyncWssRoute() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start").to("ahc-wss:" + WEBSOCKET_ENDPOINT);
            from("ahc-wss:" + WEBSOCKET_ENDPOINT).to("seda:end");
        }
    });

    WsComponent wsComponent = (WsComponent) camelctx.getComponent("ahc-wss");
    wsComponent.setSslContextParameters(defineSSLContextClientParameters());

    PollingConsumer consumer = camelctx.getEndpoint("seda:end").createPollingConsumer();
    consumer.start();

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

        Exchange exchange = consumer.receive(1000);
        Assert.assertEquals("Hello Kermit", exchange.getIn().getBody(String.class));

    } finally {
        camelctx.close();
    }
}
 
Example 3
Source File: ComponentVerifier.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.AvoidDeeplyNestedIfStmts")
protected ComponentVerifierExtension resolveComponentVerifierExtension(CamelContext context, String scheme) {
    if (verifierExtension == null) {
        synchronized (this) {
            if (verifierExtension == null) {
                Component component = context.getComponent(scheme, true, false);
                if (component == null) {
                    LOG.error("Component {} does not exist", scheme);
                } else {
                    verifierExtension = component.getExtension(verifierExtensionClass).orElse(null);
                    if (verifierExtension == null) {
                        LOG.warn("Component {} does not support verifier extension", scheme);
                    }
                }
            }
        }
    }

    return verifierExtension;
}
 
Example 4
Source File: FtpToJMSWithPropertyPlaceholderTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    // create CamelContext
    CamelContext camelContext = super.createCamelContext();
    
    // connect to embedded ActiveMQ JMS broker
    ConnectionFactory connectionFactory = 
        new ActiveMQConnectionFactory("vm://localhost");
    camelContext.addComponent("jms",
        JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    // setup the properties component to use the test file
    PropertiesComponent prop = camelContext.getComponent("properties", PropertiesComponent.class);
    prop.setLocation("classpath:rider-test.properties");        
    
    return camelContext;
}
 
Example 5
Source File: SecuringConfigTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    CamelContext context = super.createCamelContext();

 // create the jasypt properties parser
    JasyptPropertiesParser jasypt = new JasyptPropertiesParser();
    // and set the master password
    jasypt.setPassword("supersecret");   
    
    // we can avoid keeping the master password in plaintext in the application
    // by referencing a environment variable
    // export CAMEL_ENCRYPTION_PASSWORD=supersecret
    // jasypt.setPassword("sysenv:CAMEL_ENCRYPTION_PASSWORD");
    
    // setup the properties component to use the production file
    PropertiesComponent prop = context.getComponent("properties", PropertiesComponent.class);
    prop.setLocation("classpath:rider-test.properties");

    // and use the jasypt properties parser so we can decrypt values
    prop.setPropertiesParser(jasypt);
    
    return context;
}
 
Example 6
Source File: SlackIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSlackMessage() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:test").to("slack:#general?iconEmoji=:camel:&username=CamelTest").to("mock:result");
            from("undertow:http://localhost/slack/webhook").setBody(constant("{\"ok\": true}"));
        }
    });

    SlackComponent comp = camelctx.getComponent("slack", SlackComponent.class);
    comp.setWebhookUrl("http://localhost:8080/slack/webhook");

    MockEndpoint mockEndpoint = camelctx.getEndpoint("mock:result", MockEndpoint.class);
    mockEndpoint.expectedMessageCount(1);

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        producer.sendBody("direct:test", "Hello from Camel!");
        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 7
Source File: JCloudsBlobStoreIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobStoreProducer() throws Exception {
    BlobStore blobStore = getBlobStore();

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .setHeader(JcloudsConstants.BLOB_NAME, constant(BLOB_NAME_WITH_DIR))
            .setHeader(JcloudsConstants.CONTAINER_NAME, constant(CONTAINER_NAME_WITH_DIR))
            .to("jclouds:blobstore:transient");
        }
    });

    List<BlobStore> blobStores = new ArrayList<>();
    blobStores.add(blobStore);

    JcloudsComponent jclouds = camelctx.getComponent("jclouds", JcloudsComponent.class);
    jclouds.setBlobStores(blobStores);

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBody("direct:start", "Hello Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    } finally {
        camelctx.close();
    }

}
 
Example 8
Source File: JCloudsBlobStoreIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testBlobStoreConsumerWithDirectory() throws Exception {
    BlobStore blobStore = getBlobStore();

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF("jclouds:blobstore:transient?container=%s&directory=dir", CONTAINER_NAME_WITH_DIR)
            .convertBodyTo(String.class)
            .to("mock:result");
        }
    });

    List<BlobStore> blobStores = new ArrayList<>();
    blobStores.add(blobStore);

    JcloudsComponent jclouds = camelctx.getComponent("jclouds", JcloudsComponent.class);
    jclouds.setBlobStores(blobStores);

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

    camelctx.start();
    try {
        JcloudsBlobStoreHelper.writeBlob(blobStore, CONTAINER_NAME_WITH_DIR, BLOB_NAME_WITH_DIR, new StringPayload("Hello Kermit"));

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example 9
Source File: TwilioIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testTwilioProducer() throws Exception {
    Assume.assumeNotNull("TWILIO_ACCOUNT_SID is null", TWILIO_ACCOUNT_SID);
    Assume.assumeNotNull("TWILIO_PASSWORD is null", TWILIO_PASSWORD);

    CamelContext camelctx = new DefaultCamelContext();

    TwilioComponent component = camelctx.getComponent("twilio", TwilioComponent.class);
    component.setUsername(TWILIO_ACCOUNT_SID);
    component.setPassword(TWILIO_PASSWORD);
    component.setAccountSid(TWILIO_ACCOUNT_SID);

    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct://start").to("twilio://account/fetch");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        Account account = template.requestBodyAndHeader("direct:start", null,
                "CamelTwilioPathSid", TWILIO_ACCOUNT_SID,
                Account.class);

        Assert.assertNotNull("Twilio fetcher result was null", account);
        Assert.assertEquals("Account SID did not match", TWILIO_ACCOUNT_SID, account.getSid());
    } finally {
        camelctx.close();
    }
}
 
Example 10
Source File: CamelRiderJavaDSLProdTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    CamelContext context = super.createCamelContext();

    // setup the properties component to use the production file
    PropertiesComponent prop = context.getComponent("properties", PropertiesComponent.class);
    prop.setLocation("classpath:rider-prod.properties");

    return context;
}
 
Example 11
Source File: CamelRiderJavaDSLTest.java    From camelinaction with Apache License 2.0 5 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    CamelContext context = super.createCamelContext();

    // setup the properties component to use the test file
    PropertiesComponent prop = context.getComponent("properties", PropertiesComponent.class);
    prop.setLocation("classpath:rider-test.properties");

    return context;
}
 
Example 12
Source File: ActiveMQConnector.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private SjmsComponent lookupComponent() {
    final CamelContext context = getCamelContext();
    final List<String> names = context.getComponentNames();

    if (ObjectHelper.isEmpty(names)) {
        return null;
    }

    // Try to check if a component with same set-up has already been
    // configured, if so reuse it.
    for (String name : names) {
        Component cmp = context.getComponent(name, false, false);
        if (!(cmp instanceof SjmsComponent)) {
            continue;
        }

        ConnectionFactory factory = ((SjmsComponent) cmp).getConnectionFactory();
        if (factory instanceof ActiveMQConnectionFactory) {
            ActiveMQConnectionFactory amqFactory = (ActiveMQConnectionFactory) factory;

            if (!Objects.equals(brokerUrl, amqFactory.getBrokerURL())) {
                continue;
            }
            if (!Objects.equals(username, amqFactory.getUserName())) {
                continue;
            }
            if (!Objects.equals(password, amqFactory.getPassword())) {
                continue;
            }

            return (SjmsComponent) cmp;
        }
    }

    return null;
}
 
Example 13
Source File: ComponentMetadataRetrieval.java    From syndesis with Apache License 2.0 5 votes vote down vote up
protected MetaDataExtension resolveMetaDataExtension(CamelContext context, Class<? extends MetaDataExtension> metaDataExtensionClass, String componentId, String actionId) {
    Component component = context.getComponent(componentId, true, false);
    if (component == null) {
        throw new IllegalArgumentException(
            String.format("Component %s does not exists", componentId)
        );
    }

    return component.getExtension(metaDataExtensionClass).orElse(null);
}
 
Example 14
Source File: ComponentProxyWithCustomComponentTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void validate(Registry registry) throws Exception {
    final CamelContext context = new DefaultCamelContext(registry);

    try {
        context.setAutoStartup(false);
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                    .to("my-sql-proxy")
                    .to("mock:result");
            }
        });

        context.start();

        Collection<String> names = context.getComponentNames();

        assertThat(names).contains("my-sql-proxy");
        assertThat(names).contains("sql-my-sql-proxy");

        SqlComponent sqlComponent = context.getComponent("sql-my-sql-proxy", SqlComponent.class);
        DataSource sqlDatasource = sqlComponent.getDataSource();

        assertThat(sqlDatasource).isEqualTo(this.ds);

        Map<String, Endpoint> endpoints = context.getEndpointMap();
        assertThat(endpoints).containsKey("sql-my-sql-proxy://select%20from%20dual");
    } finally {
        context.stop();
    }
}
 
Example 15
Source File: KnativeHttpTestSupport.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
public static KnativeComponent configureKnativeComponent(CamelContext context, CloudEvent ce, List<KnativeEnvironment.KnativeServiceDefinition> definitions) {
    KnativeComponent component = context.getComponent("knative", KnativeComponent.class);
    component.setCloudEventsSpecVersion(ce.version());
    component.setEnvironment(new KnativeEnvironment(definitions));

    return component;
}
 
Example 16
Source File: BaseOlingo4Test.java    From syndesis with Apache License 2.0 4 votes vote down vote up
@Test
public void testExpectations() throws Exception {
    URI httpURI = URI.create(defaultTestServer.servicePlainUri() + FORWARD_SLASH + defaultTestServer.resourcePath());
    String camelURI = "olingo4://read/" + defaultTestServer.resourcePath();

    //
    // Create own main class to allow for setting the context
    //
    try (MyMain main = new MyMain()) {

        //
        // Get a context we can play with
        //
        CamelContext context = main.getCamelContext();

        //
        // Find the olingo4 component to configure
        //
        Olingo4Component component = (Olingo4Component) context.getComponent("olingo4");

        //
        // Create a configuration and apply the sevice url to
        // workaround the no serviceUri problem.
        //
        Olingo4AppEndpointConfiguration configuration = new Olingo4AppEndpointConfiguration();

        //
        // Override the ACCEPT header since it does not take account of the odata.metadata parameter
        //
        Map<String, String> httpHeaders = new HashMap<>();
        httpHeaders.put(HttpHeaders.ACCEPT, "application/json;odata.metadata=full,application/xml,*/*");
        configuration.setHttpHeaders(httpHeaders);

        configuration.setServiceUri(defaultTestServer.servicePlainUri());

        //
        // Apply empty values to these properties so they are
        // not violated as missing
        //
        configuration.setQueryParams(new HashMap<>());
        configuration.setEndpointHttpHeaders(new HashMap<>());

        //
        // Apply the configuration to the component
        //
        component.setConfiguration(configuration);

        //
        // Apply the component to the context
        //
        context.removeComponent("olingo4");
        context.addComponent("olingo4", component);

        //
        // Apply the route and run
        //
        main.addRoutesBuilder(new MyRouteBuilder(camelURI));

        ClientEntitySet olEntitySet = null;
        ODataRetrieveResponse<ClientEntitySet> response = null;
        ODataClient client = ODataClientFactory.getClient();
        try {
            response = client.getRetrieveRequestFactory().getEntitySetRequest(httpURI).execute();
            assertEquals(HttpStatus.SC_OK, response.getStatusCode());

            olEntitySet = response.getBody();
            assertNotNull(olEntitySet);
        } finally {
            if (response != null) {
                response.close();
            }
        }

        main.start();

        /*
         * Note:
         * Annoyingly, cannot put olEntitySet in the expected body of
         * the mock:result. Although an EntitySet is returned with all the
         * correct properties and values, some of the individual entity
         * attributes are slightly different, such as names being null
         * rather than Edm.null. These different attributes do not make
         * the results wrong enough to fail the test.
         */

        MockEndpoint result = context.getEndpoint("mock:result", MockEndpoint.class);
        result.setMinimumExpectedMessageCount(1);
        result.assertIsSatisfied();

        //
        // Split is true by default hence the return of a client entity rather than an entity set
        //
        Object body = result.getExchanges().get(0).getIn().getBody();
        assertTrue(body instanceof ClientEntity);
        ClientEntity cmEntity = (ClientEntity) body;

        ClientEntity olEntity = olEntitySet.getEntities().get(0);
        assertEquals(olEntity.getProperties(), cmEntity.getProperties());
    }
}
 
Example 17
Source File: AtomixMapIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testPutAndGet() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        public void configure() {
            from("direct:start").toF("atomix-map:%s", MAP_NAME);
        }
    });

    final String key = camelctx.getUuidGenerator().generateUuid();
    final String val = camelctx.getUuidGenerator().generateUuid();

    AtomixMapComponent component = camelctx.getComponent("atomix-map", AtomixMapComponent.class);
    component.setNodes(Collections.singletonList(replicaAddress));

    camelctx.start();
    try {
        Message result;

        FluentProducerTemplate fluent = camelctx.createFluentProducerTemplate().to("direct:start");

        result = fluent.clearAll()
                .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixMap.Action.PUT)
                .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
                .withBody(val)
                .request(Message.class);

        Assert.assertFalse(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        Assert.assertEquals(val, result.getBody());
        Assert.assertEquals(val, map.get(key).join());

        result = fluent.clearAll()
                .withHeader(AtomixClientConstants.RESOURCE_ACTION, AtomixMap.Action.GET)
                .withHeader(AtomixClientConstants.RESOURCE_KEY, key)
                .request(Message.class);

        Assert.assertTrue(result.getHeader(AtomixClientConstants.RESOURCE_ACTION_HAS_RESULT, Boolean.class));
        Assert.assertEquals(val, result.getBody(String.class));
        Assert.assertTrue(map.containsKey(key).join());
    } finally {
        camelctx.close();
    }

}
 
Example 18
Source File: ComponentOptionsTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private static void validateRegistryOption(CamelContext context) throws Exception {
    context.start();

    Collection<String> names = context.getComponentNames();

    assertThat(names).contains("my-sql-proxy");
    assertThat(names).contains("sql");
    assertThat(names).doesNotContain("sql-my-sql-proxy");

    SqlComponent sqlComponent = context.getComponent("sql", SqlComponent.class);
    DataSource sqlDatasource = sqlComponent.getDataSource();

    assertThat(sqlDatasource).isNull();

    Map<String, Endpoint> endpoints = context.getEndpointMap();
    assertThat(endpoints).containsKey("sql://select%20from%20dual?dataSource=%23ds");


    context.stop();
}
 
Example 19
Source File: AbstractXChangeIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
boolean hasAPICredentials(CamelContext camelctx) {
    XChangeComponent component = camelctx.getComponent("xchange", XChangeComponent.class);
    XChange xchange = component.getXChange();
    IllegalStateAssertion.assertNotNull(xchange, "XChange not created");
    return xchange.getExchangeSpecification().getApiKey() != null;
}
 
Example 20
Source File: JCloudsBlobStoreIntegrationTest.java    From wildfly-camel with Apache License 2.0 4 votes vote down vote up
@Test
public void testBlobStoreConsumer() throws Exception {
    BlobStore blobStore = getBlobStore();

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            fromF("jclouds:blobstore:transient?container=%s", CONTAINER_NAME)
            .convertBodyTo(String.class)
            .to("mock:result");
        }
    });

    List<BlobStore> blobStores = new ArrayList<>();
    blobStores.add(blobStore);

    JcloudsComponent jclouds = camelctx.getComponent("jclouds", JcloudsComponent.class);
    jclouds.setBlobStores(blobStores);

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

    camelctx.start();
    try {
        JcloudsBlobStoreHelper.writeBlob(blobStore, CONTAINER_NAME, BLOB_NAME, new StringPayload("Hello Kermit"));

        mockEndpoint.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}