Java 类org.apache.camel.model.RouteDefinition 实例源码

项目:drinkwater-java    文件:TraceRouteBuilder.java   
public static ProcessorDefinition addServerReceivedTracing(IDrinkWaterService service,
                                                       RouteDefinition routeDefinition,
                                                       Method method) {
    ProcessorDefinition answer = routeDefinition;
    if (!service.getConfiguration().getIsTraceEnabled()) {
        return answer;
    }

    answer = routeDefinition
            .setHeader(BeanOperationName)
            .constant(Operation.of(method))
            .to(ROUTE_serverReceivedEvent);


    return answer;
}
项目:drinkwater-java    文件:TraceRouteBuilder.java   
public static RouteDefinition addMethodInvokedStartTrace(
        IDrinkWaterService service,
        RouteDefinition routeDefinition,
        Operation operation){
    RouteDefinition answer = routeDefinition;
    if (!service.getConfiguration().getIsTraceEnabled()) {
        return answer;
    }

    answer = routeDefinition
            .setHeader(BeanOperationName)
            .constant(operation)
            .to(ROUTE_MethodInvokedStartEvent);


    return answer;
}
项目:drinkwater-java    文件:RouteBuilders.java   
public static RouteBuilder mapBeanClassRoutes(DrinkWaterApplication app, Service service) {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                List<Method> methods = javaslang.collection.List.of(service.getConfiguration().getServiceClass().getDeclaredMethods());

                // create an instance of the bean
                Object beanToUse = BeanFactory.createBeanClass(app, service.getConfiguration(), service);

                for (Method m : methods) {
                    if (Modifier.isPublic(m.getModifiers())) {
                        RouteDefinition def = from("direct:" + formatBeanMethodRoute(m));
                        def = addMethodInvokedStartTrace(service, def, Operation.of(m));
                        def.bean(beanToUse, formatBeanEndpointRoute(m), true);
                        addMethodInvokedEndTrace(service, def);

                    }
                }
            }
        };
    }
项目:fabric8-forge    文件:CamelXmlHelper.java   
protected static List<ContextDto> parseCamelContexts(CamelCatalog camelCatalog, File xmlFile) throws Exception {
    List<ContextDto> camelContexts = new ArrayList<>();

    RouteXml routeXml = new RouteXml();
    XmlModel xmlModel = routeXml.unmarshal(xmlFile);

    // TODO we don't handle multiple contexts inside an XML file!
    CamelContextFactoryBean contextElement = xmlModel.getContextElement();
    String name = contextElement.getId();
    List<RouteDefinition> routeDefs = contextElement.getRoutes();
    ContextDto context = new ContextDto(name);
    camelContexts.add(context);
    String key = name;
    if (Strings.isNullOrBlank(key)) {
        key = "_camelContext" + camelContexts.size();
    }
    context.setKey(key);
    List<NodeDto> routes = createRouteDtos(camelCatalog, routeDefs, context);
    context.setChildren(routes);
    return camelContexts;
}
项目:fabric8-forge    文件:CamelXmlHelper.java   
protected static List<NodeDto> createRouteDtos(CamelCatalog camelCatalog, List<RouteDefinition> routeDefs, ContextDto context) {
    List<NodeDto> answer = new ArrayList<>();
    Map<String, Integer> nodeCounts = new HashMap<>();
    for (RouteDefinition def : routeDefs) {
        RouteDto route = new RouteDto();
        route.setId(def.getId());
        route.setLabel(CamelModelHelper.getDisplayText(def));
        route.setDescription(CamelModelHelper.getDescription(def));
        answer.add(route);
        route.defaultKey(context, nodeCounts);

        addInputs(camelCatalog, route, def.getInputs());
        addOutputs(camelCatalog, route, def.getOutputs());
    }
    return answer;
}
项目:Camel    文件:AdviceWithIssueTest.java   
public void testAdviceWithInterceptFrom() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptFrom().to("mock:from");
        }
    });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:from").expectedBodiesReceived("World");
    getMockEndpoint("mock:from").expectedHeaderReceived(Exchange.INTERCEPTED_ENDPOINT, "direct://start");

    template.sendBody("direct:start", "World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithTwoRoutesOnExceptionTest.java   
public void testAdviceWithA() throws Exception {
    RouteDefinition route = context.getRouteDefinition("a");
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("mock://a")
                .skipSendToOriginalEndpoint()
                .throwException(new IllegalArgumentException("Forced"));
        }
    });

    getMockEndpoint("mock:a").expectedMessageCount(0);
    getMockEndpoint("mock:error").expectedMessageCount(1);
    getMockEndpoint("mock:error").message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(IllegalArgumentException.class);

    template.sendBody("direct:a", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:RouteScopedErrorHandlerAndOnExceptionTest.java   
public void testOnException() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*")
                .skipSendToOriginalEndpoint()
                .throwException(new ConnectException("Forced"));
        }
    });

    getMockEndpoint("mock:local").expectedMessageCount(0);
    getMockEndpoint("mock:seda").expectedMessageCount(0);
    // we fail all redeliveries so after that we send to mock:exhausted
    getMockEndpoint("mock:exhausted").expectedMessageCount(1);

    try {
        template.sendBody("direct:start", "Hello World");
        fail("Should thrown an exception");
    } catch (CamelExecutionException e) {
        ConnectException cause = assertIsInstanceOf(ConnectException.class, e.getCause());
        assertEquals("Forced", cause.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:ValidateIdTest.java   
public void testValidateId() throws Exception {
    getMockEndpoint("mock:result").expectedMessageCount(1);

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();

    RouteDefinition route = context.getRouteDefinition("myRoute");
    assertNotNull(route);

    // mock:result should be the only with the result as id
    assertTrue(route.getOutputs().get(0).getId().equals("myValidate"));
    assertFalse(route.getOutputs().get(1).getId().equals("result"));
    assertTrue(route.getOutputs().get(2).getId().equals("result"));
    assertTrue(route.getOutputs().get(3).getId().equals("after"));
}
项目:Camel    文件:RouteScopedOnExceptionWithInterceptSendToEndpointIssueTest.java   
public void testIssue() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*")
                .skipSendToOriginalEndpoint()
                .throwException(new ConnectException("Forced"));
        }
    });

    getMockEndpoint("mock:global").expectedMessageCount(0);
    getMockEndpoint("mock:seda").expectedMessageCount(0);
    // we fail all redeliveries so after that we send to mock:exhausted
    getMockEndpoint("mock:exhausted").expectedMessageCount(1);

    try {
        template.sendBody("direct:start", "Hello World");
        fail("Should thrown an exception");
    } catch (CamelExecutionException e) {
        ConnectException cause = assertIsInstanceOf(ConnectException.class, e.getCause());
        assertEquals("Forced", cause.getMessage());
    }

    assertMockEndpointsSatisfied();
}
项目:incubator-tamaya-sandbox    文件:TamayaPropertyResolverTest.java   
@Test
public void testXmlDSL() throws Exception {
    CamelContext camelContext = new DefaultCamelContext();
    // This is normally done by the Spring implemented registry, we keep it simple here...
    TamayaPropertiesComponent props = new TamayaPropertiesComponent();
    props.setTamayaOverrides(true);
    camelContext.addComponent("properties", props);
    // Read routes from XML DSL
    InputStream is = getClass().getResourceAsStream("/META-INF/routes.xml");
    RoutesDefinition routes = camelContext.loadRoutesDefinition(is);
    for(RouteDefinition def: routes.getRoutes()) {
        camelContext.addRouteDefinition(def);
    }
    camelContext.start();
    Greeter greeter = new ProxyBuilder(camelContext).endpoint("direct:hello1").build(Greeter.class);
    assertEquals("Good Bye from Apache Tamaya!", greeter.greet());
    greeter = new ProxyBuilder(camelContext).endpoint("direct:hello2").build(Greeter.class);
    assertEquals("Good Bye from Apache Tamaya!", greeter.greet());
    greeter = new ProxyBuilder(camelContext).endpoint("direct:hello3").build(Greeter.class);
    assertEquals("Good Bye from Apache Tamaya!", greeter.greet());
}
项目:drinkwater-java    文件:TraceRouteBuilder.java   
public static ProcessorDefinition addServerReceivedTracing(IDrinkWaterService service,
                                                       RouteDefinition routeDefinition,
                                                       Method method) {
    ProcessorDefinition answer = routeDefinition;
    if (!service.getConfiguration().getIsTraceEnabled()) {
        return answer;
    }

    answer = routeDefinition
            .setHeader(BeanOperationName)
            .constant(Operation.of(method))
            .to(ROUTE_serverReceivedEvent);


    return answer;
}
项目:Camel    文件:CamelContextAddRouteDefinitionsFromXmlTest.java   
public void testAddRouteDefinitionsFromXmlIsPrepared() throws Exception {
    RouteDefinition route = loadRoute("route1.xml");
    assertNotNull(route);

    assertEquals("foo", route.getId());
    assertEquals(0, context.getRoutes().size());

    context.addRouteDefinition(route);
    assertEquals(1, context.getRoutes().size());
    assertTrue("Route should be started", context.getRouteStatus("foo").isStarted());

    // should be prepared, check parents has been set
    assertNotNull("Parent should be set on outputs");
    route = context.getRouteDefinition("foo");
    for (ProcessorDefinition<?> output : route.getOutputs()) {
        assertNotNull("Parent should be set on output", output.getParent());
        assertEquals(route, output.getParent());
    }
}
项目:drinkwater-java    文件:RouteBuilders.java   
public static RouteBuilder mapBeanClassRoutes(DrinkWaterApplication app, Service service) {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                List<Method> methods = javaslang.collection.List.of(service.getConfiguration().getServiceClass().getDeclaredMethods());

                // create an instance of the bean
                Object beanToUse = BeanFactory.createBeanClass(app, service.getConfiguration(), service);

                for (Method m : methods) {
                    if (Modifier.isPublic(m.getModifiers())) {
                        RouteDefinition def = from("direct:" + formatBeanMethodRoute(m));
                        def = addMethodInvokedStartTrace(service, def, Operation.of(m));
                        def.bean(beanToUse, formatBeanEndpointRoute(m), true);
                        addMethodInvokedEndTrace(service, def);

                    }
                }
            }
        };
    }
项目:beyondj    文件:SystemGatewayActor.java   
private void removeUrlFromCamelRoutes(ApplicationOptions options) throws Exception {
    String servicePath = options.getContextPath();
    String toUri = null;

    if (options.isRequiresSSL()) {
        toUri = "https://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getHttpsPort() +
                options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true";
    } else {
        toUri = "http://" + InetAddress.getLocalHost().getHostAddress() + ":" + options.getPort() +
                options.getContextPath() + "?bridgeEndpoint=true&throwExceptionOnFailure=false&matchOnUriPrefix=true";
    }
    final InputStream in = com.beyondj.gateway.support.JsonRuleBaseBuilder.newRuleBase().rule(servicePath, toUri).inputStream();

    ModelCamelContext modelCamelContext = (ModelCamelContext) camelContext;
    RouteDefinition routeDefinition = modelCamelContext.getRouteDefinition(GatewayRouter.GATEWAY_ROUTE_ID);

    if (routeDefinition == null) {
        int port = Integer.valueOf(
                config.getProperty(SYSTEM_GATEWAY_ROUTE_PORT));
        camelContext.addRoutes(new GatewayRouter(coreMetricsService, scalingDataService, port));
    }

    LoadBalancerDefinition loadBalancerDefinition = getLoadBalancerDefinition(options);
    Map<String, HttpProxyRule> rules = JsonRuleBaseReader.parseJson(loadBalancerDefinition, in);
    gatewayRulesService.removeGatewayRules(rules);
}
项目:Camel    文件:XmlCdiBeanFactory.java   
private SyntheticBean<?> routeContextBean(RouteContextDefinition definition, URL url) {
    requireNonNull(definition.getId(),
        () -> format("Missing [%s] attribute for imported bean [%s] from resource [%s]",
            "id", "routeContext", url));

    return new SyntheticBean<>(manager,
        new SyntheticAnnotated(List.class,
            Stream.of(List.class, new ListParameterizedType(RouteDefinition.class))
                .collect(toSet()),
            ANY, NamedLiteral.of(definition.getId())),
        List.class,
        new SyntheticInjectionTarget<>(definition::getRoutes), bean ->
            "imported route context with "
            + "id [" + definition.getId() + "] "
            + "from resource [" + url + "] "
            + "with qualifiers " + bean.getQualifiers());
}
项目:Camel    文件:BacklogTracer.java   
private boolean shouldTracePattern(ProcessorDefinition<?> definition) {
    for (String pattern : patterns) {
        // match either route id, or node id
        String id = definition.getId();
        // use matchPattern method from endpoint helper that has a good matcher we use in Camel
        if (EndpointHelper.matchPattern(id, pattern)) {
            return true;
        }
        RouteDefinition route = ProcessorDefinitionHelper.getRoute(definition);
        if (route != null) {
            id = route.getId();
            if (EndpointHelper.matchPattern(id, pattern)) {
                return true;
            }
        }
    }
    // not matched the pattern
    return false;
}
项目:Camel    文件:RouteScopedErrorHandlerAndOnExceptionTest.java   
public void testErrorHandler() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("seda:*")
                .skipSendToOriginalEndpoint()
                .throwException(new FileNotFoundException("Forced"));
        }
    });

    getMockEndpoint("mock:local").expectedMessageCount(1);
    getMockEndpoint("mock:seda").expectedMessageCount(0);
    getMockEndpoint("mock:exhausted").expectedMessageCount(0);

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:DefaultManagementLifecycleStrategy.java   
public void onRouteContextCreate(RouteContext routeContext) {
    if (!initialized) {
        return;
    }

    // Create a map (ProcessorType -> PerformanceCounter)
    // to be passed to InstrumentationInterceptStrategy.
    Map<ProcessorDefinition<?>, PerformanceCounter> registeredCounters =
            new HashMap<ProcessorDefinition<?>, PerformanceCounter>();

    // Each processor in a route will have its own performance counter.
    // These performance counter will be embedded to InstrumentationProcessor
    // and wrap the appropriate processor by InstrumentationInterceptStrategy.
    RouteDefinition route = routeContext.getRoute();

    // register performance counters for all processors and its children
    for (ProcessorDefinition<?> processor : route.getOutputs()) {
        registerPerformanceCounters(routeContext, processor, registeredCounters);
    }

    // set this managed intercept strategy that executes the JMX instrumentation for performance metrics
    // so our registered counters can be used for fine grained performance instrumentation
    routeContext.setManagedInterceptStrategy(new InstrumentationInterceptStrategy(registeredCounters, wrappedProcessors));
}
项目:Camel    文件:DefaultManagementLifecycleStrategy.java   
/**
 * Removes the wrapped processors for the given routes, as they are no longer in use.
 * <p/>
 * This is needed to avoid accumulating memory, if a lot of routes is being added and removed.
 *
 * @param routes the routes
 */
private void removeWrappedProcessorsForRoutes(Collection<Route> routes) {
    // loop the routes, and remove the route associated wrapped processors, as they are no longer in use
    for (Route route : routes) {
        String id = route.getId();

        Iterator<KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor>> it = wrappedProcessors.values().iterator();
        while (it.hasNext()) {
            KeyValueHolder<ProcessorDefinition<?>, InstrumentationProcessor> holder = it.next();
            RouteDefinition def = ProcessorDefinitionHelper.getRoute(holder.getKey());
            if (def != null && id.equals(def.getId())) {
                it.remove();
            }
        }
    }

}
项目:Camel    文件:CamelContextAddRouteDefinitionsFromXmlTest.java   
public void testAddRouteDefinitionsFromXml2() throws Exception {
    RouteDefinition route = loadRoute("route2.xml");
    assertNotNull(route);

    assertEquals("foo", route.getId());
    assertEquals(0, context.getRoutes().size());

    context.addRouteDefinition(route);
    assertEquals(1, context.getRoutes().size());
    assertTrue("Route should be stopped", context.getRouteStatus("foo").isStopped());

    context.startRoute("foo");
    assertTrue("Route should be started", context.getRouteStatus("foo").isStarted());

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    template.sendBody("direct:start", "Hello World");
    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithTasks.java   
/**
 * Create iterator which walks the route, and only returns nodes which matches the given set of criteria.
 *
 * @param route        the route
 * @param matchBy      match by which must match
 * @param selectFirst  optional to select only the first
 * @param selectLast   optional to select only the last
 * @param selectFrom   optional to select index/range
 * @param selectTo     optional to select index/range
 * @param maxDeep      maximum levels deep (is unbounded by default)
 *
 * @return the iterator
 */
private static Iterator<ProcessorDefinition<?>> createMatchByIterator(final RouteDefinition route, final MatchBy matchBy,
                                                           final boolean selectFirst, final boolean selectLast,
                                                           final int selectFrom, final int selectTo, int maxDeep) {

    // first iterator and apply match by
    List<ProcessorDefinition<?>> matched = new ArrayList<ProcessorDefinition<?>>();

    @SuppressWarnings("rawtypes")
    Iterator<ProcessorDefinition> itAll = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class, maxDeep);
    while (itAll.hasNext()) {
        ProcessorDefinition<?> next = itAll.next();
        if (matchBy.match(next)) {
            matched.add(next);
        }
    }

    // and then apply the selector iterator
    return createSelectorIterator(matched, selectFirst, selectLast, selectFrom, selectTo);
}
项目:Camel    文件:CamelContextHelper.java   
/**
 * Checks if any of the Camel routes is using an EIP with the given name
 *
 * @param camelContext  the Camel context
 * @param name          the name of the EIP
 * @return <tt>true</tt> if in use, <tt>false</tt> if not
 */
public static boolean isEipInUse(CamelContext camelContext, String name) {
    for (RouteDefinition route : camelContext.getRouteDefinitions()) {
        for (FromDefinition from : route.getInputs()) {
            if (name.equals(from.getShortName())) {
                return true;
            }
        }
        Iterator<ProcessorDefinition> it = ProcessorDefinitionHelper.filterTypeInOutputs(route.getOutputs(), ProcessorDefinition.class);
        while (it.hasNext()) {
            ProcessorDefinition def = it.next();
            if (name.equals(def.getShortName())) {
                return true;
            }
        }
    }
    return false;
}
项目:Camel    文件:AdviceWithIssueTest.java   
public void testAdviceWithOnCompletion() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            onCompletion().to("mock:done");
        }
    });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:done").expectedBodiesReceived("Hello World");

    template.sendBody("direct:start", "World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithTwoRoutesOnExceptionTest.java   
public void testAdviceWithB() throws Exception {
    RouteDefinition route = context.getRouteDefinition("b");
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("mock://b")
                .skipSendToOriginalEndpoint()
                .throwException(new IllegalArgumentException("Forced"));
        }
    });

    getMockEndpoint("mock:b").expectedMessageCount(0);
    getMockEndpoint("mock:error").expectedMessageCount(1);
    getMockEndpoint("mock:error").message(0).exchangeProperty(Exchange.EXCEPTION_CAUGHT).isInstanceOf(IllegalArgumentException.class);

    template.sendBody("direct:b", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithTwoRoutesTest.java   
public void testAdviceWithB() throws Exception {
    RouteDefinition route = context.getRouteDefinition("b");
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("mock://b")
                .skipSendToOriginalEndpoint()
                .to("mock:detour");
        }
    });

    getMockEndpoint("mock:b").expectedMessageCount(0);
    getMockEndpoint("mock:detour").expectedMessageCount(1);

    template.sendBody("direct:b", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithCBRTest.java   
public void testAdviceCBR() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById("foo").after().to("mock:foo2");
            weaveById("bar").after().to("mock:bar2");
        }
    });

    getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:foo2").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:bar").expectedBodiesReceived("Bye World");
    getMockEndpoint("mock:bar2").expectedBodiesReceived("Bye World");
    getMockEndpoint("mock:baz").expectedBodiesReceived("Hi World");

    template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123");
    template.sendBodyAndHeader("direct:start", "Bye World", "bar", "123");
    template.sendBody("direct:start", "Hi World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:RouteBuilder.java   
@SuppressWarnings("deprecation")
protected void checkInitialized() throws Exception {
    if (initialized.compareAndSet(false, true)) {
        // Set the CamelContext ErrorHandler here
        ModelCamelContext camelContext = getContext();
        if (camelContext.getErrorHandlerBuilder() != null) {
            setErrorHandlerBuilder(camelContext.getErrorHandlerBuilder());
        }
        configure();
        // mark all route definitions as custom prepared because
        // a route builder prepares the route definitions correctly already
        for (RouteDefinition route : getRouteCollection().getRoutes()) {
            route.markPrepared();
        }
    }
}
项目:Camel    文件:AdviceWithCBRTest.java   
public void testAdviceToStringCBR() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveByToString("To[mock:foo]").after().to("mock:foo2");
            weaveByToString("To[mock:bar]").after().to("mock:bar2");
        }
    });

    getMockEndpoint("mock:foo").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:foo2").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:bar").expectedBodiesReceived("Bye World");
    getMockEndpoint("mock:bar2").expectedBodiesReceived("Bye World");
    getMockEndpoint("mock:baz").expectedBodiesReceived("Hi World");

    template.sendBodyAndHeader("direct:start", "Hello World", "foo", "123");
    template.sendBodyAndHeader("direct:start", "Bye World", "bar", "123");
    template.sendBody("direct:start", "Hi World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithOnExceptionTest.java   
public void testAdviceWithOnException() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            weaveById("b").after().to("mock:result");
        }
    });
    context.start();

    getMockEndpoint("mock:a").expectedMessageCount(1);
    getMockEndpoint("mock:b").expectedMessageCount(1);
    getMockEndpoint("mock:result").expectedMessageCount(1);

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:CamelContextAddRouteDefinitionsFromXmlTest.java   
public void testRemoveRouteDefinitionsFromXml() throws Exception {
    RouteDefinition route = loadRoute("route1.xml");
    assertNotNull(route);

    assertEquals("foo", route.getId());
    assertEquals(0, context.getRoutes().size());

    context.addRouteDefinition(route);
    assertEquals(1, context.getRouteDefinitions().size());
    assertEquals(1, context.getRoutes().size());
    assertTrue("Route should be started", context.getRouteStatus("foo").isStarted());

    context.removeRouteDefinition(route);
    assertEquals(0, context.getRoutes().size());
    assertNull(context.getRouteStatus("foo"));

    assertEquals(0, context.getRouteDefinitions().size());
}
项目:Camel    文件:XmlConfigTestSupport.java   
protected void assertValidContext(CamelContext context) {
    assertNotNull("No context found!", context);

    List<RouteDefinition> routes = ((ModelCamelContext)context).getRouteDefinitions();
    LOG.debug("Found routes: " + routes);

    assertEquals("One Route should be found", 1, routes.size());

    for (RouteDefinition route : routes) {
        List<FromDefinition> inputs = route.getInputs();
        assertEquals("Number of inputs", 1, inputs.size());
        FromDefinition fromType = inputs.get(0);
        assertEquals("from URI", "seda:test.a", fromType.getUri());

        List<?> outputs = route.getOutputs();
        assertEquals("Number of outputs", 1, outputs.size());
    }
}
项目:Camel    文件:HttpInterceptSendToEndpointTest.java   
@Test
public void testHttpInterceptSendToEndpoint() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            interceptSendToEndpoint("http*").to("mock:http").skipSendToOriginalEndpoint();
        }
    });

    getMockEndpoint("mock:http").expectedMessageCount(1);

    template.sendBody("direct:start", "Hello World");

    assertMockEndpointsSatisfied();
}
项目:Camel    文件:AdviceWithIssueTest.java   
public void testAdviceWithOnException() throws Exception {
    RouteDefinition route = context.getRouteDefinitions().get(0);
    route.adviceWith(context, new AdviceWithRouteBuilder() {
        @Override
        public void configure() throws Exception {
            onException(IllegalArgumentException.class)
                    .handled(true)
                    .to("mock:error");
        }
    });

    getMockEndpoint("mock:result").expectedBodiesReceived("Hello World");
    getMockEndpoint("mock:error").expectedBodiesReceived("Kaboom");

    template.sendBody("direct:start", "World");
    template.sendBody("direct:start", "Kaboom");

    assertMockEndpointsSatisfied();
}
项目:drinkwater-java    文件:TraceRouteBuilder.java   
public static RouteDefinition addServerReceivedTracing(IDrinkWaterService service,
                                                           RouteDefinition routeDefinition) {
    RouteDefinition answer = routeDefinition;
    if (!service.getConfiguration().getIsTraceEnabled()) {
        return answer;
    }

    answer = routeDefinition
            .setHeader(BeanOperationName)
            .method(ExtractHttpMethodFromExchange.class)
            .to(ROUTE_serverReceivedEvent);


    return answer;
}
项目:drinkwater-java    文件:RouteBuilders.java   
public static RouteBuilder mapHttpProxyRoutes(DrinkWaterApplication app, Service service) {

        return new RouteBuilder() {
            @Override
            public void configure() throws Exception {

                boolean useSessionManager = service.safeLookupProperty(Boolean.class, "useSessionManager:false", false);
                String sessionManagerOption = useSessionManager? "&sessionSupport=true":"";

                String frontEndpoint = service.lookupProperty("proxy.endpoint");

                String destinationEndpoint = service.lookupProperty("destination.endpoint");

                if (frontEndpoint == null || destinationEndpoint == null) {
                    throw new RuntimeException("could not find proxy and destination endpoint from config");
                }

                String handlers = getHandlersForJetty(service);
                String handlersConfig = handlers == null ? "":"&handlers="+handlers;

                addExceptionTracing(service, Exception.class, this);

                RouteDefinition choice =
                        from("jetty:" + frontEndpoint + "?matchOnUriPrefix=true&enableMultipartFilter=false"
                                + handlersConfig + sessionManagerOption);

                choice = addServerReceivedTracing(service, choice);
                choice = choice.to("jetty:" + destinationEndpoint + "?bridgeEndpoint=true&amp;throwExceptionOnFailure=true");
                addServerSentTracing(service, choice);
            }
        };
    }
项目:drinkwater-java    文件:RouteBuilders.java   
private static RouteDefinition enableCorsOnRoute(RouteDefinition route, Service service) {

        String allowedHeaders = RestHelper.getAllowedCorsheaders(service);
        return route
                .setHeader("Access-Control-Allow-Origin", constant("*"))
                .setHeader("Access-Control-Allow-Methods", constant("GET, HEAD, POST, PUT, DELETE, TRACE, OPTIONS, CONNECT, PATCH"))
                .setHeader("Access-Control-Allow-Headers", constant(allowedHeaders))
                .setHeader("Allow", constant("GET, OPTIONS, POST, PATCH"));

    }
项目:fabric8-forge    文件:RouteXml.java   
/**
 * Loads the given file then updates the route definitions from the given list then stores the file again
 */
public void marshal(File file, final List<RouteDefinition> routeDefinitionList) throws Exception {
    marshal(file, new Model2Model() {
        @Override
        public XmlModel transform(XmlModel model) {
            copyRoutesToElement(routeDefinitionList, model.getContextElement());
            return model;
        }
    });
}
项目:fabric8-forge    文件:StandAloneRoutesXmlMarshalToTextTest.java   
@Test
public void testMarshalToText() throws Exception {
    String text = FileCopyUtils.copyToString(new FileReader(new File(getBaseDir(), "src/test/resources/routes.xml")));

    RouteDefinition route = new RouteDefinition();
    route.from("seda:new.in").to("seda:new.out");

    String actual = tool.marshalToText(text, Arrays.asList(route));
    System.out.println("Got " + actual);

    assertTrue("Missing seda:new.in for: " + actual, actual.contains("seda:new.in"));
}
项目:fabric8-forge    文件:PreserveCommentTest.java   
@Test
public void testCommentsBeforeRoutePreserved() throws Exception {
    XmlModel x = assertRoundTrip("src/test/resources/commentBeforeRoute.xml", 2);

    RouteDefinition route1 = x.getRouteDefinitionList().get(1);
    assertEquals("route4", route1.getId());
    DescriptionDefinition desc = route1.getDescription();
    assertNotNull(desc);
    assertEquals("route4 description\ncomment about route4", desc.getText());
}