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 Project: camelinaction2   Author: camelinaction   File: HttpServer.java    License: 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 Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: original.java    License: 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 #3
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 Project: wildfly-camel   Author: wildfly-extras   File: ServletIntegrationTest.java    License: 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 #5
Source Project: camel-k-runtime   Author: apache   File: KnativeHttpSupport.java    License: 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 #6
Source Project: camel-k-runtime   Author: apache   File: KnativeHttpSupport.java    License: 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 #7
Source Project: camelinaction2   Author: camelinaction   File: FileRollbackTest.java    License: 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 #8
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 #9
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 Project: camelinaction2   Author: camelinaction   File: MirandaTest.java    License: 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 Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 Project: camelinaction2   Author: camelinaction   File: SimulateErrorUsingProcessorTest.java    License: 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 Project: syndesis   Author: syndesisio   File: TracingInterceptStrategy.java    License: 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 Project: wildfly-camel   Author: wildfly-extras   File: HipchatEndpointSupport.java    License: 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 #16
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: file_t.java    License: 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 #17
Source Project: wildfly-camel   Author: wildfly-extras   File: BraintreeIntegrationTest.java    License: 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 #18
Source Project: camelinaction2   Author: camelinaction   File: MyInterceptor.java    License: 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 #19
Source Project: wildfly-camel   Author: wildfly-extras   File: CXFWSProducerIntegrationTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testCxfSoapHeader() throws Exception {
    deployer.deploy(SIMPLE_WAR);
    try {
        CamelContext camelctx = new DefaultCamelContext();
        camelctx.addRoutes(new RouteBuilder() {
            @Override
            public void configure() throws Exception {
                from("direct:start")
                .process(new Processor() {
                    @Override
                    public void process(Exchange exchange) throws Exception {
                        List<SoapHeader> soapHeaders = new ArrayList<SoapHeader>();

                        String headerXml = "<?xml version=\"1.0\" encoding=\"utf-8\"?><input xmlns=\"http://wildfly.camel.test.cxf\">Kermit</input>";

                        SoapHeader soapHeader = new SoapHeader(new QName("http://wildfly.camel.test.cxf", "input"), getSoapHeaderElement(headerXml));
                        soapHeader.setDirection(Header.Direction.DIRECTION_IN);
                        soapHeaders.add(soapHeader);

                        exchange.getOut().setHeader(Header.HEADER_LIST, soapHeaders);
                    }
                })
                .to("cxf://" + getEndpointAddress("/simple") + "?serviceClass=" + Endpoint.class.getName());
            }
        });

        camelctx.start();
        try {
            ProducerTemplate producer = camelctx.createProducerTemplate();
            String result = producer.requestBody("direct:start", null, String.class);
            Assert.assertEquals("Hello Kermit", result);
        } finally {
            camelctx.close();
        }
    } finally {
        deployer.undeploy(SIMPLE_WAR);
    }
}
 
Example #20
Source Project: camel-spring-boot   Author: apache   File: CamelRestTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Consumer createConsumer(
    CamelContext camelContext,
    Processor processor,
    String verb,
    String basePath,
    String uriTemplate,
    String consumes,
    String produces,
    RestConfiguration configuration,
    Map<String, Object> parameters) throws Exception {

    // just use a seda endpoint for testing purpose
    String id;
    if (uriTemplate != null) {
        id = DefaultUuidGenerator.generateSanitizedId(basePath + uriTemplate);
    } else {
        id = DefaultUuidGenerator.generateSanitizedId(basePath);
    }
    // remove leading dash as we add that ourselves
    if (id.startsWith("-")) {
        id = id.substring(1);
    }

    if (configuration.getConsumerProperties() != null) {
        String ref = (String) configuration.getConsumerProperties().get("dummy");
        if (ref != null) {
            dummy = CamelContextHelper.mandatoryLookup(camelContext, ref.substring(1));
        }
    }

    SedaEndpoint seda = camelContext.getEndpoint("seda:" + verb + "-" + id, SedaEndpoint.class);
    return seda.createConsumer(processor);
}
 
Example #21
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: original.java    License: 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 #22
Source Project: container   Author: OpenTOSCA   File: Route.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {

    final URL wsdlURL = this.getClass().getClassLoader().getResource("wsdl/SoapAPI.wsdl");

    // CXF Endpoint
    final String SOAP_ENDPOINT = "cxf:" + ENDPOINT + "?wsdlURL=" + wsdlURL.toString()
        + "&serviceName={http://opentosca.org/appinvoker/}AppInvokerSoapWebServiceService&portName="
        + PORT.toString() + "&dataFormat=PAYLOAD&loggingFeatureEnabled=true";

    final ValueBuilder APP_BUS_ENDPOINT =
        new ValueBuilder(method(ApplicationBusServiceHandler.class, "getApplicationBusRoutingEndpoint"));
    final Predicate APP_BUS_ENDPOINT_EXISTS = PredicateBuilder.isNotNull(APP_BUS_ENDPOINT);

    final ClassLoader cl = org.opentosca.bus.application.api.soaphttp.model.ObjectFactory.class.getClassLoader();
    final JAXBContext jc = JAXBContext.newInstance("org.opentosca.bus.application.api.soaphttp.model", cl);
    final JaxbDataFormat jaxb = new JaxbDataFormat(jc);

    final Processor requestProcessor = new RequestProcessor();
    final Processor responseProcessor = new ResponseProcessor();

    from(SOAP_ENDPOINT).unmarshal(jaxb).process(requestProcessor).choice().when(APP_BUS_ENDPOINT_EXISTS)
        //FIXME this recipientList should be replaced with a directly injected service reference
        .recipientList(APP_BUS_ENDPOINT).to("direct:handleResponse").endChoice().otherwise()
        .to("direct:handleException");

    // handle exception if Application Bus is not running or wasn't bound
    from("direct:handleException")
        .throwException(new ApplicationBusInternalException("It seems like the Application Bus is not running."))
        .to("direct:handleResponse");

    // handle response
    from("direct:handleResponse").process(responseProcessor).marshal(jaxb);
}
 
Example #23
Source Project: wildfly-camel-examples   Author: wildfly-extras   File: JmsRouteBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void configure() throws Exception {
    /**
     * Configure the JMSComponent to use the connection factory
     * injected into this class
     */
    JmsComponent component = new JmsComponent();
    component.setConnectionFactory(connectionFactory);

    getContext().addComponent("jms", component);

    /**
     * This route uses the timer component to generate a message which is sent to
     * the JMS OrdersQueue
     */
    from("timer:produceJMSMessage?period=5s&delay=0&fixedRate=true")
    .process(new Processor() {
        @Override
        public void process(Exchange exchange) throws Exception {
            Integer count = exchange.getProperty(Exchange.TIMER_COUNTER, Integer.class);
            Date date = exchange.getProperty(Exchange.TIMER_FIRED_TIME, Date.class);

            exchange.getOut().setBody(String.format("Message %d created at %s", count, date.toString()));
        }
    })
    .to("jms:queue:OrdersQueue");

    /**
     * This route is invoked by the {@link MessageDrivenBean} message consumer and outputs
     * the message payload to the console log
     */
    from("direct:jmsIn")
    .log("Received message: ${body}");
}
 
Example #24
Source Project: karaf-decanter   Author: apache   File: DecanterTraceEventHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void traceExchange(ProcessorDefinition<?> node, Processor target, TraceInterceptor traceInterceptor, Exchange exchange) throws Exception {
    HashMap<String, Object> data = new HashMap<>();
    data.put("type", "camelTracer");
    data.put("karafName", System.getProperty("karaf.name"));
    data.put("hostAddress", InetAddress.getLocalHost().getHostAddress());
    data.put("hostName", InetAddress.getLocalHost().getHostName());
    data.put("nodeId", node.getId());
    data.put("timestamp", System.currentTimeMillis());
    new DefaultExchangeExtender().extend(data, exchange);
    for (String property : exchange.getProperties().keySet()) {
        if (property.startsWith("decanter.")) {
            data.put(property.substring("decanter.".length()), exchange.getProperties().get(property));
        }
    }
    dextender.extend(data, exchange);
    if (extender != null)  {
        extender.extend(data, exchange);
    }
    for (String header : exchange.getIn().getHeaders().keySet()) {
        if (header.startsWith("decanter.")) {
            data.put(header.substring("decanter.".length()), exchange.getIn().getHeader(header));
        }
    }
    Event event = new Event("decanter/collect/camel/tracer", data);
    eventAdmin.postEvent(event);
}
 
Example #25
Source Project: camelinaction   Author: camelinaction   File: FtpToJMSWithProcessorExample.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    // create CamelContext
    CamelContext context = new DefaultCamelContext();
    
    // connect to embedded ActiveMQ JMS broker
    ConnectionFactory connectionFactory = 
        new ActiveMQConnectionFactory("vm://localhost");
    context.addComponent("jms",
        JmsComponent.jmsComponentAutoAcknowledge(connectionFactory));

    // add our route to the CamelContext
    context.addRoutes(new RouteBuilder() {
        @Override
        public void configure() {
            from("ftp://rider.com/orders?username=rider&password=secret").
            process(new Processor() {                    
                public void process(Exchange exchange) throws Exception {
                    System.out.println("We just downloaded: " + exchange.getIn().getHeader("CamelFileName"));
                }
            }).
            to("jms:incomingOrders");
        }
    });

    // start the route and let it do its work
    context.start();
    Thread.sleep(10000);

    // stop the CamelContext
    context.stop();
}
 
Example #26
Source Project: camel-k-runtime   Author: apache   File: KnativeProducer.java    License: Apache License 2.0 5 votes vote down vote up
public KnativeProducer(Endpoint endpoint, Processor processor, Processor... processors) {
    super(endpoint);

    List<Processor> elements = new ArrayList<>(1 + processors.length);
    elements.add(processor);

    for (Processor p : processors) {
        elements.add(p);
    }

    Processor pipeline = Pipeline.newInstance(endpoint.getCamelContext(), elements);

    this.processor = AsyncProcessorConverterHelper.convert(pipeline);
}
 
Example #27
Source Project: gumtree-spoon-ast-diff   Author: SpoonLabs   File: patched.java    License: 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 #28
Source Project: wildfly-camel   Author: wildfly-extras   File: ScannedComponentSpringRouteBuilder.java    License: 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 Project: wildfly-camel   Author: wildfly-extras   File: JGroupsIntegrationTest.java    License: 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 #30
Source Project: syndesis   Author: syndesisio   File: WebhookConnectorCustomizerTest.java    License: 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));
    };
}