Java源码示例:org.apache.camel.ExtendedCamelContext

示例1
@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();
}
 
示例2
@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());
}
 
示例3
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;
}
 
示例4
@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());
}
 
示例5
@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.");
}
 
示例6
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;
}
 
示例7
@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
    });
}
 
示例8
@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
    });
}
 
示例9
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);
}
 
示例10
@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");
}
 
示例11
@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);
}
 
示例12
@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);
}
 
示例13
@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();
    }
}
 
示例14
@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());
}
 
示例15
@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());
}
 
示例16
@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());
}
 
示例17
@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);
}
 
示例18
@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));
}
 
示例19
@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();
    }
}
 
示例20
@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();
    }
}
 
示例21
@Override
public void start(Map<String, String> props) {
    try {
        LOG.info("Starting CamelSinkTask connector task");
        Map<String, String> actualProps = TaskHelper.mergeProperties(getDefaultConfig(), props);
        config = getCamelSinkConnectorConfig(actualProps);

        String remoteUrl = config.getString(CamelSinkConnectorConfig.CAMEL_SINK_URL_CONF);
        final String marshaller = config.getString(CamelSinkConnectorConfig.CAMEL_SINK_MARSHAL_CONF);
        final int size = config.getInt(CamelSinkConnectorConfig.CAMEL_SINK_AGGREGATE_SIZE_CONF);
        final long timeout = config.getLong(CamelSinkConnectorConfig.CAMEL_SINK_AGGREGATE_TIMEOUT_CONF);

        CamelContext camelContext = new DefaultCamelContext();
        if (remoteUrl == null) {
            remoteUrl = TaskHelper.buildUrl(camelContext.adapt(ExtendedCamelContext.class).getRuntimeCamelCatalog(),
                                            actualProps,
                                            config.getString(CamelSinkConnectorConfig.CAMEL_SINK_COMPONENT_CONF),
                                            CAMEL_SINK_ENDPOINT_PROPERTIES_PREFIX,
                                            CAMEL_SINK_PATH_PROPERTIES_PREFIX);
        }

        cms = new CamelMainSupport(actualProps, LOCAL_URL, remoteUrl, marshaller, null, size, timeout, camelContext);

        producer = cms.createProducerTemplate();

        cms.start();
        LOG.info("CamelSinkTask connector task started");
    } catch (Exception e) {
        throw new ConnectException("Failed to create and start Camel context", e);
    }
}
 
示例22
@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);
    }
}
 
示例23
@Test
public void testBuildUrlWithRuntimeCatalog() throws URISyntaxException {
    DefaultCamelContext dcc = new DefaultCamelContext();
    RuntimeCamelCatalog rcc = dcc.adapt(ExtendedCamelContext.class).getRuntimeCamelCatalog();
    Map<String, String> props = new HashMap<String, String>() {
        {
            put("camel.source.path.name", "test");
            put("camel.source.endpoint.synchronous", "true");
        }
    };

    String result = TaskHelper.buildUrl(rcc, props, "direct", "camel.source.endpoint.", "camel.source.path.");

    assertEquals("direct:test?synchronous=true", result);

    props = new HashMap<String, String>() {
        {
            put("camel.source.path.port", "8080");
            put("camel.source.path.keyspace", "test");
            put("camel.source.path.hosts", "localhost");
        }
    };

    result = TaskHelper.buildUrl(rcc, props, "cql", "camel.source.endpoint.", "camel.source.path.");

    assertEquals("cql:localhost:8080/test", result);
}
 
示例24
@Path("/main/describe")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject describeMain() {
    final ExtendedCamelContext camelContext = main.getCamelContext().adapt(ExtendedCamelContext.class);

    JsonArrayBuilder listeners = Json.createArrayBuilder();
    main.getMainListeners().forEach(listener -> listeners.add(listener.getClass().getName()));

    JsonArrayBuilder routeBuilders = Json.createArrayBuilder();
    main.configure().getRoutesBuilders().forEach(builder -> routeBuilders.add(builder.getClass().getName()));

    JsonArrayBuilder routes = Json.createArrayBuilder();
    main.getCamelContext().getRoutes().forEach(route -> routes.add(route.getId()));

    JsonObjectBuilder collector = Json.createObjectBuilder();
    collector.add("type", main.getRoutesCollector().getClass().getName());
    if (main.getRoutesCollector() instanceof CamelMainRoutesCollector) {
        CamelMainRoutesCollector crc = (CamelMainRoutesCollector) main.getRoutesCollector();
        collector.add("type-registry", crc.getRegistryRoutesLoader().getClass().getName());
        collector.add("type-xml", crc.getXmlRoutesLoader().getClass().getName());
    }

    return Json.createObjectBuilder()
            .add("xml-loader", camelContext.getXMLRoutesDefinitionLoader().getClass().getName())
            .add("xml-model-dumper", camelContext.getModelToXMLDumper().getClass().getName())
            .add("xml-model-factory", camelContext.getModelJAXBContextFactory().getClass().getName())
            .add("routes-collector", collector)
            .add("listeners", listeners)
            .add("routeBuilders", routeBuilders)
            .add("routes", routes)
            .add("autoConfigurationLogSummary", main.getMainConfigurationProperties().isAutoConfigurationLogSummary())
            .build();
}
 
示例25
@Path("/context/name")
@POST
@Produces(MediaType.TEXT_PLAIN)
public String setCamelContextName(String name) {
    main.getCamelContext().adapt(ExtendedCamelContext.class).setName(name);
    return main.getCamelContext().getName();
}
 
示例26
@Path("/registry/component/{name}")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject describeRegistryComponent(@PathParam("name") String name) {
    final Map<String, Object> properties = new HashMap<>();
    final DefaultRegistry registry = main.getCamelContext().getRegistry(DefaultRegistry.class);
    final JsonObjectBuilder builder = Json.createObjectBuilder();

    Component component = registry.getFallbackRegistry().lookupByNameAndType(name, Component.class);
    if (component != null) {
        builder.add("type", component.getClass().getName());
        builder.add("registry", "fallback");
        builder.add("registry-type", registry.getFallbackRegistry().getClass().getName());
    } else {
        for (BeanRepository repository : registry.getRepositories()) {
            component = repository.lookupByNameAndType(name, Component.class);
            if (component != null) {
                builder.add("type", component.getClass().getName());
                builder.add("registry", "repository");
                builder.add("registry-type", repository.getClass().getName());
                break;
            }
        }
    }

    if (component != null) {
        main.getCamelContext().adapt(ExtendedCamelContext.class).getBeanIntrospection().getProperties(component, properties,
                null);
        properties.forEach((k, v) -> {
            if (v != null) {
                builder.add(k, Objects.toString(v));
            }
        });
    }

    return builder.build();
}
 
示例27
@Path("/main/describe")
@GET
@Produces(MediaType.APPLICATION_JSON)
public JsonObject describeMain() {
    final ExtendedCamelContext camelContext = main.getCamelContext().adapt(ExtendedCamelContext.class);

    JsonArrayBuilder listeners = Json.createArrayBuilder();
    main.getMainListeners().forEach(listener -> listeners.add(listener.getClass().getName()));

    JsonArrayBuilder routeBuilders = Json.createArrayBuilder();
    main.configure().getRoutesBuilders().forEach(builder -> routeBuilders.add(builder.getClass().getName()));

    JsonArrayBuilder routes = Json.createArrayBuilder();
    main.getCamelContext().getRoutes().forEach(route -> routes.add(route.getId()));

    JsonObjectBuilder collector = Json.createObjectBuilder();
    collector.add("type", main.getRoutesCollector().getClass().getName());
    if (main.getRoutesCollector() instanceof CamelMainRoutesCollector) {
        CamelMainRoutesCollector crc = (CamelMainRoutesCollector) main.getRoutesCollector();
        collector.add("type-registry", crc.getRegistryRoutesLoader().getClass().getName());
        collector.add("type-xml", crc.getXmlRoutesLoader().getClass().getName());
    }

    return Json.createObjectBuilder()
            .add("xml-loader", camelContext.getXMLRoutesDefinitionLoader().getClass().getName())
            .add("xml-model-dumper", camelContext.getModelToXMLDumper().getClass().getName())
            .add("xml-model-factory", camelContext.getModelJAXBContextFactory().getClass().getName())
            .add("routes-collector", collector)
            .add("listeners", listeners)
            .add("routeBuilders", routeBuilders)
            .add("routes", routes)
            .add("autoConfigurationLogSummary", main.getMainConfigurationProperties().isAutoConfigurationLogSummary())
            .build();
}
 
示例28
@Path("/adapt/extended-camel-context")
@GET
@Produces(MediaType.TEXT_PLAIN)
public boolean adaptToExtendedCamelContext() {
    try {
        context.adapt(ExtendedCamelContext.class);
        return true;
    } catch (ClassCastException e) {
        return false;
    }
}
 
示例29
@Override
protected void loadRouteBuilders(CamelContext camelContext) throws Exception {
    // routes are discovered and pre-instantiated which allow to post process them to support Camel's DI
    CamelBeanPostProcessor postProcessor = camelContext.adapt(ExtendedCamelContext.class).getBeanPostProcessor();
    for (RoutesBuilder builder : mainConfigurationProperties.getRoutesBuilders()) {
        postProcessor.postProcessBeforeInitialization(builder, builder.getClass().getName());
        postProcessor.postProcessAfterInitialization(builder, builder.getClass().getName());
    }
}
 
示例30
@Override
public synchronized RouteDefinition getRouteDefinition(String id) {
    for (RouteDefinition route : routeDefinitions) {
        if (route.idOrCreate(camelContext.adapt(ExtendedCamelContext.class).getNodeIdFactory()).equals(id)) {
            return route;
        }
    }
    return null;
}