001 /** 002 * 003 * Licensed to the Apache Software Foundation (ASF) under one or more 004 * contributor license agreements. See the NOTICE file distributed with 005 * this work for additional information regarding copyright ownership. 006 * The ASF licenses this file to You under the Apache License, Version 2.0 007 * (the "License"); you may not use this file except in compliance with 008 * the License. You may obtain a copy of the License at 009 * 010 * http://www.apache.org/licenses/LICENSE-2.0 011 * 012 * Unless required by applicable law or agreed to in writing, software 013 * distributed under the License is distributed on an "AS IS" BASIS, 014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 015 * See the License for the specific language governing permissions and 016 * limitations under the License. 017 */ 018 package org.apache.camel.processor; 019 020 import org.apache.camel.Exchange; 021 import org.apache.camel.Processor; 022 import org.apache.camel.impl.ServiceSupport; 023 import org.apache.camel.model.ExceptionType; 024 025 import java.util.IdentityHashMap; 026 import java.util.List; 027 import java.util.Map; 028 import java.util.Set; 029 030 /** 031 * @version $Revision: 1.1 $ 032 */ 033 public abstract class ErrorHandlerSupport extends ServiceSupport implements ErrorHandler { 034 private Map<Class, ExceptionType> exceptionPolicices = new IdentityHashMap<Class, ExceptionType>(); 035 036 public void addExceptionPolicy(ExceptionType exception) { 037 Processor processor = exception.getErrorHandler(); 038 addChildService(processor); 039 040 List<Class> list = exception.getExceptionClasses(); 041 042 for (Class exceptionType : list) { 043 exceptionPolicices.put(exceptionType, exception); 044 } 045 } 046 047 /** 048 * Attempts to invoke the handler for this particular exception if one is available 049 * 050 * @param exchange 051 * @param exception 052 * @return 053 */ 054 protected boolean customProcessorForException(Exchange exchange, Throwable exception) throws Exception { 055 ExceptionType policy = getExceptionPolicy(exchange, exception); 056 Processor processor = policy.getErrorHandler(); 057 if (processor != null) { 058 processor.process(exchange); 059 return true; 060 } 061 return false; 062 } 063 064 protected ExceptionType getExceptionPolicy(Exchange exchange, Throwable exception) { 065 Set<Map.Entry<Class, ExceptionType>> entries = exceptionPolicices.entrySet(); 066 for (Map.Entry<Class, ExceptionType> entry : entries) { 067 Class type = entry.getKey(); 068 if (type.isInstance(exception)) { 069 return entry.getValue(); 070 } 071 } 072 return null; 073 } 074 }