Search in sources :

Example 1 with Runtime

use of org.apache.camel.k.Runtime in project camel-k-runtime by apache.

the class LoaderSupport method inspectSource.

public static JsonObject inspectSource(CamelContext context, String location, byte[] code) throws Exception {
    final Runtime runtime = Runtime.on(context);
    final RoutesLoader loader = context.adapt(ExtendedCamelContext.class).getRoutesLoader();
    final Collection<RoutesBuilder> builders = loader.findRoutesBuilders(ResourceHelper.fromBytes(location, code));
    for (RoutesBuilder builder : builders) {
        runtime.addRoutes(builder);
    }
    return Json.createObjectBuilder().add("components", extractComponents(context)).add("routes", extractRoutes(context)).add("endpoints", extractEndpoints(context)).build();
}
Also used : Runtime(org.apache.camel.k.Runtime) ExtendedCamelContext(org.apache.camel.ExtendedCamelContext) RoutesLoader(org.apache.camel.spi.RoutesLoader) RoutesBuilder(org.apache.camel.RoutesBuilder)

Example 2 with Runtime

use of org.apache.camel.k.Runtime in project camel-k-runtime by apache.

the class SourcesSupport method load.

public static void load(Runtime runtime, Source source) {
    final List<RouteBuilderLifecycleStrategy> interceptors;
    switch(source.getType()) {
        case source:
            interceptors = RuntimeSupport.loadInterceptors(runtime.getCamelContext(), source);
            interceptors.forEach(interceptor -> {
                if (interceptor instanceof RuntimeAware) {
                    ((RuntimeAware) interceptor).setRuntime(runtime);
                }
            });
            break;
        case template:
            if (!source.getInterceptors().isEmpty()) {
                LOGGER.warn("Interceptors associated to the route template {} will be ignored", source.getName());
            }
            interceptors = List.of(new RouteBuilderLifecycleStrategy() {

                @Override
                public void afterConfigure(RouteBuilder builder) {
                    List<RouteDefinition> routes = builder.getRouteCollection().getRoutes();
                    List<RouteTemplateDefinition> templates = builder.getRouteTemplateCollection().getRouteTemplates();
                    if (routes.size() != 1) {
                        throw new IllegalArgumentException("There should be a single route definition, got " + routes.size());
                    }
                    if (!templates.isEmpty()) {
                        throw new IllegalArgumentException("There should not be any template, got " + templates.size());
                    }
                    // create a new template from the source
                    RouteTemplateDefinition templatesDefinition = builder.getRouteTemplateCollection().routeTemplate(source.getId());
                    templatesDefinition.setRoute(routes.get(0));
                    source.getPropertyNames().forEach(templatesDefinition::templateParameter);
                    // remove all routes definitions as they have been translated
                    // in the related route template
                    routes.clear();
                }
            });
            break;
        case errorHandler:
            if (!source.getInterceptors().isEmpty()) {
                LOGGER.warn("Interceptors associated to the route template {} will be ignored", source.getName());
            }
            interceptors = List.of(new RouteBuilderLifecycleStrategy() {

                @Override
                public void afterConfigure(RouteBuilder builder) {
                    List<RouteDefinition> routes = builder.getRouteCollection().getRoutes();
                    List<RouteTemplateDefinition> templates = builder.getRouteTemplateCollection().getRouteTemplates();
                    if (!routes.isEmpty()) {
                        throw new IllegalArgumentException("There should be no route definition, got " + routes.size());
                    }
                    if (!templates.isEmpty()) {
                        throw new IllegalArgumentException("There should not be any template, got " + templates.size());
                    }
                    if (hasErrorHandlerBuilder(builder)) {
                        LOGGER.debug("Setting default error handler builder factory as {}", builder.getErrorHandlerBuilder());
                        runtime.getCamelContext().adapt(ExtendedCamelContext.class).setErrorHandlerFactory(builder.getErrorHandlerBuilder());
                    }
                }
            });
            break;
        default:
            throw new IllegalArgumentException("Unknown source type: " + source.getType());
    }
    try {
        final Resource resource = Sources.asResource(runtime.getCamelContext(), source);
        final ExtendedCamelContext ecc = runtime.getCamelContext(ExtendedCamelContext.class);
        final Collection<RoutesBuilder> builders = ecc.getRoutesLoader().findRoutesBuilders(resource);
        builders.stream().map(RouteBuilder.class::cast).peek(b -> interceptors.forEach(b::addLifecycleInterceptor)).forEach(runtime::addRoutes);
    } catch (Exception e) {
        throw RuntimeCamelException.wrapRuntimeCamelException(e);
    }
}
Also used : RuntimeCamelException(org.apache.camel.RuntimeCamelException) RouteDefinition(org.apache.camel.model.RouteDefinition) RoutesBuilder(org.apache.camel.RoutesBuilder) RouteTemplateDefinition(org.apache.camel.model.RouteTemplateDefinition) SourcesConfigurer(org.apache.camel.k.listener.SourcesConfigurer) Logger(org.slf4j.Logger) Resource(org.apache.camel.spi.Resource) AbstractPhaseListener(org.apache.camel.k.listener.AbstractPhaseListener) Collection(java.util.Collection) LoggerFactory(org.slf4j.LoggerFactory) ExtendedCamelContext(org.apache.camel.ExtendedCamelContext) List(java.util.List) SourceDefinition(org.apache.camel.k.SourceDefinition) RouteBuilder(org.apache.camel.builder.RouteBuilder) Source(org.apache.camel.k.Source) RuntimeAware(org.apache.camel.k.RuntimeAware) Runtime(org.apache.camel.k.Runtime) ObjectHelper(org.apache.camel.util.ObjectHelper) RouteBuilderLifecycleStrategy(org.apache.camel.builder.RouteBuilderLifecycleStrategy) RuntimeAware(org.apache.camel.k.RuntimeAware) RouteBuilder(org.apache.camel.builder.RouteBuilder) Resource(org.apache.camel.spi.Resource) RouteTemplateDefinition(org.apache.camel.model.RouteTemplateDefinition) RuntimeCamelException(org.apache.camel.RuntimeCamelException) RouteDefinition(org.apache.camel.model.RouteDefinition) ExtendedCamelContext(org.apache.camel.ExtendedCamelContext) RouteBuilderLifecycleStrategy(org.apache.camel.builder.RouteBuilderLifecycleStrategy) RoutesBuilder(org.apache.camel.RoutesBuilder)

Example 3 with Runtime

use of org.apache.camel.k.Runtime in project camel-k-runtime by apache.

the class PropertiesFunctionsConfigurerTest method testKubernetesFunction.

@Test
public void testKubernetesFunction() {
    Runtime runtime = Runtime.on(new DefaultCamelContext());
    runtime.setProperties("my.property", "{{secret:my-secret/my-property}}");
    new PropertiesConfigurer().accept(runtime);
    assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{secret:my-secret/my-property}}")).isEqualTo("my-secret-property");
    assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{secret:none/my-property:my-default-secret}}")).isEqualTo("my-default-secret");
    CamelContext context = runtime.getCamelContext();
    assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{secret:none/my-property}}")).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("returned null value which is not allowed, from input");
    assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{configmap:my-cm/my-property}}")).isEqualTo("my-cm-property");
    assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{configmap:my-cm/my-property:my-default-cm}}")).isEqualTo("my-default-cm");
    assertThatThrownBy(() -> context.resolvePropertyPlaceholders("{{configmap:none/my-property}}")).isInstanceOf(IllegalArgumentException.class).hasMessageContaining("returned null value which is not allowed, from input");
    assertThat(runtime.getCamelContext().resolvePropertyPlaceholders("{{my.property}}")).isEqualTo("my-secret-property");
}
Also used : CamelContext(org.apache.camel.CamelContext) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Runtime(org.apache.camel.k.Runtime) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Test(org.junit.jupiter.api.Test)

Example 4 with Runtime

use of org.apache.camel.k.Runtime in project camel-k-runtime by apache.

the class CronTest method testCronTimerActivation.

@ParameterizedTest
@MethodSource("parameters")
public void testCronTimerActivation(String code, String cronOverride) throws Exception {
    final Runtime runtime = Runtime.on(new DefaultCamelContext());
    runtime.getRegistry().bind("__camel_k_resolver", new CustomResolver());
    final YamlRoutesBuilderLoader loader = new YamlRoutesBuilderLoader();
    loader.setCamelContext(runtime.getCamelContext());
    loader.start();
    final CronSourceLoaderInterceptor interceptor = new CronSourceLoaderInterceptor();
    interceptor.setRuntime(runtime);
    interceptor.setOverridableComponents(cronOverride);
    final RouteBuilder builder = (RouteBuilder) loader.loadRoutesBuilder(ResourceHelper.fromBytes("my-cron.yaml", code.getBytes(StandardCharsets.UTF_8)));
    builder.addLifecycleInterceptor(interceptor);
    runtime.getCamelContext().addRoutes(builder);
    CountDownLatch termination = new CountDownLatch(1);
    runtime.getCamelContext().addLifecycleStrategy(new LifecycleStrategySupport() {

        @Override
        public void onContextStopped(CamelContext context) {
            termination.countDown();
        }
    });
    MockEndpoint mock = runtime.getCamelContext().getEndpoint("mock:result", MockEndpoint.class);
    mock.expectedMessageCount(1);
    mock.setResultWaitTime(10000);
    runtime.getCamelContext().start();
    mock.assertIsSatisfied();
    termination.await(10, TimeUnit.SECONDS);
    assertThat(termination.getCount()).isZero();
}
Also used : CamelContext(org.apache.camel.CamelContext) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) Runtime(org.apache.camel.k.Runtime) RouteBuilder(org.apache.camel.builder.RouteBuilder) LifecycleStrategySupport(org.apache.camel.support.LifecycleStrategySupport) MockEndpoint(org.apache.camel.component.mock.MockEndpoint) YamlRoutesBuilderLoader(org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader) CountDownLatch(java.util.concurrent.CountDownLatch) DefaultCamelContext(org.apache.camel.impl.DefaultCamelContext) CustomResolver(org.apache.camel.dsl.yaml.deserializers.CustomResolver) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 5 with Runtime

use of org.apache.camel.k.Runtime in project camel-k-runtime by apache.

the class Application method load.

@GET
@Path("/load")
@Produces(MediaType.TEXT_PLAIN)
public String load() throws Exception {
    final String code = "" + "\n- from:" + "\n    uri: \"timer:tick?period=1&delay=60000\"" + "\n    steps:" + "\n      - log: \"${body}\"";
    final YamlRoutesBuilderLoader loader = new YamlRoutesBuilderLoader();
    loader.setCamelContext(context);
    loader.build();
    final Runtime rt = new DelegatingRuntime(runtime) {

        @Override
        public void stop() throws Exception {
            stopped.set(true);
        }
    };
    final CronSourceLoaderInterceptor interceptor = new CronSourceLoaderInterceptor();
    interceptor.setRuntime(rt);
    interceptor.setOverridableComponents("timer");
    final RouteBuilder builder = (RouteBuilder) loader.loadRoutesBuilder(ResourceHelper.fromBytes("my-cron.yaml", code.getBytes(StandardCharsets.UTF_8)));
    builder.addLifecycleInterceptor(interceptor);
    try {
        context.addRoutes(builder);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return "" + context.getRoutesSize();
}
Also used : DelegatingRuntime(org.apache.camel.k.support.DelegatingRuntime) Runtime(org.apache.camel.k.Runtime) RouteBuilder(org.apache.camel.builder.RouteBuilder) DelegatingRuntime(org.apache.camel.k.support.DelegatingRuntime) CronSourceLoaderInterceptor(org.apache.camel.k.cron.CronSourceLoaderInterceptor) YamlRoutesBuilderLoader(org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

Runtime (org.apache.camel.k.Runtime)5 RouteBuilder (org.apache.camel.builder.RouteBuilder)3 CamelContext (org.apache.camel.CamelContext)2 ExtendedCamelContext (org.apache.camel.ExtendedCamelContext)2 RoutesBuilder (org.apache.camel.RoutesBuilder)2 YamlRoutesBuilderLoader (org.apache.camel.dsl.yaml.YamlRoutesBuilderLoader)2 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)2 Collection (java.util.Collection)1 List (java.util.List)1 CountDownLatch (java.util.concurrent.CountDownLatch)1 GET (javax.ws.rs.GET)1 Path (javax.ws.rs.Path)1 Produces (javax.ws.rs.Produces)1 RuntimeCamelException (org.apache.camel.RuntimeCamelException)1 RouteBuilderLifecycleStrategy (org.apache.camel.builder.RouteBuilderLifecycleStrategy)1 MockEndpoint (org.apache.camel.component.mock.MockEndpoint)1 CustomResolver (org.apache.camel.dsl.yaml.deserializers.CustomResolver)1 RuntimeAware (org.apache.camel.k.RuntimeAware)1 Source (org.apache.camel.k.Source)1 SourceDefinition (org.apache.camel.k.SourceDefinition)1