Search in sources :

Example 21 with Consumer

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

the class DefaultCamelContext method doStartOrResumeRoutes.

/**
     * Starts or resumes the routes
     *
     * @param routeServices  the routes to start (will only start a route if its not already started)
     * @param checkClash     whether to check for startup ordering clash
     * @param startConsumer  whether the route consumer should be started. Can be used to warmup the route without starting the consumer.
     * @param resumeConsumer whether the route consumer should be resumed.
     * @param addingRoutes   whether we are adding new routes
     * @throws Exception is thrown if error starting routes
     */
protected void doStartOrResumeRoutes(Map<String, RouteService> routeServices, boolean checkClash, boolean startConsumer, boolean resumeConsumer, boolean addingRoutes) throws Exception {
    isStartingRoutes.set(true);
    try {
        // filter out already started routes
        Map<String, RouteService> filtered = new LinkedHashMap<String, RouteService>();
        for (Map.Entry<String, RouteService> entry : routeServices.entrySet()) {
            boolean startable = false;
            Consumer consumer = entry.getValue().getRoutes().iterator().next().getConsumer();
            if (consumer instanceof SuspendableService) {
                // consumer could be suspended, which is not reflected in the RouteService status
                startable = ((SuspendableService) consumer).isSuspended();
            }
            if (!startable && consumer instanceof StatefulService) {
                // consumer could be stopped, which is not reflected in the RouteService status
                startable = ((StatefulService) consumer).getStatus().isStartable();
            } else if (!startable) {
                // no consumer so use state from route service
                startable = entry.getValue().getStatus().isStartable();
            }
            if (startable) {
                filtered.put(entry.getKey(), entry.getValue());
            }
        }
        // the context is in last phase of staring, so lets start the routes
        safelyStartRouteServices(checkClash, startConsumer, resumeConsumer, addingRoutes, filtered.values());
    } finally {
        isStartingRoutes.remove();
    }
}
Also used : SuspendableService(org.apache.camel.SuspendableService) PollingConsumer(org.apache.camel.PollingConsumer) Consumer(org.apache.camel.Consumer) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) TreeMap(java.util.TreeMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) StatefulService(org.apache.camel.StatefulService)

Example 22 with Consumer

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

the class NewFileConsumeTest method testNewFileConsumer.

public void testNewFileConsumer() throws Exception {
    FileComponent comp = new FileComponent();
    comp.setCamelContext(context);
    // create a file to consume
    createDirectory("target/consumefile");
    FileOutputStream fos = new FileOutputStream(new File("target/consumefile/hello.txt"));
    try {
        fos.write("Hello World".getBytes());
    } finally {
        fos.close();
    }
    Endpoint endpoint = comp.createEndpoint("file://target/consumefile", "target/consumefile", new HashMap<String, Object>());
    Consumer consumer = endpoint.createConsumer(new Processor() {

        public void process(Exchange exchange) throws Exception {
            assertNotNull(exchange);
            String body = exchange.getIn().getBody(String.class);
            assertEquals("Hello World", body);
            latch.countDown();
        }
    });
    consumer.start();
    latch.await();
    consumer.stop();
}
Also used : Exchange(org.apache.camel.Exchange) Processor(org.apache.camel.Processor) Endpoint(org.apache.camel.Endpoint) Consumer(org.apache.camel.Consumer) FileOutputStream(java.io.FileOutputStream) File(java.io.File)

Example 23 with Consumer

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

the class ConsumerCamelContextAware method testConsumerCamelContextAware.

public void testConsumerCamelContextAware() throws Exception {
    Consumer consumer = context.getEndpoint("vm:foo").createConsumer(null);
    assertNotNull(consumer);
    VmConsumer vm = assertIsInstanceOf(VmConsumer.class, consumer);
    assertEquals(vm.getCamelContext(), context);
}
Also used : Consumer(org.apache.camel.Consumer)

Example 24 with Consumer

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

the class ScheduledPollConsumerBackoffTest method testBackoffError.

public void testBackoffError() throws Exception {
    final Endpoint endpoint = getMockEndpoint("mock:foo");
    final Exception expectedException = new Exception("Hello, I should be thrown on shutdown only!");
    MockScheduledPollConsumer consumer = new MockScheduledPollConsumer(endpoint, expectedException);
    consumer.setBackoffMultiplier(4);
    consumer.setBackoffErrorThreshold(3);
    consumer.setPollStrategy(new PollingConsumerPollStrategy() {

        public boolean begin(Consumer consumer, Endpoint endpoint) {
            return true;
        }

        public void commit(Consumer consumer, Endpoint endpoint, int polledMessages) {
            commits++;
        }

        public boolean rollback(Consumer consumer, Endpoint endpoint, int retryCounter, Exception e) throws Exception {
            errors++;
            return false;
        }
    });
    consumer.start();
    consumer.run();
    consumer.run();
    consumer.run();
    assertEquals(3, errors);
    // now it should backoff 4 times
    consumer.run();
    consumer.run();
    consumer.run();
    consumer.run();
    assertEquals(3, errors);
    // and now we poll again
    consumer.run();
    consumer.run();
    consumer.run();
    assertEquals(6, errors);
    // now it should backoff 4 times
    consumer.run();
    consumer.run();
    consumer.run();
    consumer.run();
    assertEquals(6, errors);
    consumer.stop();
}
Also used : Endpoint(org.apache.camel.Endpoint) Consumer(org.apache.camel.Consumer) PollingConsumerPollStrategy(org.apache.camel.spi.PollingConsumerPollStrategy) Endpoint(org.apache.camel.Endpoint)

Example 25 with Consumer

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

the class RestEndpoint method createConsumer.

@Override
public Consumer createConsumer(Processor processor) throws Exception {
    RestConsumerFactory factory = null;
    String cname = null;
    if (getComponentName() != null) {
        Object comp = getCamelContext().getRegistry().lookupByName(getComponentName());
        if (comp != null && comp instanceof RestConsumerFactory) {
            factory = (RestConsumerFactory) comp;
        } else {
            comp = getCamelContext().getComponent(getComponentName());
            if (comp != null && comp instanceof RestConsumerFactory) {
                factory = (RestConsumerFactory) comp;
            }
        }
        if (factory == null) {
            if (comp != null) {
                throw new IllegalArgumentException("Component " + getComponentName() + " is not a RestConsumerFactory");
            } else {
                throw new NoSuchBeanException(getComponentName(), RestConsumerFactory.class.getName());
            }
        }
        cname = getComponentName();
    }
    // try all components
    if (factory == null) {
        for (String name : getCamelContext().getComponentNames()) {
            Component comp = getCamelContext().getComponent(name);
            if (comp != null && comp instanceof RestConsumerFactory) {
                factory = (RestConsumerFactory) comp;
                cname = name;
                break;
            }
        }
    }
    // lookup in registry
    if (factory == null) {
        Set<RestConsumerFactory> factories = getCamelContext().getRegistry().findByType(RestConsumerFactory.class);
        if (factories != null && factories.size() == 1) {
            factory = factories.iterator().next();
        }
    }
    // and there must only be exactly one so we safely can pick this one
    if (factory == null) {
        RestConsumerFactory found = null;
        String foundName = null;
        for (String name : DEFAULT_REST_CONSUMER_COMPONENTS) {
            Object comp = getCamelContext().getComponent(name, true);
            if (comp != null && comp instanceof RestConsumerFactory) {
                if (found == null) {
                    found = (RestConsumerFactory) comp;
                    foundName = name;
                } else {
                    throw new IllegalArgumentException("Multiple RestConsumerFactory found on classpath. Configure explicit which component to use");
                }
            }
        }
        if (found != null) {
            LOG.debug("Auto discovered {} as RestConsumerFactory", foundName);
            factory = found;
        }
    }
    if (factory != null) {
        // if no explicit port/host configured, then use port from rest configuration
        String scheme = "http";
        String host = "";
        int port = 80;
        RestConfiguration config = getCamelContext().getRestConfiguration(cname, true);
        if (config.getScheme() != null) {
            scheme = config.getScheme();
        }
        if (config.getHost() != null) {
            host = config.getHost();
        }
        int num = config.getPort();
        if (num > 0) {
            port = num;
        }
        // if no explicit hostname set then resolve the hostname
        if (ObjectHelper.isEmpty(host)) {
            if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.allLocalIp) {
                host = "0.0.0.0";
            } else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localHostName) {
                host = HostUtils.getLocalHostName();
            } else if (config.getRestHostNameResolver() == RestConfiguration.RestHostNameResolver.localIp) {
                host = HostUtils.getLocalIp();
            }
        }
        // calculate the url to the rest service
        String path = getPath();
        if (!path.startsWith("/")) {
            path = "/" + path;
        }
        // there may be an optional context path configured to help Camel calculate the correct urls for the REST services
        // this may be needed when using camel-servlet where we cannot get the actual context-path or port number of the servlet engine
        // during init of the servlet
        String contextPath = config.getContextPath();
        if (contextPath != null) {
            if (!contextPath.startsWith("/")) {
                path = "/" + contextPath + path;
            } else {
                path = contextPath + path;
            }
        }
        String baseUrl = scheme + "://" + host + (port != 80 ? ":" + port : "") + path;
        String url = baseUrl;
        if (uriTemplate != null) {
            // make sure to avoid double slashes
            if (uriTemplate.startsWith("/")) {
                url = url + uriTemplate;
            } else {
                url = url + "/" + uriTemplate;
            }
        }
        Consumer consumer = factory.createConsumer(getCamelContext(), processor, getMethod(), getPath(), getUriTemplate(), getConsumes(), getProduces(), config, getParameters());
        configureConsumer(consumer);
        // add to rest registry so we can keep track of them, we will remove from the registry when the consumer is removed
        // the rest registry will automatic keep track when the consumer is removed,
        // and un-register the REST service from the registry
        getCamelContext().getRestRegistry().addRestService(consumer, url, baseUrl, getPath(), getUriTemplate(), getMethod(), getConsumes(), getProduces(), getInType(), getOutType(), getRouteId(), getDescription());
        return consumer;
    } else {
        throw new IllegalStateException("Cannot find RestConsumerFactory in Registry or as a Component to use");
    }
}
Also used : Consumer(org.apache.camel.Consumer) NoSuchBeanException(org.apache.camel.NoSuchBeanException) RestConfiguration(org.apache.camel.spi.RestConfiguration) Component(org.apache.camel.Component) RestConsumerFactory(org.apache.camel.spi.RestConsumerFactory) DefaultEndpoint(org.apache.camel.impl.DefaultEndpoint) UriEndpoint(org.apache.camel.spi.UriEndpoint)

Aggregations

Consumer (org.apache.camel.Consumer)76 Endpoint (org.apache.camel.Endpoint)27 Processor (org.apache.camel.Processor)19 Exchange (org.apache.camel.Exchange)18 Test (org.junit.Test)18 HashMap (java.util.HashMap)10 RestConfiguration (org.apache.camel.spi.RestConfiguration)10 Producer (org.apache.camel.Producer)7 PollingConsumer (org.apache.camel.PollingConsumer)6 File (java.io.File)5 PollingConsumerPollStrategy (org.apache.camel.spi.PollingConsumerPollStrategy)5 FileNotFoundException (java.io.FileNotFoundException)4 ConcurrentHashMap (java.util.concurrent.ConcurrentHashMap)4 SuspendableService (org.apache.camel.SuspendableService)4 ArrayList (java.util.ArrayList)3 CountDownLatch (java.util.concurrent.CountDownLatch)3 CamelContext (org.apache.camel.CamelContext)3 Component (org.apache.camel.Component)3 NoSuchBeanException (org.apache.camel.NoSuchBeanException)3 Route (org.apache.camel.Route)3