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.util;
018
019 import org.apache.camel.Endpoint;
020 import org.apache.camel.Exchange;
021 import org.apache.camel.PollingConsumer;
022 import org.apache.camel.Processor;
023 import org.apache.commons.logging.Log;
024 import org.apache.commons.logging.LogFactory;
025
026 /**
027 * Some helper methods for working with {@link Endpoint} instances
028 *
029 * @version $Revision: 745826 $
030 */
031 public final class EndpointHelper {
032 private static final transient Log LOG = LogFactory.getLog(EndpointHelper.class);
033
034 private EndpointHelper() {
035 //Utility Class
036 }
037 /**
038 * Creates a {@link PollingConsumer} and polls all pending messages on the endpoint
039 * and invokes the given {@link Processor} to process each {@link Exchange} and then closes
040 * down the consumer and throws any exceptions thrown.
041 */
042 public static void pollEndpoint(Endpoint endpoint, Processor processor, long timeout) throws Exception {
043 PollingConsumer consumer = endpoint.createPollingConsumer();
044 try {
045 consumer.start();
046
047 while (true) {
048 Exchange exchange = consumer.receive(timeout);
049 if (exchange == null) {
050 break;
051 } else {
052 processor.process(exchange);
053 }
054 }
055 } finally {
056 try {
057 consumer.stop();
058 } catch (Exception e) {
059 LOG.warn("Failed to stop PollingConsumer: " + e, e);
060 }
061 }
062 }
063
064 /**
065 * Creates a {@link PollingConsumer} and polls all pending messages on the
066 * endpoint and invokes the given {@link Processor} to process each
067 * {@link Exchange} and then closes down the consumer and throws any
068 * exceptions thrown.
069 */
070 public static void pollEndpoint(Endpoint endpoint, Processor processor) throws Exception {
071 pollEndpoint(endpoint, processor, 1000L);
072 }
073 }