org.apache.camel.ExtendedCamelContext Java Examples

The following examples show how to use org.apache.camel.ExtendedCamelContext. 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: ODataMetaDataRetrievalTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void testFindingAdapter() throws Exception {
    String resourcePath = "META-INF/syndesis/connector/meta/";
    String connectorId = "odata";
    ExtendedCamelContext context = new DefaultCamelContext();

    try {
        FactoryFinder finder = context.getFactoryFinder(resourcePath);
        assertThat(finder).isNotNull();

        Optional<Class<?>> type = finder.findClass(connectorId);
        assertTrue(type.isPresent());
        assertThat(type.get()).isEqualTo(ODataMetaDataRetrieval.class);

        MetadataRetrieval adapter = (MetadataRetrieval) context.getInjector().newInstance(type.get());
        assertThat(adapter).isNotNull();
    } finally {
        context.close();
    }
}
 
Example #2
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 #3
Source File: KnativeComponent.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Override
protected void doInit() throws Exception {
    super.doInit();

    if (transport == null) {
        this.transport = getCamelContext().getRegistry().lookupByNameAndType(protocol.name(), KnativeTransport.class);

        if (this.transport == null) {
            this.transport = getCamelContext()
                .adapt(ExtendedCamelContext.class)
                .getFactoryFinder(Knative.KNATIVE_TRANSPORT_RESOURCE_PATH)
                .newInstance(protocol.name(), KnativeTransport.class)
                .orElseThrow(() -> new RuntimeException("Error creating knative transport for protocol: " + protocol.name()));
        }
    }

    if (this.transport instanceof CamelContextAware) {
        CamelContextAware camelContextAware = (CamelContextAware)this.transport;

        if (camelContextAware.getCamelContext() == null) {
            camelContextAware.setCamelContext(getCamelContext());
        }
    }

    LOGGER.info("found knative transport: {} for protocol: {}", transport, protocol.name());
}
 
Example #4
Source File: AuthenticationCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSupportAllAuthenticationValues() {
    final ComponentProxyComponent component = new SwaggerProxyComponent("dataset-test", "dataset-test");
    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    component.setCamelContext(context);

    when(context.adapt(ExtendedCamelContext.class)).thenReturn(context);

    final AuthenticationCustomizer customizer = new AuthenticationCustomizer();

    Stream.of(AuthenticationType.values()).forEach(authenticationType -> {
        final Map<String, Object> options = new HashMap<>();
        options.put("authenticationType", authenticationType.name());

        customizer.customize(component, options);
        // no IllegalStateException thrown
    });
}
 
Example #5
Source File: AuthenticationCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldSupportNamedAuthenticationValues() {
    final ComponentProxyComponent component = new SwaggerProxyComponent("dataset-test", "dataset-test");
    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    component.setCamelContext(context);

    when(context.adapt(ExtendedCamelContext.class)).thenReturn(context);

    final AuthenticationCustomizer customizer = new AuthenticationCustomizer();

    Stream.of(AuthenticationType.values()).forEach(authenticationType -> {
        final Map<String, Object> options = new HashMap<>();
        options.put("authenticationType", authenticationType.name() + ":name");

        customizer.customize(component, options);
        // no IllegalStateException thrown
    });
}
 
Example #6
Source File: AuthenticationCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private static void assertHeaderSetTo(final ComponentProxyComponent component, final String headerName, final String headerValue) throws Exception {
    final Processor processor = component.getBeforeProducer();

    final Exchange exchange = mock(Exchange.class);
    final Message message = mock(Message.class);
    when(exchange.getIn()).thenReturn(message);
    when(exchange.getOut()).thenReturn(message);
    when(exchange.getPattern()).thenReturn(ExchangePattern.InOut);

    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    when(exchange.getContext()).thenReturn(context);

    final AsyncProcessorAwaitManager async = mock(AsyncProcessorAwaitManager.class);
    when(context.getAsyncProcessorAwaitManager()).thenReturn(async);

    processor.process(exchange);

    verify(message).setHeader(headerName, headerValue);
}
 
Example #7
Source File: ConnectorEndpoint.java    From syndesis with Apache License 2.0 6 votes vote down vote up
private MetadataRetrieval findAdapter(String connectorId) {
    MetadataRetrieval adapter = null;
    try {
        adapter = applicationContext.getBean(connectorId + "-adapter", MetadataRetrieval.class);
    } catch (NoSuchBeanDefinitionException | NoSuchBeanException ignored) {
        LOGGER.debug("No bean of type: {} with id: '{}-adapter' found in application context, switch to factory finder",
            MetadataRetrieval.class.getName(), connectorId);

        try {
            // Then fallback to camel's factory finder
            final FactoryFinder finder = camelContext.adapt(ExtendedCamelContext.class).getFactoryFinder(RESOURCE_PATH);
            final Class<?> type = finder.findClass(connectorId).get();

            adapter = (MetadataRetrieval) camelContext.getInjector().newInstance(type);
        } catch (@SuppressWarnings("PMD.AvoidCatchingGenericException") final Exception e) {
            LOGGER.warn("No factory finder of type: {} for id: {}", MetadataRetrieval.class.getName(), connectorId, e);
        }
    }

    if (adapter == null) {
        throw new IllegalStateException("Unable to find adapter for: " + connectorId);
    }

    return adapter;
}
 
Example #8
Source File: WebhookConnectorCustomizerTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldDestroyAllOutput() throws Exception {
    final WebhookConnectorCustomizer customizer = new WebhookConnectorCustomizer();
    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    customizer.setCamelContext(context);

    when(context.adapt(ExtendedCamelContext.class)).thenReturn(context);

    customizer.customize(component, Collections.emptyMap());

    final Processor afterConsumer = component.getAfterConsumer();
    assertThat(afterConsumer).isNotNull();

    final Exchange exchange = mock(Exchange.class);
    final Message message = mock(Message.class);
    when(exchange.getMessage()).thenReturn(message);

    afterConsumer.process(exchange);

    verify(message).setBody("");
    verify(message).removeHeaders("*");
    verify(message).setHeader(Exchange.HTTP_RESPONSE_CODE, 200);
    verify(message).setHeader(Exchange.HTTP_RESPONSE_TEXT, "No Content");
}
 
Example #9
Source File: IntegrationTracingContextCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(CamelContext camelContext) {
    // Lets generates always incrementing lexically sortable unique
    // uuids. These uuids are also more compact than the camel default
    // and contain an embedded timestamp.
    camelContext.setUuidGenerator(KeyGenerator::createKey);

    Tracer tracer = Configuration.fromEnv(serviceName).getTracer();
    camelContext.getRegistry().bind("tracer", tracer);

    camelContext.getRegistry().bind("bodyLogger", new BodyLogger.Default());

    TracingInterceptStrategy tis = new TracingInterceptStrategy(tracer);
    camelContext.getRegistry().bind("integrationLoggingInterceptStrategy", tis);
    if (camelContext instanceof ExtendedCamelContext) {
        ExtendedCamelContext ecc = (ExtendedCamelContext) camelContext;
        ecc.addInterceptStrategy(tis);

        // Log listener
        ecc.addLogListener(new TracingLogListener(tracer));
    }

    LOGGER.info("Added opentracing to CamelContext.");
}
 
Example #10
Source File: HttpRequestWrapperProcessorTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMapValuesFromMessageHeaders() throws Exception {
    String schemaStr = JsonUtils.writer().forType(JsonSchema.class).writeValueAsString(schema);
    JsonNode schemaNode = JsonUtils.reader().forType(JsonNode.class).readTree(schemaStr);
    final HttpRequestWrapperProcessor processor = new HttpRequestWrapperProcessor(schemaNode);

    final Exchange exchange = mock(Exchange.class);
    final Message message = mock(Message.class);
    final ExtendedCamelContext camelContext = mock(ExtendedCamelContext.class);
    when(camelContext.adapt(ExtendedCamelContext.class)).thenReturn(camelContext);
    when(camelContext.getHeadersMapFactory()).thenReturn(mock(HeadersMapFactory.class));
    when(exchange.getIn()).thenReturn(message);
    when(exchange.getContext()).thenReturn(camelContext);
    when(message.getBody()).thenReturn(givenBody);
    when(message.getHeader("param1", String[].class)).thenReturn(new String[] {"param_value1"});
    when(message.getHeader("param2", String[].class)).thenReturn(new String[] {"param_value2_1", "param_value2_2"});

    processor.process(exchange);

    final ArgumentCaptor<Message> replacement = ArgumentCaptor.forClass(Message.class);
    verify(exchange).setIn(replacement.capture());
    assertThat(replacement.getValue().getBody()).isEqualTo(replacedBody);
}
 
Example #11
Source File: HttpRequestWrapperProcessorTest.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldMapValuesFromHttpRequest() throws Exception {
    final String schemaStr = JsonUtils.writer().forType(JsonSchema.class).writeValueAsString(schema);
    final JsonNode schemaNode = JsonUtils.reader().forType(JsonNode.class).readTree(schemaStr);
    final HttpRequestWrapperProcessor processor = new HttpRequestWrapperProcessor(schemaNode);

    final Exchange exchange = mock(Exchange.class);
    final Message message = mock(Message.class);
    final ExtendedCamelContext camelContext = mock(ExtendedCamelContext.class);
    when(camelContext.adapt(ExtendedCamelContext.class)).thenReturn(camelContext);
    when(camelContext.getHeadersMapFactory()).thenReturn(mock(HeadersMapFactory.class));
    when(exchange.getIn()).thenReturn(message);
    when(exchange.getContext()).thenReturn(camelContext);
    final HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    when(message.getHeader(Exchange.HTTP_SERVLET_REQUEST, HttpServletRequest.class)).thenReturn(servletRequest);
    when(message.getBody()).thenReturn(givenBody);
    when(servletRequest.getParameterValues("param1")).thenReturn(new String[] {"param_value1"});
    when(servletRequest.getParameterValues("param2")).thenReturn(new String[] {"param_value2_1", "param_value2_2"});

    processor.process(exchange);

    final ArgumentCaptor<Message> replacement = ArgumentCaptor.forClass(Message.class);
    verify(exchange).setIn(replacement.capture());
    assertThat(replacement.getValue().getBody()).isEqualTo(replacedBody);
}
 
Example #12
Source File: IntegrationLoggingContextCustomizer.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public void apply(CamelContext camelContext) {
    // Lets generates always incrementing lexically sortable unique
    // uuids. These uuids are also more compact than the camel default
    // and contain an embedded timestamp.
    camelContext.setUuidGenerator(KeyGenerator::createKey);

    if(activityTracker == null) {
        activityTracker = new ActivityTracker.SysOut();
    }

    camelContext.getRegistry().bind("activityTracker", activityTracker);
    camelContext.getRegistry().bind("bodyLogger", new BodyLogger.Default());
    ActivityTrackingInterceptStrategy atis =
        new ActivityTrackingInterceptStrategy(activityTracker);
    camelContext.getRegistry().bind("integrationLoggingInterceptStrategy", atis);

    // Log listener
    if (camelContext instanceof ExtendedCamelContext) {
        ExtendedCamelContext ecc = (ExtendedCamelContext) camelContext;
        ecc.addLogListener(new IntegrationLoggingListener(activityTracker));
        ecc.addInterceptStrategy(atis);
    }

    LOGGER.info("Added IntegrationLoggingListener with {} to CamelContext.", activityTracker.getClass());
}
 
Example #13
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void createSwiftContainer() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    when(containerService.create(anyString(), nullable(CreateUpdateContainerOptions.class))).thenReturn(actionResponse);
    when(actionResponse.isSuccess()).thenReturn(true);

    SwiftEndpoint endpoint = Mockito.mock(SwiftEndpoint.class);
    Producer producer = new ContainerProducer(endpoint, client);
    msg.setHeader(OpenstackConstants.OPERATION, OpenstackConstants.CREATE);
    msg.setHeader(SwiftConstants.CONTAINER_NAME, CONTAINER_NAME);

    producer.process(exchange);

    ArgumentCaptor<String> containerNameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<CreateUpdateContainerOptions> optionsCaptor = ArgumentCaptor.forClass(CreateUpdateContainerOptions.class);

    verify(containerService).create(containerNameCaptor.capture(), optionsCaptor.capture());
    assertEquals(CONTAINER_NAME, containerNameCaptor.getValue());
    assertNull(optionsCaptor.getValue());
}
 
Example #14
Source File: CoreMainResource.java    From camel-quarkus with Apache License 2.0 6 votes vote down vote up
@Path("/context/reactive-executor")
@GET
@Produces(MediaType.TEXT_PLAIN)
public JsonObject reactiveExecutor() {
    ReactiveExecutor executor = main.getCamelContext().adapt(ExtendedCamelContext.class).getReactiveExecutor();

    JsonObjectBuilder builder = Json.createObjectBuilder();
    builder.add("class", executor.getClass().getName());

    if (executor instanceof VertXReactiveExecutor) {
        builder.add("configured", ((VertXReactiveExecutor) executor).getVertx() != null);

    }

    return builder.build();
}
 
Example #15
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void createNeutronNetwork() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    msg.setHeader(OpenstackConstants.OPERATION, OpenstackConstants.CREATE);
    msg.setHeader(OpenstackConstants.NAME, dummyNetwork.getName());
    msg.setHeader(NeutronConstants.NETWORK_TYPE, dummyNetwork.getNetworkType());
    msg.setHeader(NeutronConstants.TENANT_ID, dummyNetwork.getTenantId());

    NeutronEndpoint endpoint = Mockito.mock(NeutronEndpoint.class);
    Producer producer = new NetworkProducer(endpoint, client);
    producer.process(exchange);

    ArgumentCaptor<Network> captor = ArgumentCaptor.forClass(Network.class);
    verify(networkService).create(captor.capture());

    assertEqualsNetwork(dummyNetwork, captor.getValue());
    assertNotNull(msg.getBody(Network.class).getId());
}
 
Example #16
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void createKeystoneProject() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    msg.setHeader(OpenstackConstants.OPERATION, OpenstackConstants.CREATE);
    msg.setHeader(OpenstackConstants.NAME, dummyProject.getName());
    msg.setHeader(KeystoneConstants.DESCRIPTION, dummyProject.getDescription());
    msg.setHeader(KeystoneConstants.DOMAIN_ID, dummyProject.getDomainId());
    msg.setHeader(KeystoneConstants.PARENT_ID, dummyProject.getParentId());

    KeystoneEndpoint endpoint = Mockito.mock(KeystoneEndpoint.class);
    Producer producer = new ProjectProducer(endpoint, client);
    producer.process(exchange);

    ArgumentCaptor<Project> captor = ArgumentCaptor.forClass(Project.class);
    verify(projectService).create(captor.capture());

    assertEqualsProject(dummyProject, captor.getValue());
}
 
Example #17
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void reserveGlanceImage() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    GlanceEndpoint endpoint = Mockito.mock(GlanceEndpoint.class);
    when(endpoint.getOperation()).thenReturn(GlanceConstants.RESERVE);

    Message msg = new DefaultMessage(camelContext);
    msg.setBody(dummyImage);

    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    Producer producer = new GlanceProducer(endpoint, client);
    producer.process(exchange);
    ArgumentCaptor<Image> captor = ArgumentCaptor.forClass(Image.class);
    verify(imageService).reserve(captor.capture());
    assertEquals(dummyImage, captor.getValue());

    Image result = msg.getBody(Image.class);
    assertNotNull(result.getId());
    assertEqualsImages(dummyImage, result);
}
 
Example #18
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void createCinderVolume() throws Exception {
    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    CinderEndpoint endpoint = Mockito.mock(CinderEndpoint.class);
    when(endpoint.getOperation()).thenReturn(OpenstackConstants.CREATE);
    msg.setBody(dummyVolume);

    Producer producer = new VolumeProducer(endpoint, client);
    producer.process(exchange);
    assertEqualVolumes(dummyVolume, msg.getBody(Volume.class));
}
 
Example #19
Source File: JAXBInitalizationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testJaxbDumpModelAsXML() throws Exception {

	ModelCamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .routeId("route-1")
            .to("log:test");
        }
    });

    camelctx.start();

    try {
        ModelToXMLDumper dumper = camelctx.adapt(ExtendedCamelContext.class).getModelToXMLDumper();
        String xml = dumper.dumpModelAsXml(camelctx, camelctx.getRouteDefinition("route-1"));
        Assert.assertTrue(xml.contains("log:test"));
    } finally {
        camelctx.close();
    }
}
 
Example #20
Source File: FastHeadersIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testSimple() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            from("direct:start").to("log:foo").to("log:bar").to("mock:result");
        }
    });

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

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

        mockResult.assertIsSatisfied();

        HeadersMapFactory factory = camelctx.adapt(ExtendedCamelContext.class).getHeadersMapFactory();
        Assert.assertTrue("Instance of FastHeadersMapFactory", factory instanceof FastHeadersMapFactory);
    } finally {
        camelctx.close();
    }
}
 
Example #21
Source File: ProcessorsTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static ComponentProxyComponent createComponent() {
    // this uses a component from camel-catalog, sql component is
    // likely to be present there
    final ComponentProxyComponent component = new ComponentProxyComponent("sql", "sql");
    final ExtendedCamelContext mockContext = mock(ExtendedCamelContext.class);
    component.setCamelContext(mockContext);

    when(mockContext.adapt(ExtendedCamelContext.class)).thenReturn(mockContext);

    return component;
}
 
Example #22
Source File: TracingCamelContextConfiguration.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void beforeApplicationStart(CamelContext camelContext) {
    LOG.info("ActivityTracking: Opentracing Activity Logging strategy");
    // Lets generates always incrementing lexically sortable unique
    // uuids. These uuids are also more compact than the camel default
    // and contain an embedded timestamp.
    camelContext.setUuidGenerator(KeyGenerator::createKey);

    // Log listener
    camelContext.adapt(ExtendedCamelContext.class).addLogListener(new TracingLogListener(tracer));
}
 
Example #23
Source File: IntegrationRouteBuilder.java    From syndesis with Apache License 2.0 5 votes vote down vote up
/**
 * If the integration has a scheduler, start the route with a timer or quartz2
 * endpoint.
 */
private ProcessorDefinition<?> configureRouteScheduler(final Flow flow) throws URISyntaxException {
    if (flow.getScheduler().isPresent()) {
        Scheduler scheduler = flow.getScheduler().get();

        // We now support simple timer only, cron support will be supported
        // later on.
        if (scheduler.isTimer()) {
            Map<String, String> properties = new HashMap<>();
            properties.put("timerName", "integration");
            properties.put("period", scheduler.getExpression());

            final RuntimeCamelCatalog catalog = getContext().adapt(ExtendedCamelContext.class).getRuntimeCamelCatalog();
            final String uri = catalog.asEndpointUri("timer", properties, false);

            RouteDefinition route = this.from(uri);
            route.getInput().setId("integration-scheduler");
            flow.getId().ifPresent(route::setId);

            return route;
        }

        throw new IllegalArgumentException("Unsupported scheduler type: " + scheduler.getType());
    }

    return null;
}
 
Example #24
Source File: IntegrationTestSupport.java    From syndesis with Apache License 2.0 5 votes vote down vote up
public static void dumpRoutes(CamelContext context, RoutesDefinition definition) {
    if (!LOGGER.isInfoEnabled()) {
        return;
    }

    try {
        ExtendedCamelContext extendedCamelContext = context.adapt(ExtendedCamelContext.class);
        ModelToXMLDumper dumper = extendedCamelContext.getModelToXMLDumper();
        LOGGER.info("Routes: \n{}", dumper.dumpModelAsXml(context, definition));
    } catch (Exception e) {
        LOGGER.warn("Unable to dump route definition as XML");
        LOGGER.debug("Error encountered while dumping route definition as XML", e);
    }
}
 
Example #25
Source File: WebhookConnectorCustomizerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldAddWrapperProcessorIfSyndesisJsonSchemaGiven() throws Exception {
    final WebhookConnectorCustomizer customizer = new WebhookConnectorCustomizer();
    final ExtendedCamelContext context = mock(ExtendedCamelContext.class);
    customizer.setCamelContext(context);

    when(context.adapt(ExtendedCamelContext.class)).thenReturn(context);

    customizer.setOutputDataShape(new DataShape.Builder().kind(DataShapeKinds.JSON_SCHEMA).specification(SIMPLE_SCHEMA).build());

    customizer.customize(component, Collections.emptyMap());

    final Processor beforeConsumer = component.getBeforeConsumer();
    assertThat(beforeConsumer).isInstanceOf(Pipeline.class);
    final Pipeline pipeline = (Pipeline) beforeConsumer;
    final Collection<Processor> processors = pipeline.next();
    assertThat(processors).hasSize(3);
    assertThat(processors).anySatisfy(containsInstanceOf(HttpRequestWrapperProcessor.class));
    assertThat(processors).anySatisfy(containsInstanceOf(HttpMessageToDefaultMessageProcessor.class));

    final HttpRequestWrapperProcessor wrapper = (HttpRequestWrapperProcessor) processors.stream()
        .map(n -> ((Navigate<?>) n).next().get(0))
        .filter(HttpRequestWrapperProcessor.class::isInstance)
        .findFirst().get();
    assertThat(wrapper.getParameters()).containsOnly("source", "status");

    final Processor removeHeader = processors.stream().filter(p -> !(p instanceof HttpRequestWrapperProcessor)).findFirst().get();
    final Exchange exchange = mock(Exchange.class);
    final Message in = mock(Message.class);
    when(exchange.getIn()).thenReturn(in);
    removeHeader.process(exchange);
    verify(in).removeHeader(Exchange.HTTP_URI);
}
 
Example #26
Source File: HttpRequestUnwrapperProcessorTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Before
public void setupMocks() {
    final HeadersMapFactory factory = mock(HeadersMapFactory.class);
    when(camelContext.adapt(ExtendedCamelContext.class)).thenReturn(camelContext);
    when(camelContext.getHeadersMapFactory()).thenReturn(factory);
    when(factory.newMap()).thenReturn(new HashMap<>());
}
 
Example #27
Source File: SyncopeCamelContext.java    From syncope with Apache License 2.0 5 votes vote down vote up
private void loadRouteDefinitions(final List<String> routes) {
    try {
        RoutesDefinition routeDefs = (RoutesDefinition) camelContext.adapt(ExtendedCamelContext.class).
                getXMLRoutesDefinitionLoader().loadRoutesDefinition(
                        camelContext,
                        new ByteArrayInputStream(("<routes xmlns=\"http://camel.apache.org/schema/spring\">"
                                + routes.stream().collect(Collectors.joining())
                                + "</routes>").getBytes(StandardCharsets.UTF_8)));
        camelContext.addRouteDefinitions(routeDefs.getRoutes());
    } catch (Exception e) {
        LOG.error("While adding route definitions into Camel Context {}", getCamelContext(), e);
        throw new CamelException(e);
    }
}
 
Example #28
Source File: OpenstackIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testNovaKeypair() throws Exception {
    when(osTestKeypair.getName()).thenReturn(KEYPAIR_NAME);
    when(osTestKeypair.getPublicKey()).thenReturn(dummyKeypair.getPublicKey());
    when(osTestKeypair.getFingerprint()).thenReturn("fp");
    when(osTestKeypair.getPrivateKey()).thenReturn("prk");

    ExtendedCamelContext camelContext = Mockito.mock(ExtendedCamelContext.class);
    when(camelContext.getHeadersMapFactory()).thenReturn(new DefaultHeadersMapFactory());

    Message msg = new DefaultMessage(camelContext);
    msg.setHeader(OpenstackConstants.OPERATION, OpenstackConstants.CREATE);
    msg.setHeader(OpenstackConstants.NAME, KEYPAIR_NAME);

    Exchange exchange = Mockito.mock(Exchange.class);
    when(exchange.getIn()).thenReturn(msg);

    NovaEndpoint endpoint = Mockito.mock(NovaEndpoint.class);
    Producer producer = new KeypairProducer(endpoint, client);
    producer.process(exchange);

    ArgumentCaptor<String> nameCaptor = ArgumentCaptor.forClass(String.class);
    ArgumentCaptor<String> keypairCaptor = ArgumentCaptor.forClass(String.class);
    verify(keypairService).create(nameCaptor.capture(), keypairCaptor.capture());

    assertEquals(KEYPAIR_NAME, nameCaptor.getValue());
    assertNull(keypairCaptor.getValue());

    Keypair result = msg.getBody(Keypair.class);
    assertEquals("fp", result.getFingerprint());
    assertEquals("prk", result.getPrivateKey());
    assertEquals(dummyKeypair.getName(), result.getName());
    assertEquals(dummyKeypair.getPublicKey(), result.getPublicKey());
}
 
Example #29
Source File: ReactiveExecutorRecorder.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
public RuntimeValue<CamelContextCustomizer> createReactiveExecutorCustomizer(RuntimeValue<Vertx> vertx) {
    return new RuntimeValue<>(new CamelContextCustomizer() {
        @Override
        public void customize(CamelContext context) {
            VertXReactiveExecutor executor = new VertXReactiveExecutor();
            executor.setVertx(vertx.getValue());

            context.adapt(ExtendedCamelContext.class).setReactiveExecutor(executor);
        }
    });
}
 
Example #30
Source File: CamelSourceTask.java    From camel-kafka-connector with Apache License 2.0 5 votes vote down vote up
@Override
public void start(Map<String, String> props) {
    try {
        LOG.info("Starting CamelSourceTask connector task");
        Map<String, String> actualProps = TaskHelper.mergeProperties(getDefaultConfig(), props);
        config = getCamelSourceConnectorConfig(actualProps);

        maxBatchPollSize = config.getLong(CamelSourceConnectorConfig.CAMEL_SOURCE_MAX_BATCH_POLL_SIZE_CONF);
        maxPollDuration = config.getLong(CamelSourceConnectorConfig.CAMEL_SOURCE_MAX_POLL_DURATION_CONF);

        camelMessageHeaderKey = config.getString(CamelSourceConnectorConfig.CAMEL_SOURCE_MESSAGE_HEADER_KEY_CONF);

        String remoteUrl = config.getString(CamelSourceConnectorConfig.CAMEL_SOURCE_URL_CONF);
        final String unmarshaller = config.getString(CamelSourceConnectorConfig.CAMEL_SOURCE_UNMARSHAL_CONF);
        topic = config.getString(CamelSourceConnectorConfig.TOPIC_CONF);

        String localUrl = getLocalUrlWithPollingOptions(config);

        CamelContext camelContext = new DefaultCamelContext();
        if (remoteUrl == null) {
            remoteUrl = TaskHelper.buildUrl(camelContext.adapt(ExtendedCamelContext.class).getRuntimeCamelCatalog(),
                    actualProps, config.getString(CamelSourceConnectorConfig.CAMEL_SOURCE_COMPONENT_CONF),
                    CAMEL_SOURCE_ENDPOINT_PROPERTIES_PREFIX, CAMEL_SOURCE_PATH_PROPERTIES_PREFIX);
        }

        cms = new CamelMainSupport(actualProps, remoteUrl, localUrl, null, unmarshaller, 10, 500, camelContext);

        Endpoint endpoint = cms.getEndpoint(localUrl);
        consumer = endpoint.createPollingConsumer();
        consumer.start();

        cms.start();
        LOG.info("CamelSourceTask connector task started");
    } catch (Exception e) {
        throw new ConnectException("Failed to create and start Camel context", e);
    }
}