org.apache.camel.Processor Java Examples

The following examples show how to use org.apache.camel.Processor. 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: HttpServer.java    From camelinaction2 with Apache License 2.0 7 votes vote down vote up
public void server() throws Exception {
    CamelContext camel = new DefaultCamelContext();
    camel.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("jetty:" + url)
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        String body = exchange.getIn().getBody(String.class);

                        System.out.println("Received message: " + body);

                        if (body != null && body.contains("Kabom")) {
                            throw new Exception("ILLEGAL DATA");
                        }
                        exchange.getOut().setBody("OK");
                    }
                });
        }
    });
    camel.start();

}
 
Example #2
Source File: KnativeHttpSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Removes cloud event headers at the end of the processing.
 */
public static Processor withoutCloudEventHeaders(Processor delegate, CloudEvent ce) {
    return new DelegateAsyncProcessor(delegate) {
        @Override
        public boolean process(Exchange exchange, AsyncCallback callback) {
            return processor.process(exchange, doneSync -> {
                final Message message = exchange.getMessage();

                // remove CloudEvent headers
                for (CloudEvent.Attribute attr : ce.attributes()) {
                    message.removeHeader(attr.http());
                }

                callback.done(doneSync);
            });
        }
    };
}
 
Example #3
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService, boolean streaming,
                          boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork,
                          boolean parallelAggregate) {
    notNull(camelContext, "camelContext");
    this.camelContext = camelContext;
    this.processors = processors;
    this.aggregationStrategy = aggregationStrategy;
    this.executorService = executorService;
    this.shutdownExecutorService = shutdownExecutorService;
    this.streaming = streaming;
    this.stopOnException = stopOnException;
    // must enable parallel if executor service is provided
    this.parallelProcessing = parallelProcessing || executorService != null;
    this.timeout = timeout;
    this.onPrepare = onPrepare;
    this.shareUnitOfWork = shareUnitOfWork;
    this.parallelAggregate = parallelAggregate;
}
 
Example #4
Source File: original.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
/**
 * Strategy to create the unit of work to be used for the sub route
 *
 * @param routeContext the route context
 * @param processor    the processor
 * @param exchange     the exchange
 * @return the unit of work processor
 */
protected Processor createUnitOfWorkProcessor(RouteContext routeContext, Processor processor, Exchange exchange) {
    String routeId = routeContext != null ? routeContext.getRoute().idOrCreate(routeContext.getCamelContext().getNodeIdFactory()) : null;
    CamelInternalProcessor internal = new CamelInternalProcessor(processor);

    // and wrap it in a unit of work so the UoW is on the top, so the entire route will be in the same UoW
    UnitOfWork parent = exchange.getProperty(Exchange.PARENT_UNIT_OF_WORK, UnitOfWork.class);
    if (parent != null) {
        internal.addAdvice(new CamelInternalProcessor.ChildUnitOfWorkProcessorAdvice(routeId, parent));
    } else {
        internal.addAdvice(new CamelInternalProcessor.UnitOfWorkProcessorAdvice(routeId));
    }

    // and then in route context so we can keep track which route this is at runtime
    if (routeContext != null) {
        internal.addAdvice(new CamelInternalProcessor.RouteContextAdvice(routeContext));
    }
    return internal;
}
 
Example #5
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@link ProcessorExchangePair} which holds the processor and exchange to be send out.
 * <p/>
 * You <b>must</b> use this method to create the instances of {@link ProcessorExchangePair} as they
 * need to be specially prepared before use.
 *
 * @param index        the index
 * @param processor    the processor
 * @param exchange     the exchange
 * @param routeContext the route context
 * @return prepared for use
 */
protected ProcessorExchangePair createProcessorExchangePair(int index, Processor processor, Exchange exchange,
                                                            RouteContext routeContext) {
    Processor prepared = processor;

    // set property which endpoint we send to
    setToEndpoint(exchange, prepared);

    // rework error handling to support fine grained error handling
    prepared = createErrorHandler(routeContext, exchange, prepared);

    // invoke on prepare on the exchange if specified
    if (onPrepare != null) {
        try {
            onPrepare.process(exchange);
        } catch (Exception e) {
            exchange.setException(e);
        }
    }
    return new DefaultProcessorExchangePair(index, processor, prepared, exchange);
}
 
Example #6
Source File: ServletIntegrationTest.java    From wildfly-camel with Apache License 2.0 6 votes vote down vote up
@Test
public void testServletRoute() throws Exception {

    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("servlet://hello?matchOnUriPrefix=true")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    exchange.getOut().setBody("Hello Kermit");
                }
            });
        }
    });

    camelctx.start();
    try {
        HttpResponse result = HttpRequest.get("http://localhost:8080/camel/services/hello").getResponse();
        Assert.assertEquals("Hello Kermit", result.getBody());
    } finally {
        camelctx.close();
    }
}
 
Example #7
Source File: KnativeHttpSupport.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
/**
 * Remap camel headers to cloud event http headers.
 */
public static Processor remapCloudEventHeaders(Processor delegate, CloudEvent ce) {
    return new DelegateAsyncProcessor(delegate) {
        @Override
        public boolean process(Exchange exchange, AsyncCallback callback) {
            return processor.process(exchange, doneSync -> {
                final Message message = exchange.getMessage();

                // remap CloudEvent camel --> http
                for (CloudEvent.Attribute attr : ce.attributes()) {
                    Object value = message.getHeader(attr.id());
                    if (value != null) {
                        message.setHeader(attr.http(), value);
                    }
                }

                callback.done(doneSync);
            });
        }
    };
}
 
Example #8
Source File: FileRollbackTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:confirm")
                .process(new Processor() {
                    public void process(Exchange exchange) throws Exception {
                        // register the FileRollback as Synchronization
                        exchange.getUnitOfWork().addSynchronization(new FileRollback());

                        // this can be done a bit easier by using:
                        // exchange.addOnCompletion(new FileRollback());
                    }
                })
                // or use Java 8 style with lambda instead of the inlined processor above
                // .process(e -> e.addOnCompletion(new FileRollback()))
                .bean(OrderService.class, "createMail")
                .log("Saving mail backup file")
                .to("file:target/mail/backup")
                .log("Trying to send mail to ${header.to}")
                .bean(OrderService.class, "sendMail")
                .log("Mail sent to ${header.to}");
        }
    };
}
 
Example #9
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService, boolean streaming,
                          boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork,
                          boolean parallelAggregate) {
    notNull(camelContext, "camelContext");
    this.camelContext = camelContext;
    this.processors = processors;
    this.aggregationStrategy = aggregationStrategy;
    this.executorService = executorService;
    this.shutdownExecutorService = shutdownExecutorService;
    this.streaming = streaming;
    this.stopOnException = stopOnException;
    // must enable parallel if executor service is provided
    this.parallelProcessing = parallelProcessing || executorService != null;
    this.timeout = timeout;
    this.onPrepare = onPrepare;
    this.shareUnitOfWork = shareUnitOfWork;
    this.parallelAggregate = parallelAggregate;
}
 
Example #10
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
protected Iterable<ProcessorExchangePair> createProcessorExchangePairs(Exchange exchange) throws Exception {
    List<ProcessorExchangePair> result = new ArrayList<ProcessorExchangePair>(processors.size());

    int index = 0;
    for (Processor processor : processors) {
        // copy exchange, and do not share the unit of work
        Exchange copy = ExchangeHelper.createCorrelatedCopy(exchange, false);

        // if we share unit of work, we need to prepare the child exchange
        if (isShareUnitOfWork()) {
            prepareSharedUnitOfWork(copy, exchange);
        }

        // and add the pair
        RouteContext routeContext = exchange.getUnitOfWork() != null ? exchange.getUnitOfWork().getRouteContext() : null;
        result.add(createProcessorExchangePair(index++, processor, copy, routeContext));
    }

    if (exchange.getException() != null) {
        // force any exceptions occurred during creation of exchange paris to be thrown
        // before returning the answer;
        throw exchange.getException();
    }

    return result;
}
 
Example #11
Source File: MirandaTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testMiranda() throws Exception {
    context.setTracing(true);

    MockEndpoint mock = getMockEndpoint("mock:miranda");
    mock.expectedBodiesReceived("ID=123");
    mock.whenAnyExchangeReceived(new Processor() {
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody("ID=123,STATUS=IN PROGRESS");
        }
    });

    String out = template.requestBody("http://localhost:9080/service/order?id=123", null, String.class);
    assertEquals("IN PROGRESS", out);

    assertMockEndpointsSatisfied();
}
 
Example #12
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the {@link ProcessorExchangePair} which holds the processor and exchange to be send out.
 * <p/>
 * You <b>must</b> use this method to create the instances of {@link ProcessorExchangePair} as they
 * need to be specially prepared before use.
 *
 * @param index        the index
 * @param processor    the processor
 * @param exchange     the exchange
 * @param routeContext the route context
 * @return prepared for use
 */
protected ProcessorExchangePair createProcessorExchangePair(int index, Processor processor, Exchange exchange,
                                                            RouteContext routeContext) {
    Processor prepared = processor;

    // set property which endpoint we send to
    setToEndpoint(exchange, prepared);

    // rework error handling to support fine grained error handling
    prepared = createErrorHandler(routeContext, exchange, prepared);

    // invoke on prepare on the exchange if specified
    if (onPrepare != null) {
        try {
            onPrepare.process(exchange);
        } catch (Exception e) {
            exchange.setException(e);
        }
    }
    return new DefaultProcessorExchangePair(index, processor, prepared, exchange);
}
 
Example #13
Source File: SimulateErrorUsingProcessorTest.java    From camelinaction2 with Apache License 2.0 6 votes vote down vote up
@Override
protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            context.setTracing(true);

            errorHandler(defaultErrorHandler()
                    .maximumRedeliveries(5).redeliveryDelay(1000));

            onException(IOException.class).maximumRedeliveries(3)
                    .handled(true)
                    .to("mock:ftp");

            from("direct:file")
                    // simulate an error using a processor to throw the exception
                    .process(new Processor() {
                        public void process(Exchange exchange) throws Exception {
                            throw new ConnectException("Simulated connection error");
                        }
                    })
                    .to("mock:http");
        }
    };
}
 
Example #14
Source File: TracingInterceptStrategy.java    From syndesis with Apache License 2.0 6 votes vote down vote up
@Override
public Processor wrapProcessorInInterceptors(CamelContext context, NamedNode definition, Processor target, Processor nextTarget) throws Exception {
    if (definition instanceof PipelineDefinition) {
        final String id = definition.getId();
        if (ObjectHelper.isEmpty(id)) {
            return target;
        }

        final String stepId = StringHelper.after(id, "step:");
        if (ObjectHelper.isEmpty(stepId)) {
            return target;
        }

        return new EventProcessor(target, stepId);
    }
    return target;
}
 
Example #15
Source File: MyInterceptor.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public Processor wrapProcessorInInterceptors(CamelContext context,
        ProcessorDefinition<?> definition, final Processor target,
        Processor nextTarget) throws Exception {

	return new DelegateAsyncProcessor(new Processor() {

		public void process(Exchange exchange) throws Exception {
			LOG.info("Before the processor...");
			target.process(exchange);
			LOG.info("After the processor...");
		}
	});
}
 
Example #16
Source File: HiWorldEndpoint.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
public Consumer createConsumer(Processor processor) throws Exception {
    // make sure inBody is not set for consumers
    if (inBody != null) {
        throw new IllegalArgumentException("Option inBody is not supported for consumer endpoint");
    }
    final HiWorldConsumer consumer = new HiWorldConsumer(this, processor);
    // also set consumer.* properties
    configureConsumer(consumer);
    return consumer;
}
 
Example #17
Source File: ComponentProxyEndpoint.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public Consumer createConsumer(final Processor processor) throws Exception {
    final Processor beforeConsumer = getBeforeConsumer();
    final Processor afterConsumer = getAfterConsumer();

    // use a pipeline to process before, processor, after in that order
    // create consumer with the pipeline
    final Processor pipeline = Pipeline.newInstance(getCamelContext(), beforeConsumer, processor, afterConsumer);
    final Consumer consumer = endpoint.createConsumer(pipeline);
    configureConsumer(consumer);

    return consumer;
}
 
Example #18
Source File: file_t.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Deprecated
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService,
                          boolean streaming, boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork) {
    this(camelContext, processors, aggregationStrategy, parallelProcessing, executorService, shutdownExecutorService,
            streaming, stopOnException, timeout, onPrepare, shareUnitOfWork, false);
}
 
Example #19
Source File: SAPNetweaverIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testSAPNetweaverEndpointJsonResponse() throws Exception {
    CamelContext camelctx = new DefaultCamelContext();
    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("direct:start")
            .to("sap-netweaver:http://localhost:8080/sap/api");

            from("undertow:http://localhost:8080/sap/api?matchOnUriPrefix=true")
            .process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    String data = TestUtils.getResourceValue(SAPNetweaverIntegrationTest.class, "/flight-data.json");
                    exchange.getMessage().setBody(data);
                }
            });
        }
    });

    camelctx.start();
    try {
        ProducerTemplate producer = camelctx.createProducerTemplate();
        String result = producer.requestBodyAndHeader("direct:start", null, NetWeaverConstants.COMMAND, SAP_COMMAND, String.class);
        Assert.assertTrue(result.contains("PRICE=422.94, CURRENCY=USD"));
    } finally {
        camelctx.close();
    }
}
 
Example #20
Source File: ApiProviderReturnPathCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static Processor statusCodeUpdater(Integer httpResponseCode) {
    return exchange -> {
        //making sure we don't return anything
        exchange.getIn().setBody("");
        if (httpResponseCode != null) {
            exchange.getIn().setHeader(Exchange.HTTP_RESPONSE_CODE, httpResponseCode);
        }
    };
}
 
Example #21
Source File: ComponentProxyEndpoint.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
@SuppressWarnings("PMD.SignatureDeclareThrowsException")
public Producer createProducer() throws Exception {
    final Producer producer = endpoint.createProducer();

    final Processor beforeProducer = getBeforeProducer();
    final Processor afterProducer = getAfterProducer();

    // use a pipeline to process before, producer, after in that order
    // create producer with the pipeline
    final Processor pipeline = Pipeline.newInstance(getCamelContext(), beforeProducer, producer, afterProducer);

    return new ComponentProxyProducer(endpoint, pipeline);
}
 
Example #22
Source File: ApiProviderStartEndpointCustomizer.java    From syndesis with Apache License 2.0 5 votes vote down vote up
@Override
public void customize(ComponentProxyComponent component, Map<String, Object> options) {
    final List<Processor> beforeConsumers = new ArrayList<>(2);
    if (outputDataShape != null && outputDataShape.getKind() == DataShapeKinds.JSON_SCHEMA && outputDataShape.getSpecification() != null) {
        try {
            final JsonNode schema = READER.readTree(outputDataShape.getSpecification());
            Set<String> properties = SimpleJsonSchemaInspector.getProperties(schema);
            Set<String> extraneousProperties = new HashSet<>(properties);
            extraneousProperties.removeAll(Arrays.asList("parameters", "body"));

            if (!properties.isEmpty() && extraneousProperties.isEmpty()) {
                beforeConsumers.add(new HttpRequestWrapperProcessor(schema));
            }
        } catch (IOException e) {
            throw new RuntimeCamelException(e);
        }
    }

    beforeConsumers.add(new HttpMessageToDefaultMessageProcessor());

    // removes all non Syndesis.* headers, this is so the headers that might
    // influence HTTP components in the flow after this connector don't
    // interpret them, for instance the `Host` header is particularly
    // troublesome
    beforeConsumers.add((e) -> e.getIn().removeHeaders("*", Exchange.CONTENT_TYPE, "Syndesis.*"));

    component.setBeforeConsumer(Pipeline.newInstance(context, beforeConsumers));
}
 
Example #23
Source File: SpringCircuitBreakerLoadBalancerTest.java    From camelinaction2 with Apache License 2.0 5 votes vote down vote up
protected Exchange sendMessage(final String endpoint, final Object body) throws Exception {
    return template.send(endpoint, new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody(body);
        }
    });
}
 
Example #24
Source File: HipchatEndpointSupport.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Override
public Consumer createConsumer(Processor processor) throws Exception {
    return new HipchatConsumer(this, processor) {
        @Override
        protected CloseableHttpResponse executeGet(HttpGet httpGet) throws IOException {
            return closeableHttpResponse;
        }
    };
}
 
Example #25
Source File: BraintreeIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testBraintreeClientTokenGateway() throws Exception {

    Map<String, Object> braintreeOptions = createBraintreeOptions();

    Assume.assumeTrue("[#1679] Enable Braintree testing in Jenkins",
            braintreeOptions.size() == BraintreeOption.values().length);

    final CountDownLatch latch = new CountDownLatch(1);
    final CamelContext camelctx = new DefaultCamelContext();
    final BraintreeConfiguration configuration = new BraintreeConfiguration();
    configuration.setHttpLogLevel(Level.WARNING);
    IntrospectionSupport.setProperties(configuration, braintreeOptions);

    // add BraintreeComponent to Camel context
    final BraintreeComponent component = new BraintreeComponent(camelctx);
    component.setConfiguration(configuration);
    camelctx.addComponent("braintree", component);

    camelctx.addRoutes(new RouteBuilder() {
        @Override
        public void configure() throws Exception {
            from("timer://braintree?repeatCount=1")
                .to("braintree:clientToken/generate")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        latch.countDown();
                    }})
                .to("mock:result");
        }
    });

    camelctx.start();
    try {
        Assert.assertTrue("Countdown reached zero", latch.await(5, TimeUnit.MINUTES));
    } finally {
        camelctx.close();
    }
}
 
Example #26
Source File: WebhookConnectorCustomizerTest.java    From syndesis with Apache License 2.0 5 votes vote down vote up
private static Consumer<Processor> containsInstanceOf(Class<?> type) {
    return p -> {
        assertThat(p).isInstanceOf(Navigate.class);
        final List<?> next = ((Navigate) p).next();

        assertThat(next).hasOnlyOneElementSatisfying(n -> type.isInstance(n));
    };
}
 
Example #27
Source File: JGroupsIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Test
public void testMasterElection() throws Exception {

    final CountDownLatch latch = new CountDownLatch(1);

    CamelContext camelcxt = new DefaultCamelContext();
    camelcxt.addRoutes(new RouteBuilder() {
        public void configure() throws Exception {
            String jgroupsEndpoint = String.format("jgroups:%s?enableViewMessages=true", UUID.randomUUID());
            from(jgroupsEndpoint).filter(JGroupsFilters.dropNonCoordinatorViews()).process(new Processor() {
                @Override
                public void process(Exchange exchange) throws Exception {
                    String camelContextName = exchange.getContext().getName();
                    if (!camelContextName.equals(master)) {
                        master = camelContextName;
                        System.out.println("ELECTED MASTER: " + master);
                        latch.countDown();
                    }
                }
            });
        }
    });

    camelcxt.start();
    try {
        Assert.assertTrue(latch.await(3, TimeUnit.SECONDS));
        Assert.assertEquals(camelcxt.getName(), master);
    } finally {
        camelcxt.stop();
    }
}
 
Example #28
Source File: ScannedComponentSpringRouteBuilder.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    from("direct:start").process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            exchange.getIn().setBody(getApplicationContext());
        }
    });
}
 
Example #29
Source File: file_s.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Deprecated
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService,
                          boolean streaming, boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork) {
    this(camelContext, processors, aggregationStrategy, parallelProcessing, executorService, shutdownExecutorService,
            streaming, stopOnException, timeout, onPrepare, shareUnitOfWork, false);
}
 
Example #30
Source File: patched.java    From gumtree-spoon-ast-diff with Apache License 2.0 5 votes vote down vote up
@Deprecated
public MulticastProcessor(CamelContext camelContext, Collection<Processor> processors, AggregationStrategy aggregationStrategy,
                          boolean parallelProcessing, ExecutorService executorService, boolean shutdownExecutorService,
                          boolean streaming, boolean stopOnException, long timeout, Processor onPrepare, boolean shareUnitOfWork) {
    this(camelContext, processors, aggregationStrategy, parallelProcessing, executorService, shutdownExecutorService,
            streaming, stopOnException, timeout, onPrepare, shareUnitOfWork, false);
}