blob: 4601d9cf97a813d1ccfb7df0454752c00eafa5eb [file] [log] [blame]
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.cxf.dosgi.common.proxy;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.osgi.framework.ServiceException;
public class ExceptionMapper {
private static final String REMOTE_EXCEPTION_TYPE = "REMOTE";
private Map<Method, Set<Class<?>>> exceptionsMap = new HashMap<Method, Set<Class<?>>>();
public ExceptionMapper(Class<?> iType) {
introspectTypeForExceptions(iType);
}
public Throwable mapException(Method m, Throwable ex) throws Throwable {
Throwable cause = ex.getCause() == null ? ex : ex.getCause();
Set<Class<?>> excTypes = exceptionsMap.get(m);
if (excTypes != null) {
for (Class<?> type : excTypes) {
if (type.isAssignableFrom(ex.getClass())) {
return ex;
}
if (type.isAssignableFrom(cause.getClass())) {
return cause;
}
}
}
return new ServiceException(REMOTE_EXCEPTION_TYPE, ex);
}
private void introspectTypeForExceptions(Class<?> iType) {
for (Method m : iType.getDeclaredMethods()) {
addExceptions(m);
}
for (Method m : iType.getMethods()) {
addExceptions(m);
}
}
private void addExceptions(Method m) {
for (Class<?> excType : m.getExceptionTypes()) {
if (Exception.class.isAssignableFrom(excType)) {
getCurrentExTypes(m).add(excType);
}
}
}
private Set<Class<?>> getCurrentExTypes(Method m) {
Set<Class<?>> types = exceptionsMap.get(m);
if (types == null) {
types = new HashSet<Class<?>>();
exceptionsMap.put(m, types);
}
return types;
}
}