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 */
017package org.apache.camel.impl;
018
019import java.util.concurrent.RejectedExecutionException;
020
021import org.apache.camel.Endpoint;
022import org.apache.camel.Exchange;
023import org.apache.camel.IsSingleton;
024import org.apache.camel.Processor;
025import org.apache.camel.RuntimeExchangeException;
026import org.apache.camel.util.ServiceHelper;
027
028/**
029 * A simple implementation of {@link org.apache.camel.PollingConsumer} which just uses
030 * a {@link Processor}. This implementation does not support timeout based
031 * receive methods such as {@link #receive(long)}
032 *
033 * @version 
034 */
035public class ProcessorPollingConsumer extends PollingConsumerSupport implements IsSingleton {
036    private final Processor processor;
037
038    public ProcessorPollingConsumer(Endpoint endpoint, Processor processor) {
039        super(endpoint);
040        this.processor = processor;
041    }
042
043    protected void doStart() throws Exception {
044        ServiceHelper.startService(processor);
045    }
046
047    protected void doStop() throws Exception {
048        ServiceHelper.stopService(processor);
049    }
050
051    public Exchange receive() {
052        // must be started
053        if (!isRunAllowed() || !isStarted()) {
054            throw new RejectedExecutionException(this + " is not started, but in state: " + getStatus().name());
055        }
056
057        Exchange exchange = getEndpoint().createExchange();
058        try {
059            processor.process(exchange);
060        } catch (Exception e) {
061            throw new RuntimeExchangeException("Error while processing exchange", exchange, e);
062        }
063        return exchange;
064    }
065
066    public Exchange receiveNoWait() {
067        return receive();
068    }
069
070    public Exchange receive(long timeout) {
071        return receive();
072    }
073
074    @Override
075    public boolean isSingleton() {
076        return true;
077    }
078    
079}