001 /**
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements. See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License. You may obtain a copy of the License at
008 *
009 * http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017 package org.apache.camel.component.seda;
018
019 import java.util.concurrent.TimeUnit;
020
021 import org.apache.camel.AlreadyStoppedException;
022 import org.apache.camel.Consumer;
023 import org.apache.camel.Exchange;
024 import org.apache.camel.Processor;
025 import org.apache.camel.impl.ServiceSupport;
026 import org.apache.commons.logging.Log;
027 import org.apache.commons.logging.LogFactory;
028
029 /**
030 * @version $Revision: 563607 $
031 */
032 public class SedaConsumer<E extends Exchange> extends ServiceSupport implements Consumer<E>, Runnable {
033 private static final Log LOG = LogFactory.getLog(SedaConsumer.class);
034
035 private SedaEndpoint<E> endpoint;
036 private Processor processor;
037 private Thread thread;
038
039 public SedaConsumer(SedaEndpoint<E> endpoint, Processor processor) {
040 this.endpoint = endpoint;
041 this.processor = processor;
042 }
043
044 @Override
045 public String toString() {
046 return "QueueConsumer: " + endpoint.getEndpointUri();
047 }
048
049 public void run() {
050 while (!isStopping()) {
051 E exchange;
052 try {
053 exchange = endpoint.getQueue().poll(1000, TimeUnit.MILLISECONDS);
054 } catch (InterruptedException e) {
055 break;
056 }
057 if (exchange != null && !isStopping()) {
058 try {
059 processor.process(exchange);
060 } catch (AlreadyStoppedException e) {
061 LOG.debug("Ignoring failed message due to shutdown: " + e, e);
062 break;
063 } catch (Throwable e) {
064 LOG.error(e);
065 }
066 }
067 }
068 }
069
070 protected void doStart() throws Exception {
071 thread = new Thread(this, getThreadName(endpoint.getEndpointUri()));
072 thread.setDaemon(true);
073 thread.start();
074 }
075
076 protected void doStop() throws Exception {
077 thread.join();
078 }
079
080 }