All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.apache.cxf.dosgi.common.proxy.ExceptionMapper Maven / Gradle / Ivy

/**
 * 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>> exceptionsMap = new HashMap>>();
    
    public ExceptionMapper(Class iType) {
        introspectTypeForExceptions(iType);
    }
    
    public Throwable mapException(Method m, Throwable ex) throws Throwable {
        Throwable cause = ex.getCause() == null ? ex : ex.getCause();
        Set> 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> getCurrentExTypes(Method m) {
        Set> types = exceptionsMap.get(m);
        if (types == null) {
            types = new HashSet>();
            exceptionsMap.put(m, types);
        }
        return types;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy