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.processor;
018
019import java.util.List;
020
021import org.apache.camel.AsyncCallback;
022import org.apache.camel.Exchange;
023import org.apache.camel.Predicate;
024import org.apache.camel.Processor;
025import org.apache.camel.Traceable;
026import org.apache.camel.spi.IdAware;
027import org.apache.camel.util.EventHelper;
028import org.apache.camel.util.ExchangeHelper;
029import org.apache.camel.util.ObjectHelper;
030import org.slf4j.Logger;
031import org.slf4j.LoggerFactory;
032
033/**
034 * A processor which catches exceptions.
035 *
036 * @version 
037 */
038public class CatchProcessor extends DelegateAsyncProcessor implements Traceable, IdAware {
039    private static final Logger LOG = LoggerFactory.getLogger(CatchProcessor.class);
040
041    private String id;
042    private final List<Class<? extends Throwable>> exceptions;
043    private final Predicate onWhen;
044    private final Predicate handled;
045
046    public CatchProcessor(List<Class<? extends Throwable>> exceptions, Processor processor, Predicate onWhen, Predicate handled) {
047        super(processor);
048        this.exceptions = exceptions;
049        this.onWhen = onWhen;
050        this.handled = handled;
051    }
052
053    @Override
054    public String toString() {
055        return "Catch[" + exceptions + " -> " + getProcessor() + "]";
056    }
057
058    public String getId() {
059        return id;
060    }
061
062    public void setId(String id) {
063        this.id = id;
064    }
065
066    public String getTraceLabel() {
067        return "catch";
068    }
069
070    @Override
071    public boolean process(final Exchange exchange, final AsyncCallback callback) {
072        Exception e = exchange.getException();
073        Throwable caught = catches(exchange, e);
074        // If a previous catch clause handled the exception or if this clause does not match, exit
075        if (exchange.getProperty(Exchange.EXCEPTION_HANDLED) != null || caught == null) {
076            callback.done(true);
077            return true;
078        }
079        if (LOG.isTraceEnabled()) {
080            LOG.trace("This CatchProcessor catches the exception: {} caused by: {}", caught.getClass().getName(), e.getMessage());
081        }
082
083        // store the last to endpoint as the failure endpoint
084        if (exchange.getProperty(Exchange.FAILURE_ENDPOINT) == null) {
085            exchange.setProperty(Exchange.FAILURE_ENDPOINT, exchange.getProperty(Exchange.TO_ENDPOINT));
086        }
087        // give the rest of the pipeline another chance
088        exchange.setProperty(Exchange.EXCEPTION_HANDLED, true);
089        exchange.setProperty(Exchange.EXCEPTION_CAUGHT, e);
090        exchange.setException(null);
091        // and we should not be regarded as exhausted as we are in a try .. catch block
092        exchange.removeProperty(Exchange.REDELIVERY_EXHAUSTED);
093
094        // is the exception handled by the catch clause
095        final boolean handled = handles(exchange);
096
097        if (LOG.isDebugEnabled()) {
098            LOG.debug("The exception is handled: {} for the exception: {} caused by: {}",
099                    new Object[]{handled, e.getClass().getName(), e.getMessage()});
100        }
101
102        if (handled) {
103            // emit event that the failure is being handled
104            EventHelper.notifyExchangeFailureHandling(exchange.getContext(), exchange, processor, false, null);
105        }
106
107        boolean sync = processor.process(exchange, new AsyncCallback() {
108            public void done(boolean doneSync) {
109                if (handled) {
110                    // emit event that the failure was handled
111                    EventHelper.notifyExchangeFailureHandled(exchange.getContext(), exchange, processor, false, null);
112                } else {
113                    if (exchange.getException() == null) {
114                        exchange.setException(exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class));
115                    }
116                }
117                // always clear redelivery exhausted in a catch clause
118                exchange.removeProperty(Exchange.REDELIVERY_EXHAUSTED);
119
120                if (!doneSync) {
121                    // signal callback to continue routing async
122                    ExchangeHelper.prepareOutToIn(exchange);
123                }
124
125                callback.done(doneSync);
126            }
127        });
128
129        return sync;
130    }
131
132    /**
133     * Returns with the exception that is caught by this processor.
134     *
135     * This method traverses exception causes, so sometimes the exception
136     * returned from this method might be one of causes of the parameter
137     * passed.
138     *
139     * @param exchange  the current exchange
140     * @param exception the thrown exception
141     * @return Throwable that this processor catches. <tt>null</tt> if nothing matches.
142     */
143    protected Throwable catches(Exchange exchange, Throwable exception) {
144        // use the exception iterator to walk the caused by hierarchy
145        for (final Throwable e : ObjectHelper.createExceptionIterable(exception)) {
146            // see if we catch this type
147            for (final Class<?> type : exceptions) {
148                if (type.isInstance(e) && matchesWhen(exchange)) {
149                    return e;
150                }
151            }
152        }
153
154        // not found
155        return null;
156    }
157
158    /**
159     * Whether this catch processor handles the exception it have caught
160     *
161     * @param exchange  the current exchange
162     * @return <tt>true</tt> if this processor handles it, <tt>false</tt> otherwise.
163     */
164    protected boolean handles(Exchange exchange) {
165        if (handled == null) {
166            // handle by default
167            return true;
168        }
169
170        return handled.matches(exchange);
171    }
172
173    public List<Class<? extends Throwable>> getExceptions() {
174        return exceptions;
175    }
176
177    /**
178     * Strategy method for matching the exception type with the current exchange.
179     * <p/>
180     * This default implementation will match as:
181     * <ul>
182     *   <li>Always true if no when predicate on the exception type
183     *   <li>Otherwise the when predicate is matches against the current exchange
184     * </ul>
185     *
186     * @param exchange the current {@link org.apache.camel.Exchange}
187     * @return <tt>true</tt> if matched, <tt>false</tt> otherwise.
188     */
189    protected boolean matchesWhen(Exchange exchange) {
190        if (onWhen == null) {
191            // if no predicate then it's always a match
192            return true;
193        }
194        return onWhen.matches(exchange);
195    }
196}