org.apache.camel.model.ModelCamelContext Java Examples

The following examples show how to use org.apache.camel.model.ModelCamelContext. 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: 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 #2
Source File: CustomThreadPoolProfileRoute.java    From camel-cookbook-examples with Apache License 2.0 6 votes vote down vote up
@Override
public void configure() throws Exception {
    ThreadPoolProfile customThreadPoolProfile =
        new ThreadPoolProfileBuilder("customThreadPoolProfile").poolSize(5).maxQueueSize(100).build();
    ModelCamelContext context = getContext();
    context.getExecutorServiceManager().registerThreadPoolProfile(customThreadPoolProfile);

    from("direct:in")
        .log("Received ${body}:${threadName}")
        .threads().executorServiceRef("customThreadPoolProfile")
        .log("Processing ${body}:${threadName}")
        .transform(simple("${threadName}"))
        .to("mock:out");
}
 
Example #3
Source File: ApacheCamelExample.java    From yuzhouwan with Apache License 2.0 6 votes vote down vote up
public static void main(String... args) throws Exception {

        // 这是camel上下文对象,用来驱动所有路由
        ModelCamelContext camelContext = new DefaultCamelContext();
        // 启动route
        camelContext.start();
        // 将我们编排的一个完整消息路由过程,加入到上下文中
        camelContext.addRoutes(new ApacheCamelExample());

        /*
         * ==========================
         * 为什么我们先启动一个Camel服务
         * 再使用addRoutes添加编排好的路由呢?
         * 这是为了告诉各位读者,Apache Camel支持 动态加载/卸载编排 的路由
         * 这很重要,因为后续设计的Broker需要依赖这种能力
         * ==========================
         */

        // 通用没有具体业务意义的代码,只是为了保证主线程不退出
        synchronized (ApacheCamelExample.class) {
            ApacheCamelExample.class.wait();
        }
    }
 
Example #4
Source File: RuntimeTest.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@Test
public void testLoadJavaSourceWrap() throws Exception {
    KnativeComponent component = new KnativeComponent();
    component.setEnvironment(KnativeEnvironment.on(
        KnativeEnvironment.endpoint(Knative.EndpointKind.sink, "sink", "localhost", AvailablePortFinder.getNextAvailable())
    ));

    PlatformHttpServiceContextCustomizer phsc = new PlatformHttpServiceContextCustomizer();
    phsc.setBindPort(AvailablePortFinder.getNextAvailable());
    phsc.apply(runtime.getCamelContext());

    runtime.getCamelContext().addComponent("knative", component);
    runtime.addListener(RoutesConfigurer.forRoutes("classpath:MyRoutesWithBeans.java?interceptors=knative-source"));
    runtime.addListener(Runtime.Phase.Started, r ->  runtime.stop());
    runtime.run();

    assertThat(runtime.getRegistry().lookupByName("my-bean")).isInstanceOfSatisfying(MyBean.class, b -> {
        assertThat(b).hasFieldOrPropertyWithValue("name", "my-bean-name");
    });
    assertThat(runtime.getCamelContext(ModelCamelContext.class).getRouteDefinition("my-route")).satisfies(definition -> {
        assertThat(definition.getOutputs()).last().isInstanceOfSatisfying(ToDefinition.class, to -> {
            assertThat(to.getEndpointUri()).isEqualTo("knative://endpoint/sink");
        });
    });
}
 
Example #5
Source File: CoreResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/adapt/model-camel-context")
@GET
@Produces(MediaType.TEXT_PLAIN)
public boolean adaptToModelCamelContext() {
    try {
        context.adapt(ModelCamelContext.class);
        return true;
    } catch (ClassCastException e) {
        return false;
    }
}
 
Example #6
Source File: DirectRouterExample.java    From yuzhouwan with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {

        // 这是camel上下文对象,整个路由的驱动全靠它了
        ModelCamelContext camelContext = new DefaultCamelContext();
        // 启动route
        camelContext.start();
        // 首先将两个完整有效的路由注册到Camel服务中
        camelContext.addRoutes(new DirectRouterExample().new DirectRouteA());
        camelContext.addRoutes(new DirectRouterExample().new DirectRouteB());

        // 通用没有具体业务意义的代码,只是为了保证主线程不退出
        synchronized (DirectRouterExample.class) {
            DirectRouterExample.class.wait();
        }
    }
 
Example #7
Source File: RuntimeTest.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Test
void testLoadRouteAndRest() throws Exception {
    runtime.addListener(new ContextConfigurer());
    runtime.addListener(RoutesConfigurer.forRoutes("classpath:routes.xml", "classpath:rests.xml"));
    runtime.addListener(Runtime.Phase.Started, r -> {
        CamelContext context = r.getCamelContext();

        assertThat(context.adapt(ModelCamelContext.class).getRouteDefinitions()).isNotEmpty();
        assertThat(context.adapt(ModelCamelContext.class).getRestDefinitions()).isNotEmpty();

        runtime.stop();
    });

    runtime.run();
}
 
Example #8
Source File: RouteTest.java    From fcrepo-camel-toolbox with Apache License 2.0 5 votes vote down vote up
@Override
protected CamelContext createCamelContext() throws Exception {
    final CamelContext ctx = getOsgiService(CamelContext.class, "(camel.context.name=FcrepoSolrIndexerTest)",
            10000);
    context = (ModelCamelContext)ctx;
    return ctx;
}
 
Example #9
Source File: MqttOnCamelMqttToLinkIntegrationTest.java    From Ardulink-2 with Apache License 2.0 5 votes vote down vote up
private CamelContext camelContext(Topics topics) throws Exception {
	ModelCamelContext context = new DefaultCamelContext();
	MqttConnectionProperties mqtt = new MqttConnectionProperties().name("foo").brokerHost(brokerHost())
			.brokerPort(brokerPort());
	new MqttCamelRouteBuilder(context, topics).fromSomethingToMqtt(MOCK, mqtt).andReverse();
	adviceAll(context, d -> d.getInput().getEndpointUri().equals(MOCK), a -> a.replaceFromWith("direct:noop"));
	// CamelContext#start is async so it does not guarantee that routes are ready,
	// so we call #startRouteDefinitions
	context.startRouteDefinitions();
	context.start();
	return context;
}
 
Example #10
Source File: IntegrationTest.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@Test
public void testRestDSL() {
    configureRoutes(
        "classpath:routes-with-rest-dsl.js"
    );

    ModelCamelContext mcc = context.adapt(ModelCamelContext.class);
    List<RestDefinition> rests = mcc.getRestDefinitions();
    List<RouteDefinition> routes = mcc.getRouteDefinitions();

    assertThat(rests).hasSize(1);
    assertThat(rests).first().hasFieldOrPropertyWithValue("produces", "text/plain");
    assertThat(rests).first().satisfies(definition -> {
        assertThat(definition.getVerbs()).hasSize(1);
        assertThat(definition.getVerbs()).first().isInstanceOfSatisfying(GetVerbDefinition.class, get -> {
            assertThat(get).hasFieldOrPropertyWithValue("uri", "/say/hello");
        });
    });

    assertThat(routes).hasSize(1);
    assertThat(routes).first().satisfies(definition -> {
        assertThat(definition.getInput()).isInstanceOf(FromDefinition.class);
        assertThat(definition.getOutputs()).hasSize(1);
        assertThat(definition.getOutputs()).first().satisfies(output -> {
            assertThat(output).isInstanceOf(TransformDefinition.class);
        });
    });
}
 
Example #11
Source File: SpringContextRouteLoader.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
public void addRoutesToCamelContext() throws Exception
{
    ModelCamelContext modelCamelContext = (ModelCamelContext) applicationContext.getBean(camelContextId);
    ArrayList<RouteDefinition> routeDefinitions = (ArrayList<RouteDefinition>) applicationContext.getBean(routeContextId);
    modelCamelContext.addRouteDefinitions(routeDefinitions);
}
 
Example #12
Source File: RouteXml.java    From fabric8-forge with Apache License 2.0 5 votes vote down vote up
public void copyRoutesToElement(CamelContext context, CamelContextFactoryBean contextElement) {
    if (context instanceof ModelCamelContext) {
        copyRoutesToElement(((ModelCamelContext) context).getRouteDefinitions(), contextElement);
    } else {
        LOG.error("Invalid camel context! ({})", context.getClass().getName());
    }
}
 
Example #13
Source File: IntegrationRouteBuilder.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private void loadFragments(Step step) {
    if (StepKind.extension != step.getStepKind()) {
        return;
    }

    final StepAction action = step.getActionAs(StepAction.class)
                                  .orElseThrow(() -> new IllegalArgumentException(
                                          String.format("Missing step action on step: %s - %s", step.getId(), step.getName())));

    if (action.getDescriptor().getKind() == StepAction.Kind.ENDPOINT) {
        final ModelCamelContext context = getContext();
        final String resource = action.getDescriptor().getResource();

        if (ObjectHelper.isNotEmpty(resource) && resources.add(resource)) {
            final Object instance = mandatoryLoadResource(context, resource);
            final RoutesDefinition definitions = mandatoryConvertToRoutesDefinition(resource, instance);

            LOGGER.debug("Resolved resource: {} as {}", resource, instance.getClass());

            try {
                context.addRouteDefinitions(definitions.getRoutes());
            } catch (Exception e) {
                throw new IllegalStateException(e);
            }
        }
    }
}
 
Example #14
Source File: IntegrationTestSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
protected void dumpRoutes(ModelCamelContext context) {
    RoutesDefinition definition = new RoutesDefinition();
    definition.setRoutes(context.adapt(ModelCamelContext.class).getRouteDefinitions());

    dumpRoutes(context, definition);
}
 
Example #15
Source File: MqttOnCamelMqttToLinkIntegrationTest.java    From Ardulink-2 with Apache License 2.0 4 votes vote down vote up
private static void adviceAll(ModelCamelContext context, Predicate<RouteDefinition> predicate,
		ThrowingConsumer<AdviceWithRouteBuilder, Exception> throwingConsumer) throws Exception {
	List<String> routeIds = context.getRouteDefinitions().stream().filter(predicate)
			.map(RouteDefinition::getRouteId).collect(toList());
	routeIds.forEach(d -> replaceFromWith(context, d, throwingConsumer));
}
 
Example #16
Source File: XmlModel.java    From fabric8-forge with Apache License 2.0 4 votes vote down vote up
public CamelContext createContext(Collection<RouteDefinition> routes) throws Exception {
    ModelCamelContext context = new DefaultCamelContext();
    context.addRouteDefinitions(routes);
    return context;
}
 
Example #17
Source File: RestSwaggerConnectorIntegrationTest.java    From syndesis with Apache License 2.0 4 votes vote down vote up
private RouteBuilder createRouteBuilder() {
    return new IntegrationRouteBuilder("", Resources.loadServices(IntegrationStepHandler.class)) {

        {
            setContext(createContext());
        }

        @Override
        public void configure() throws Exception {
            errorHandler(defaultErrorHandler().maximumRedeliveries(1));

            super.configure();
        }

        private ModelCamelContext createContext() {
            final Properties properties = new Properties();

            properties.put("flow-3.rest-openapi-1.password", "supersecret");

            properties.put("flow-4.rest-openapi-1.accessToken", "access-token");

            properties.put("flow-6.rest-openapi-1.clientSecret", "client-secret");
            properties.put("flow-6.rest-openapi-1.accessToken", "access-token");
            properties.put("flow-6.rest-openapi-1.refreshToken", "refresh-token");

            properties.put("flow-7.rest-openapi-1.clientSecret", "client-secret");
            properties.put("flow-7.rest-openapi-1.accessToken", "access-token");
            properties.put("flow-7.rest-openapi-1.refreshToken", "refresh-token");

            properties.put("flow-8.rest-openapi-1.authenticationParameterValue", "supersecret");

            properties.put("flow-9.rest-openapi-1.authenticationParameterValue", "supersecret");

            properties.put("flow-10.rest-openapi-1.authenticationParameterValue", "supersecret");

            final ModelCamelContext leanContext = new DefaultCamelContext();
            final PropertiesComponent propertiesComponent = leanContext.getPropertiesComponent();
            propertiesComponent.setInitialProperties(properties);

            leanContext.disableJMX();

            return leanContext;
        }

        @Override
        protected Integration loadIntegration() {
            return createIntegration();
        }
    };
}
 
Example #18
Source File: IntegrationTestSupport.java    From syndesis with Apache License 2.0 4 votes vote down vote up
public static void dumpRoutes(ModelCamelContext context) {
    RoutesDefinition definition = new RoutesDefinition();
    definition.setRoutes(context.getRouteDefinitions());

    dumpRoutes(context, definition);
}
 
Example #19
Source File: CamelSteps.java    From yaks with Apache License 2.0 4 votes vote down vote up
@Given("^start route (.+)$")
public void startRoute(String routeId) {
    runner.run(camel().context(camelContext().adapt(ModelCamelContext.class))
                                 .start(routeId));
}
 
Example #20
Source File: KnativeSourceRoutesLoaderTest.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("parameters")
public void testWrapLoaderWithSyntheticServiceDefinition(String uri) throws Exception {
    LOGGER.info("uri: {}", uri);

    final String data = UUID.randomUUID().toString();
    final TestRuntime runtime = new TestRuntime();
    final String typeHeaderKey = CloudEvents.v1_0.mandatoryAttribute(CloudEvent.CAMEL_CLOUD_EVENT_TYPE).http();
    final String typeHeaderVal = UUID.randomUUID().toString();
    final String url = String.format("http://localhost:%d", runtime.port);

    KnativeComponent component = new KnativeComponent();
    component.setEnvironment(new KnativeEnvironment(Collections.emptyList()));

    Properties properties = new Properties();
    properties.put("knative.sink", "mySynk");
    properties.put("k.sink", String.format("http://localhost:%d", runtime.port));
    properties.put("k.ce.overrides", Knative.MAPPER.writeValueAsString(Map.of(typeHeaderKey, typeHeaderVal)));

    CamelContext context = runtime.getCamelContext();
    context.getPropertiesComponent().setInitialProperties(properties);
    context.addComponent(KnativeConstants.SCHEME, component);

    Source source = Sources.fromURI(uri);
    SourceLoader loader = RoutesConfigurer.load(runtime, source);

    assertThat(loader.getSupportedLanguages()).contains(source.getLanguage());
    assertThat(runtime.builders).hasSize(1);

    try {
        context.addRoutes(runtime.builders.get(0));
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                fromF("platform-http:/")
                    .routeId("http")
                    .to("mock:result");
            }
        });
        context.start();

        var definitions = context.adapt(ModelCamelContext.class).getRouteDefinitions();
        var services = context.getRegistry().findByType(KnativeEnvironment.KnativeServiceDefinition.class);

        assertThat(definitions).hasSize(2);
        assertThat(definitions).first().satisfies(d -> {
            assertThat(d.getOutputs()).last().hasFieldOrPropertyWithValue(
                "endpointUri",
                "knative://endpoint/mySynk"
            );
        });

        assertThat(services).hasSize(1);
        assertThat(services).first().hasFieldOrPropertyWithValue("name", "mySynk");
        assertThat(services).first().hasFieldOrPropertyWithValue("url", url);

        MockEndpoint mock = context.getEndpoint("mock:result", MockEndpoint.class);
        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(data);
        mock.expectedHeaderReceived(typeHeaderKey, typeHeaderVal);

        context.createFluentProducerTemplate()
            .to("direct:start")
            .withHeader("MyHeader", data)
            .send();

        mock.assertIsSatisfied();
    } finally {
        context.stop();
    }
}
 
Example #21
Source File: KnativeSourceRoutesLoaderTest.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
@ParameterizedTest
@MethodSource("parameters")
public void testWrapLoader(String uri) throws Exception {
    LOGGER.info("uri: {}", uri);

    final String data = UUID.randomUUID().toString();
    final TestRuntime runtime = new TestRuntime();

    KnativeComponent component = new KnativeComponent();
    component.setEnvironment(KnativeEnvironment.on(
        KnativeEnvironment.endpoint(Knative.EndpointKind.sink, "sink", "localhost", runtime.port)
    ));

    CamelContext context = runtime.getCamelContext();
    context.addComponent(KnativeConstants.SCHEME, component);

    Source source = Sources.fromURI(uri);
    SourceLoader loader = RoutesConfigurer.load(runtime, source);

    assertThat(loader.getSupportedLanguages()).contains(source.getLanguage());
    assertThat(runtime.builders).hasSize(1);

    try {
        context.addRoutes(runtime.builders.get(0));
        context.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                fromF("platform-http:/")
                    .routeId("http")
                    .to("mock:result");
            }
        });
        context.start();

        List<RouteDefinition> definitions = context.adapt(ModelCamelContext.class).getRouteDefinitions();

        assertThat(definitions).hasSize(2);
        assertThat(definitions).first().satisfies(d -> {
            assertThat(d.getOutputs()).last().hasFieldOrPropertyWithValue(
                "endpointUri",
                "knative://endpoint/sink"
            );
        });

        MockEndpoint mock = context.getEndpoint("mock:result", MockEndpoint.class);
        mock.expectedMessageCount(1);
        mock.expectedBodiesReceived(data);

        context.createFluentProducerTemplate()
            .to("direct:start")
            .withHeader("MyHeader", data)
            .send();

        mock.assertIsSatisfied();
    } finally {
        context.stop();
    }
}
 
Example #22
Source File: NameCustomizer.java    From camel-k-runtime with Apache License 2.0 4 votes vote down vote up
@Override
public void apply(CamelContext camelContexty) {
    camelContexty.adapt(ModelCamelContext.class).setNameStrategy(new ExplicitCamelContextNameStrategy(name));
}
 
Example #23
Source File: CamelMainObserversTest.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
public void afterStart(@Observes AfterStart event) {
    event.getCamelContext(ModelCamelContext.class).getRoutes().forEach(
            route -> routes.add(route.getRouteId()));
}
 
Example #24
Source File: CoreMainResource.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@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();
    camelContext.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());
    }

    JsonObjectBuilder dataformatsInRegistry = Json.createObjectBuilder();
    camelContext.getRegistry().findByTypeWithName(DataFormat.class)
            .forEach((name, value) -> dataformatsInRegistry.add(name, value.getClass().getName()));

    JsonObjectBuilder languagesInRegistry = Json.createObjectBuilder();
    camelContext.getRegistry().findByTypeWithName(Language.class)
            .forEach((name, value) -> languagesInRegistry.add(name, value.getClass().getName()));

    JsonObjectBuilder componentsInRegistry = Json.createObjectBuilder();
    camelContext.getRegistry().findByTypeWithName(Component.class)
            .forEach((name, value) -> componentsInRegistry.add(name, value.getClass().getName()));

    JsonObjectBuilder factoryClassMap = Json.createObjectBuilder();
    FactoryFinderResolver factoryFinderResolver = camelContext.getFactoryFinderResolver();
    if (factoryFinderResolver instanceof FastFactoryFinderResolver) {
        ((FastFactoryFinderResolver) factoryFinderResolver).getClassMap().forEach((k, v) -> {
            factoryClassMap.add(k, v.getName());
        });
    }

    return Json.createObjectBuilder()
            .add("xml-loader", camelContext.getXMLRoutesDefinitionLoader().getClass().getName())
            .add("xml-model-dumper", camelContext.getModelToXMLDumper().getClass().getName())
            .add("routes-collector", collector)
            .add("listeners", listeners)
            .add("routeBuilders", routeBuilders)
            .add("routes", routes)
            .add("lru-cache-factory", LRUCacheFactory.getInstance().getClass().getName())
            .add("autoConfigurationLogSummary", main.getMainConfigurationProperties().isAutoConfigurationLogSummary())
            .add("config", Json.createObjectBuilder()
                    .add("rest-port",
                            camelContext.getRestConfiguration().getPort())
                    .add("resilience4j-sliding-window-size",
                            camelContext.adapt(ModelCamelContext.class)
                                    .getResilience4jConfiguration(null)
                                    .getSlidingWindowSize()))
            .add("registry", Json.createObjectBuilder()
                    .add("components", componentsInRegistry)
                    .add("dataformats", dataformatsInRegistry)
                    .add("languages", languagesInRegistry))
            .add("factory-finder", Json.createObjectBuilder()
                    .add("class-map", factoryClassMap))
            .build();
}
 
Example #25
Source File: CamelSteps.java    From yaks with Apache License 2.0 4 votes vote down vote up
@Given("^remove route (.+)$")
public void removeRoute(String routeId) {
    runner.run(camel().context(camelContext().adapt(ModelCamelContext.class))
                                 .remove(routeId));
}
 
Example #26
Source File: CamelSteps.java    From yaks with Apache License 2.0 4 votes vote down vote up
@Given("^stop route (.+)$")
public void stopRoute(String routeId) {
    runner.run(camel().context(camelContext().adapt(ModelCamelContext.class))
                                 .stop(routeId));
}