Search in sources :

Example 1 with PollingConsumer

use of org.apache.camel.PollingConsumer in project camel by apache.

the class InvalidConfigurationTest method testSMTPCanNotBeUsedForConsumingMails.

@Test
public void testSMTPCanNotBeUsedForConsumingMails() throws Exception {
    Endpoint endpoint = context.getEndpoint("smtp://localhost?username=james");
    PollingConsumer consumer = endpoint.createPollingConsumer();
    try {
        consumer.start();
        fail("Should have thrown NoSuchProviderException as stmp protocol cannot be used for consuming mails");
    } catch (IllegalArgumentException e) {
    // expected
    }
}
Also used : PollingConsumer(org.apache.camel.PollingConsumer) Endpoint(org.apache.camel.Endpoint) Test(org.junit.Test)

Example 2 with PollingConsumer

use of org.apache.camel.PollingConsumer in project camel by apache.

the class FromQueueThenConsumeFtpToMockTest method createRouteBuilder.

protected RouteBuilder createRouteBuilder() throws Exception {
    return new RouteBuilder() {

        public void configure() throws Exception {
            // START SNIPPET: e2
            from("seda:start").process(new Processor() {

                public void process(final Exchange exchange) throws Exception {
                    // get the filename from our custome header we want to get from a remote server
                    String filename = exchange.getIn().getHeader("myfile", String.class);
                    // construct the total url for the ftp consumer
                    // add the fileName option with the file we want to consume
                    String url = getFtpUrl() + "&fileName=" + filename;
                    // create a ftp endpoint
                    Endpoint ftp = context.getEndpoint(url);
                    // create a polling consumer where we can poll the myfile from the ftp server
                    PollingConsumer consumer = ftp.createPollingConsumer();
                    // must start the consumer before we can receive
                    consumer.start();
                    // poll the file from the ftp server
                    Exchange result = consumer.receive();
                    // the result is the response from the FTP consumer (the downloaded file)
                    // replace the outher exchange with the content from the downloaded file
                    exchange.getIn().setBody(result.getIn().getBody());
                    // stop the consumer
                    consumer.stop();
                }
            }).to("mock:result");
        // END SNIPPET: e2
        }
    };
}
Also used : Exchange(org.apache.camel.Exchange) PollingConsumer(org.apache.camel.PollingConsumer) Processor(org.apache.camel.Processor) RouteBuilder(org.apache.camel.builder.RouteBuilder) Endpoint(org.apache.camel.Endpoint) MockEndpoint(org.apache.camel.component.mock.MockEndpoint)

Example 3 with PollingConsumer

use of org.apache.camel.PollingConsumer in project camel by apache.

the class FtpPollingConsumerTest method testPollingConsumer.

@Test
public void testPollingConsumer() throws Exception {
    template.sendBodyAndHeader(getFtpUrl(), "Hello World", Exchange.FILE_NAME, "hello.txt");
    PollingConsumer consumer = context.getEndpoint(getFtpUrl()).createPollingConsumer();
    consumer.start();
    Exchange exchange = consumer.receive(5000);
    assertNotNull(exchange);
    assertEquals("Hello World", exchange.getIn().getBody(String.class));
    // sleep a bit to ensure polling consumer would be suspended after we have used it
    Thread.sleep(1000);
    // drop a new file which should not be picked up by the consumer
    template.sendBodyAndHeader(getFtpUrl(), "Bye World", Exchange.FILE_NAME, "bye.txt");
    // sleep a bit to ensure polling consumer would not have picked up that file
    Thread.sleep(1000);
    File file = new File(FTP_ROOT_DIR + "/polling/bye.txt");
    assertTrue("File should exist " + file, file.exists());
    consumer.stop();
}
Also used : Exchange(org.apache.camel.Exchange) PollingConsumer(org.apache.camel.PollingConsumer) File(java.io.File) Test(org.junit.Test)

Example 4 with PollingConsumer

use of org.apache.camel.PollingConsumer in project camel by apache.

the class PollEnricher method process.

/**
     * Enriches the input data (<code>exchange</code>) by first obtaining
     * additional data from an endpoint represented by an endpoint
     * <code>producer</code> and second by aggregating input data and additional
     * data. Aggregation of input data and additional data is delegated to an
     * {@link org.apache.camel.processor.aggregate.AggregationStrategy} object set at construction time. If the
     * message exchange with the resource endpoint fails then no aggregation
     * will be done and the failed exchange content is copied over to the
     * original message exchange.
     *
     * @param exchange input data.
     */
@Override
public boolean process(Exchange exchange, AsyncCallback callback) {
    try {
        preCheckPoll(exchange);
    } catch (Exception e) {
        exchange.setException(new CamelExchangeException("Error during pre poll check", exchange, e));
        callback.done(true);
        return true;
    }
    // which consumer to use
    PollingConsumer consumer;
    Endpoint endpoint;
    // use dynamic endpoint so calculate the endpoint to use
    Object recipient = null;
    try {
        recipient = expression.evaluate(exchange, Object.class);
        endpoint = resolveEndpoint(exchange, recipient);
        // acquire the consumer from the cache
        consumer = consumerCache.acquirePollingConsumer(endpoint);
    } catch (Throwable e) {
        if (isIgnoreInvalidEndpoint()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Endpoint uri is invalid: " + recipient + ". This exception will be ignored.", e);
            }
        } else {
            exchange.setException(e);
        }
        callback.done(true);
        return true;
    }
    // grab the real delegate consumer that performs the actual polling
    Consumer delegate = consumer;
    if (consumer instanceof EventDrivenPollingConsumer) {
        delegate = ((EventDrivenPollingConsumer) consumer).getDelegateConsumer();
    }
    // is the consumer bridging the error handler?
    boolean bridgeErrorHandler = false;
    if (delegate instanceof DefaultConsumer) {
        ExceptionHandler handler = ((DefaultConsumer) delegate).getExceptionHandler();
        if (handler != null && handler instanceof BridgeExceptionHandlerToErrorHandler) {
            bridgeErrorHandler = true;
        }
    }
    Exchange resourceExchange;
    try {
        if (timeout < 0) {
            LOG.debug("Consumer receive: {}", consumer);
            resourceExchange = consumer.receive();
        } else if (timeout == 0) {
            LOG.debug("Consumer receiveNoWait: {}", consumer);
            resourceExchange = consumer.receiveNoWait();
        } else {
            LOG.debug("Consumer receive with timeout: {} ms. {}", timeout, consumer);
            resourceExchange = consumer.receive(timeout);
        }
        if (resourceExchange == null) {
            LOG.debug("Consumer received no exchange");
        } else {
            LOG.debug("Consumer received: {}", resourceExchange);
        }
    } catch (Exception e) {
        exchange.setException(new CamelExchangeException("Error during poll", exchange, e));
        callback.done(true);
        return true;
    } finally {
        // return the consumer back to the cache
        consumerCache.releasePollingConsumer(endpoint, consumer);
    }
    // remember current redelivery stats
    Object redeliveried = exchange.getIn().getHeader(Exchange.REDELIVERED);
    Object redeliveryCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_COUNTER);
    Object redeliveryMaxCounter = exchange.getIn().getHeader(Exchange.REDELIVERY_MAX_COUNTER);
    // if we are bridging error handler and failed then remember the caused exception
    Throwable cause = null;
    if (resourceExchange != null && bridgeErrorHandler) {
        cause = resourceExchange.getException();
    }
    try {
        if (!isAggregateOnException() && (resourceExchange != null && resourceExchange.isFailed())) {
            // copy resource exchange onto original exchange (preserving pattern)
            // and preserve redelivery headers
            copyResultsPreservePattern(exchange, resourceExchange);
        } else {
            prepareResult(exchange);
            // prepare the exchanges for aggregation
            ExchangeHelper.prepareAggregation(exchange, resourceExchange);
            // must catch any exception from aggregation
            Exchange aggregatedExchange = aggregationStrategy.aggregate(exchange, resourceExchange);
            if (aggregatedExchange != null) {
                // copy aggregation result onto original exchange (preserving pattern)
                copyResultsPreservePattern(exchange, aggregatedExchange);
                // handover any synchronization
                if (resourceExchange != null) {
                    resourceExchange.handoverCompletions(exchange);
                }
            }
        }
        // if we failed then restore caused exception
        if (cause != null) {
            // restore caused exception
            exchange.setException(cause);
            // remove the exhausted marker as we want to be able to perform redeliveries with the error handler
            exchange.removeProperties(Exchange.REDELIVERY_EXHAUSTED);
            // preserve the redelivery stats
            if (redeliveried != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERED, redeliveried);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERED, redeliveried);
                }
            }
            if (redeliveryCounter != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERY_COUNTER, redeliveryCounter);
                }
            }
            if (redeliveryMaxCounter != null) {
                if (exchange.hasOut()) {
                    exchange.getOut().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
                } else {
                    exchange.getIn().setHeader(Exchange.REDELIVERY_MAX_COUNTER, redeliveryMaxCounter);
                }
            }
        }
        // set header with the uri of the endpoint enriched so we can use that for tracing etc
        if (exchange.hasOut()) {
            exchange.getOut().setHeader(Exchange.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri());
        } else {
            exchange.getIn().setHeader(Exchange.TO_ENDPOINT, consumer.getEndpoint().getEndpointUri());
        }
    } catch (Throwable e) {
        exchange.setException(new CamelExchangeException("Error occurred during aggregation", exchange, e));
        callback.done(true);
        return true;
    }
    callback.done(true);
    return true;
}
Also used : CamelExchangeException(org.apache.camel.CamelExchangeException) PollingConsumer(org.apache.camel.PollingConsumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) DefaultConsumer(org.apache.camel.impl.DefaultConsumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) CamelExchangeException(org.apache.camel.CamelExchangeException) BridgeExceptionHandlerToErrorHandler(org.apache.camel.impl.BridgeExceptionHandlerToErrorHandler) ExceptionHandler(org.apache.camel.spi.ExceptionHandler) Exchange(org.apache.camel.Exchange) Endpoint(org.apache.camel.Endpoint) PollingConsumer(org.apache.camel.PollingConsumer) Consumer(org.apache.camel.Consumer) EventDrivenPollingConsumer(org.apache.camel.impl.EventDrivenPollingConsumer) DefaultConsumer(org.apache.camel.impl.DefaultConsumer)

Example 5 with PollingConsumer

use of org.apache.camel.PollingConsumer in project camel by apache.

the class FilePollingConsumerIssueTest method testFilePollingConsumer.

public void testFilePollingConsumer() throws Exception {
    template.sendBodyAndHeader("file://target/fpc", "Hello World", Exchange.FILE_NAME, "hello.txt");
    Endpoint endpoint = context.getEndpoint("file://target/fpc?fileName=hello.txt");
    PollingConsumer consumer = endpoint.createPollingConsumer();
    consumer.start();
    Exchange exchange = consumer.receive(5000);
    assertNotNull(exchange);
    assertEquals("hello.txt", exchange.getIn().getHeader(Exchange.FILE_NAME, String.class));
    assertEquals("Hello World", exchange.getIn().getBody(String.class));
    consumer.stop();
}
Also used : Exchange(org.apache.camel.Exchange) PollingConsumer(org.apache.camel.PollingConsumer) Endpoint(org.apache.camel.Endpoint)

Aggregations

PollingConsumer (org.apache.camel.PollingConsumer)73 Exchange (org.apache.camel.Exchange)41 Test (org.junit.Test)27 HashMap (java.util.HashMap)21 CamelContext (org.apache.camel.CamelContext)21 DefaultCamelContext (org.apache.camel.impl.DefaultCamelContext)21 RouteBuilder (org.apache.camel.builder.RouteBuilder)19 Endpoint (org.apache.camel.Endpoint)10 Connection (javax.jms.Connection)9 Transactional (org.springframework.transaction.annotation.Transactional)9 ConnectionFactory (javax.jms.ConnectionFactory)7 JMSException (javax.jms.JMSException)7 MessageConversionException (org.springframework.jms.support.converter.MessageConversionException)5 ProducerTemplate (org.apache.camel.ProducerTemplate)4 WorkflowResult (org.apache.syncope.core.provisioning.api.WorkflowResult)4 Message (javax.jms.Message)3 Session (javax.jms.Session)3 TextMessage (javax.jms.TextMessage)3 ActiveMQTextMessage (org.apache.activemq.command.ActiveMQTextMessage)3 File (java.io.File)2