org.apache.camel.CamelContext Java Examples

The following examples show how to use org.apache.camel.CamelContext. 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: JmxNamingPatternSpringTest.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    enableJMX();

    CamelContext camelContext = super.createCamelContext();

    // Force hostname to be "localhost" for testing purposes
    final DefaultManagementNamingStrategy naming = (DefaultManagementNamingStrategy) camelContext.getManagementStrategy().getManagementNamingStrategy();
    naming.setHostName("localhost");
    naming.setDomainName("org.apache.camel");

    // setup the ManagementAgent to include the hostname
    camelContext.getManagementStrategy().getManagementAgent().setIncludeHostName(true);

    return camelContext;
}
 
Example #2
Source File: CXFWSSecureProducerIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testEndpointRouteWithValidCredentials() throws Exception {
    deployer.deploy(SIMPLE_WAR);
    try {
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                        .to("cxf://" + getEndpointAddress("/simple", "cxfuser", "cxfpassword"));
            }
        });

        camelctx.start();
        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            String result = producer.requestBody("direct:start", "Kermit", String.class);
            Assert.assertEquals("Hello Kermit", result);
        } finally {
            camelctx.close();
        }
    } finally {
        deployer.undeploy(SIMPLE_WAR);
    }
}
 
Example #3
Source File: ElSQLIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testElSQLConsumer() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("elsql:dbusers:users.elsql?dataSource=java:jboss/datasources/ExampleDS")
            .to("mock:end");
        }
    });

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

    camelctx.start();
    try {
        mockEndpoint.assertIsSatisfied();

        List<Exchange> exchanges = mockEndpoint.getReceivedExchanges();
        Assert.assertEquals("SA", exchanges.get(0).getIn().getBody(Map.class).get("NAME"));
    } finally {
        camelctx.close();
    }
}
 
Example #4
Source File: CamelMicroProfileMetricsRecorder.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public void customize(CamelContext camelContext) {
    if (config.enableRoutePolicy) {
        camelContext.addRoutePolicyFactory(new MicroProfileMetricsRoutePolicyFactory());
    }

    ManagementStrategy managementStrategy = camelContext.getManagementStrategy();
    if (config.enableExchangeEventNotifier) {
        managementStrategy.addEventNotifier(new MicroProfileMetricsExchangeEventNotifier());
    }

    if (config.enableRouteEventNotifier) {
        managementStrategy.addEventNotifier(new MicroProfileMetricsRouteEventNotifier());
    }

    if (config.enableCamelContextEventNotifier) {
        managementStrategy.addEventNotifier(new MicroProfileMetricsCamelContextEventNotifier());
    }
}
 
Example #5
Source File: RuntimeSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
public static Set<String> lookupCustomizerIDs(CamelContext context) {
    Set<String> customizers = new TreeSet<>();

    String customizerIDs = System.getenv().getOrDefault(Constants.ENV_CAMEL_K_CUSTOMIZERS, "");
    if (ObjectHelper.isEmpty(customizerIDs)) {
        // TODO: getPropertiesComponent().resolveProperty() throws exception instead
        //       of returning abd empty optional
        customizerIDs = context.getPropertiesComponent()
            .loadProperties(Constants.PROPERTY_CAMEL_K_CUSTOMIZER::equals)
            .getProperty(Constants.PROPERTY_CAMEL_K_CUSTOMIZER, "");
    }

    if  (ObjectHelper.isNotEmpty(customizerIDs)) {
        for (String customizerId : customizerIDs.split(",", -1)) {
            customizers.add(customizerId);
        }
    }

    return customizers;
}
 
Example #6
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService, boolean streaming,
                          boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork,
                          boolean parallelAggregate) {
    notNull(camelContext, "camelContext");
    this.camelContext = camelContext;
    this.processors = processors;
    this.aggregationStrategy = aggregationStrategy;
    this.executorService = executorService;
    this.shutdownExecutorService = shutdownExecutorService;
    this.streaming = streaming;
    this.stopOnException = stopOnException;
    // must enable parallel if executor service is provided
    this.parallelProcessing = parallelProcessing || executorService != null;
    this.timeout = timeout;
    this.onPrepare = onPrepare;
    this.shareUnitOfWork = shareUnitOfWork;
    this.parallelAggregate = parallelAggregate;
}
 
Example #7
Source File: HttpServer.java    From camelinaction with Apache License 2.0 6 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 #8
Source File: ICalFormatTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testMarshal() throws Exception {

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

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

        Calendar calendar = createTestCalendar();
        MockEndpoint mock = camelctx.getEndpoint("mock:result", MockEndpoint.class);
        mock.expectedBodiesReceived(calendar.toString());

        producer.sendBody("direct:marshal", calendar);

        mock.assertIsSatisfied();
    } finally {
        camelctx.close();
    }
}
 
Example #9
Source File: DockerIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testDockerComponentForHostnameAndPort() throws Exception {
    Assume.assumeNotNull("DOCKER_HOST environment variable is not set", System.getenv("DOCKER_HOST"));

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .toF("docker:version?host=%s&port=%d", TestUtils.getDockerHost(), TestUtils.getDockerPort());
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        Version dockerVersion = template.requestBody("direct:start", null, Version.class);
        Assert.assertNotNull("Docker version not null", dockerVersion);
        Assert.assertFalse("Docker version was empty", dockerVersion.getVersion().isEmpty());
    } finally {
        camelctx.close();
    }
}
 
Example #10
Source File: SimpleSpringProcessTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "process/example.bpmn20.xml" })
public void testRunProcess() throws Exception {
  CamelContext ctx = applicationContext.getBean(CamelContext.class);
  ProducerTemplate tpl = ctx.createProducerTemplate();
  service1.expectedBodiesReceived("ala");

  Exchange exchange = ctx.getEndpoint("direct:start").createExchange();
  exchange.getIn().setBody(Collections.singletonMap("var1", "ala"));
  tpl.send("direct:start", exchange);

  String instanceId = (String) exchange.getProperty("PROCESS_ID_PROPERTY");
  tpl.sendBodyAndProperty("direct:receive", null, ActivitiProducer.PROCESS_ID_PROPERTY, instanceId);

  assertProcessEnded(instanceId);

  service1.assertIsSatisfied();
  Map<?, ?> m = service2.getExchanges().get(0).getIn().getBody(Map.class);
  assertEquals("ala", m.get("var1"));
  assertEquals("var2", m.get("var2"));

}
 
Example #11
Source File: TimerExample.java    From camelinaction with Apache License 2.0 6 votes vote down vote up
public static void main(String args[]) throws Exception {
    // create CamelContext
    CamelContext context = new DefaultCamelContext();

    // add our route to the CamelContext
    context.addRoutes(new RouteBuilder() {
        public void configure() {
            from("timer://myTimer?period=2000")
            .setBody().simple("Current time is ${header.firedTime}")
            .to("stream:out");
        }
    });

    // start the route and let it do its work
    context.start();
    Thread.sleep(5000);

    // stop the CamelContext
    context.stop();
}
 
Example #12
Source File: SimpleCamelTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testRandomConversion() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .setBody().simple("${random(500)}");
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        Integer result = producer.requestBody("direct:start", null, Integer.class);
        Assert.assertNotNull(result);
        Assert.assertTrue(0 < result);
    } finally {
        camelctx.close();
    }
}
 
Example #13
Source File: SftpIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendFile() throws Exception {

    File testFile = resolvePath(FTP_ROOT_DIR).resolve("test.txt").toFile();
    CamelContext camelctx = new DefaultCamelContext();

    camelctx.start();
    try {
        Endpoint endpoint = camelctx.getEndpoint(getSftpEndpointUri());
        Assert.assertFalse(testFile.exists());
        camelctx.createProducerTemplate().sendBodyAndHeader(endpoint, "Hello", "CamelFileName", "test.txt");
        Assert.assertTrue(testFile.exists());
    } finally {
        camelctx.close();
        FileUtils.deleteDirectory(resolvePath(FTP_ROOT_DIR));
    }
}
 
Example #14
Source File: IntegrationRouteBuilder.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static Object mandatoryLoadResource(CamelContext context, String resource) {
    Object instance = null;

    if (resource.startsWith("classpath:")) {
        try (InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(context, resource)) {
            ExtendedCamelContext extendedCamelContext = context.adapt(ExtendedCamelContext.class);
            XMLRoutesDefinitionLoader loader = extendedCamelContext.getXMLRoutesDefinitionLoader();
            instance = loader.loadRoutesDefinition(context, is);
        } catch (Exception e) {
            throw new IllegalArgumentException(e);
        }
    } else if (resource.startsWith("class:")) {
        Class<?> type = context.getClassResolver().resolveClass(resource.substring("class:".length()));
        instance = context.getInjector().newInstance(type);
    } else if (resource.startsWith("bean:")) {
        instance = context.getRegistry().lookupByName(resource.substring("bean:".length()));
    }

    if (instance == null) {
        throw new IllegalArgumentException("Unable to resolve resource: " + resource);
    }

    return instance;
}
 
Example #15
Source File: EmptyProcessTest.java    From activiti6-boot2 with Apache License 2.0 6 votes vote down vote up
@Deployment(resources = { "process/empty.bpmn20.xml" })
public void testObjectAsStringVariable() throws Exception {
  CamelContext ctx = applicationContext.getBean(CamelContext.class);
  ProducerTemplate tpl = ctx.createProducerTemplate();
  Object expectedObj = new Long(99);

  Exchange exchange = ctx.getEndpoint("direct:startEmptyBodyAsString").createExchange();
  exchange.getIn().setBody(expectedObj);
  tpl.send("direct:startEmptyBodyAsString", exchange);

  String instanceId = (String) exchange.getProperty("PROCESS_ID_PROPERTY");

  assertProcessEnded(instanceId);
  HistoricVariableInstance var = processEngine.getHistoryService().createHistoricVariableInstanceQuery().variableName("camelBody").singleResult();
  assertNotNull(var);
  assertEquals(expectedObj.toString(), var.getValue().toString());
}
 
Example #16
Source File: NagiosIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSendToNagiosWarnAsText() throws Exception {

    CamelContext camelctx = createCamelContext();

    MessagePayload expectedPayload1 = new MessagePayload("localhost", Level.WARNING, camelctx.getName(),  "Hello Nagios");

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

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        template.sendBodyAndHeader("direct:start", "Hello Nagios", NagiosConstants.LEVEL, "WARNING");

        mock.assertIsSatisfied();

        Mockito.verify(nagiosPassiveCheckSender).send(expectedPayload1);
    } finally {
        camelctx.close();
    }
}
 
Example #17
Source File: SecureNettyIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testNettySecureTcpSocket() throws Exception {
    CamelContext camelctx = new DefaultCamelContext(new JndiBeanRepository());
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("netty:tcp://" + SOCKET_HOST + ":" + SOCKET_PORT + "?textline=true&ssl=true&sslContextParameters=#sslContextParameters");
        }
    });

    camelctx.start();
    try {
        String result = camelctx.createProducerTemplate().requestBody("direct:start", "Kermit", String.class);
        Assert.assertEquals("Hello Kermit", result);
    } finally {
        camelctx.close();
    }
}
 
Example #18
Source File: QuteEndpointConfigurer.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Override
public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) {
    QuteEndpoint target = (QuteEndpoint) obj;
    switch (ignoreCase ? name.toLowerCase() : name) {
    case "allowcontextmapall":
    case "allowContextMapAll": target.setAllowContextMapAll(property(camelContext, boolean.class, value)); return true;
    case "allowtemplatefromheader":
    case "allowTemplateFromHeader": target.setAllowTemplateFromHeader(property(camelContext, boolean.class, value)); return true;
    case "basicpropertybinding":
    case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true;
    case "contentcache":
    case "contentCache": target.setContentCache(property(camelContext, boolean.class, value)); return true;
    case "encoding": target.setEncoding(property(camelContext, java.lang.String.class, value)); return true;
    case "lazystartproducer":
    case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true;
    case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true;
    default: return false;
    }
}
 
Example #19
Source File: ReactorIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testToFunctionWithExchange() 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);
        Function<Object, Publisher<Exchange>> fun = crs.to("bean:hello");

        Flux.just(1, 2, 3)
            .flatMap(fun)
            .map(e -> e.getOut())
            .map(e -> e.getBody(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 #20
Source File: JSONJacksonAnnotationsTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testJsonIgnore() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            JacksonDataFormat jacksonDataFormat = new JacksonDataFormat();
            jacksonDataFormat.setPrettyPrint(false);

            from("direct:start")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    Organization organization = new Organization();
                    organization.setName("The Organization");

                    Employee employee = new Employee();
                    employee.setName("The Manager");
                    employee.setEmployeeNumber(12345);
                    employee.setOrganization(organization);
                    organization.setManager(employee);

                    exchange.getIn().setBody(employee);
                }
            })
            .marshal(jacksonDataFormat);
        }
    });

    camelctx.start();
    try {
        ProducerTemplate template = camelctx.createProducerTemplate();
        String result = template.requestBody("direct:start", null, String.class);

        Assert.assertEquals("{\"name\":\"The Manager\"}", result);
    } finally {
        camelctx.close();
    }
}
 
Example #21
Source File: KnativeSourceLoaderInterceptor.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
private static Optional<KnativeEnvironment.KnativeServiceDefinition> createSyntheticDefinition(
        CamelContext camelContext,
        String sinkName) {

    final String kSinkUrl = camelContext.resolvePropertyPlaceholders("{{k.sink:}}");
    final String kCeOverride = camelContext.resolvePropertyPlaceholders("{{k.ce.overrides:}}");

    if (ObjectHelper.isNotEmpty(kSinkUrl)) {
        // create a synthetic service definition to target the K_SINK url
        var serviceBuilder = KnativeEnvironment.serviceBuilder(Knative.Type.endpoint, sinkName)
            .withMeta(Knative.CAMEL_ENDPOINT_KIND, Knative.EndpointKind.sink)
            .withMeta(Knative.SERVICE_META_URL, kSinkUrl);

        if (ObjectHelper.isNotEmpty(kCeOverride)) {
            try (Reader reader = new StringReader(kCeOverride)) {
                // assume K_CE_OVERRIDES is defined as simple key/val json
                var overrides = Knative.MAPPER.readValue(
                    reader,
                    new TypeReference<HashMap<String, String>>() { }
                );

                for (var entry: overrides.entrySet()) {
                    // generate proper ce-override meta-data for the service
                    // definition
                    serviceBuilder.withMeta(
                        Knative.KNATIVE_CE_OVERRIDE_PREFIX + entry.getKey(),
                        entry.getValue()
                    );
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }

        return Optional.of(serviceBuilder.build());
    }

    return Optional.empty();
}
 
Example #22
Source File: SpringContextBindingJaxRsTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testJaxRsServiceCamelJndiBindingsInjectable() throws Exception {
    try {
        deployer.deploy(SIMPLE_WAR);

        CamelContext camelctx = contextRegistry.getCamelContext("jndi-delayed-binding-spring-context");
        Assert.assertNotNull("Expected jndi-delayed-binding-spring-context to not be null", camelctx);
        Assert.assertEquals(ServiceStatus.Started, camelctx.getStatus());

        HttpResponse response = HttpRequest.get("http://localhost:8080/simple/rest/context").getResponse();
        Assert.assertEquals("camelctxA,camelctxB,camelctxC", response.getBody());
    } finally {
        deployer.undeploy(SIMPLE_WAR);
    }
}
 
Example #23
Source File: RxJava2IntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMultipleConsumers() throws Exception {
    CamelContext camelctx = createCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("reactive-streams:multipleConsumers?concurrentConsumers=3")
                .process()
                .message(m -> m.setHeader("thread", Thread.currentThread().getId()))
                .to("mock:multipleBucket");
        }
    });

    CamelReactiveStreamsService crs = CamelReactiveStreams.get(camelctx);

    camelctx.start();
    try {
        Flowable.range(0, 1000).subscribe(
            crs.streamSubscriber("multipleConsumers", Number.class)
        );

        MockEndpoint endpoint = camelctx.getEndpoint("mock:multipleBucket", MockEndpoint.class);
        endpoint.expectedMessageCount(1000);
        endpoint.assertIsSatisfied();

        Assert.assertEquals(
            3,
            endpoint.getExchanges().stream()
                .map(x -> x.getIn().getHeader("thread", String.class))
                .distinct()
                .count()
        );
    } finally {
        camelctx.close();
    }
}
 
Example #24
Source File: FtpToJMSWithDynamicToTest.java    From camelinaction2 with Apache License 2.0 5 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));
    
    return camelContext;
}
 
Example #25
Source File: FlowableComponent.java    From flowable-engine with Apache License 2.0 5 votes vote down vote up
private <T> T getByType(CamelContext ctx, Class<T> kls) {
    Map<String, T> looked = ctx.getRegistry().findByTypeWithName(kls);
    if (looked.isEmpty()) {
        return null;
    }
    return looked.values().iterator().next();

}
 
Example #26
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Deprecated
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService,
                          boolean streaming, boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork) {
    this(camelContext, processors, aggregationStrategy, parallelProcessing, executorService, shutdownExecutorService,
            streaming, stopOnException, timeout, onPrepare, shareUnitOfWork, false);
}
 
Example #27
Source File: SpringContextTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpringContextFromURL() throws Exception {
    URL resourceUrl = getClass().getResource("/some-other-name.xml");
    CamelContext camelctx = SpringCamelContextFactory.createSingleCamelContext(resourceUrl, null);
    Assert.assertEquals(ServiceStatus.Stopped, camelctx.getStatus());
    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBody("direct:start", "Kermit", String.class);
        Assert.assertEquals("Hello green Frog", result);
    } finally {
        camelctx.close();
    }
}
 
Example #28
Source File: FhirMetadataRetrieval.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
protected SyndesisMetadata adapt(CamelContext context, String componentId, String actionId, Map<String, Object> properties, MetaDataExtension.MetaData metadata) {
    if (actionId.contains("transaction")) {
        //Transaction is not part of the FHIR spec, but we use it as a workaround for DataMapper to include
        //a number of resources in a transaction, because the DataMapper support for lists and choice fields is limited.
        properties.put(RESOURCE_TYPE, "Transaction");
    }

    if (!properties.containsKey(RESOURCE_TYPE)) {
        return SyndesisMetadata.EMPTY;
    }

    Set<String> resourceTypes = (Set<String>) metadata.getPayload();
    List<PropertyPair> resourceTypeResult = new ArrayList<>();
    resourceTypes.stream().forEach(
        t -> resourceTypeResult.add(new PropertyPair(t, t))
    );
    final Map<String, List<PropertyPair>> enrichedProperties = new HashMap<>();
    enrichedProperties.put(RESOURCE_TYPE,resourceTypeResult);
    enrichedProperties.put("containedResourceTypes", resourceTypeResult);

    if (ObjectHelper.isNotEmpty(ConnectorOptions.extractOption(properties, RESOURCE_TYPE))) {
        return createSyndesisMetadata(actionId, properties, enrichedProperties);
    }

    return SyndesisMetadata.of(enrichedProperties);
}
 
Example #29
Source File: CamelContextRecorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public RuntimeValue<CamelRuntime> createRuntime(BeanContainer beanContainer, RuntimeValue<CamelContext> context) {
    final CamelRuntime runtime = new CamelContextRuntime(context.getValue());

    // register to the container
    beanContainer.instance(CamelProducers.class).setRuntime(runtime);

    return new RuntimeValue<>(runtime);
}
 
Example #30
Source File: CronSourceLoaderInterceptor.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Override
public SourceLoader.Result afterLoad(SourceLoader loader, Source source, SourceLoader.Result result) {
    return new SourceLoader.Result() {
        @Override
        public Optional<RoutesBuilder> builder() {
            return RuntimeSupport.afterConfigure(result.builder(), builder -> {
                if (ObjectHelper.isEmpty(overridableComponents)) {
                    return;
                }

                final CamelContext context = runtime.getCamelContext();
                final String[] components = overridableComponents.split(",", -1);

                for (RouteDefinition def : builder.getRouteCollection().getRoutes()) {
                    String uri = def.getInput() != null ? def.getInput().getUri() : null;
                    if (shouldBeOverridden(uri, components)) {
                        def.getInput().setUri(timerUri);

                        //
                        // Don't install the shutdown strategy more than once.
                        //
                        if (context.getManagementStrategy().getEventNotifiers().stream().noneMatch(CronShutdownStrategy.class::isInstance)) {
                            context.getManagementStrategy().addEventNotifier(new CronShutdownStrategy(runtime));
                        }
                    }
                }
            });
        }

        @Override
        public Optional<Object> configuration() {
            return result.configuration();
        }
    };
}