Example usage for java.lang.reflect Method getExceptionTypes

List of usage examples for java.lang.reflect Method getExceptionTypes

Introduction

In this page you can find the example usage for java.lang.reflect Method getExceptionTypes.

Prototype

@Override
public Class<?>[] getExceptionTypes() 

Source Link

Usage

From source file:org.bytesoft.bytetcc.supports.spring.CompensableAnnotationValidator.java

private void validateDeclaredRemotingException(Method method, Class<?> clazz) throws IllegalStateException {
    Class<?>[] exceptionTypeArray = method.getExceptionTypes();

    boolean located = false;
    for (int i = 0; i < exceptionTypeArray.length; i++) {
        Class<?> exceptionType = exceptionTypeArray[i];
        if (RemotingException.class.isAssignableFrom(exceptionType)) {
            located = true;/*from   ww w  . j  a v  a  2s  .  c o  m*/
            break;
        }
    }

    if (located) {
        throw new FatalBeanException(String.format(
                "The method(%s) shouldn't be declared to throw a remote exception: org.bytesoft.compensable.RemotingException!",
                method));
    }

}

From source file:Main.java

public static void dumpMethod(final Method method) {
    final StringBuilder builder = new StringBuilder();
    builder.append("------------------------------\n");
    builder.append("MethodName: ").append(method.getName()).append("\n");
    builder.append("ParameterTypes:{");
    for (Class<?> cls : method.getParameterTypes()) {
        builder.append(cls.getName()).append(", ");
    }/*from  ww  w  .  j a  v a  2s  .c o  m*/
    builder.append("}\n");
    builder.append("GenericParameterTypes:{");
    for (Type cls : method.getGenericParameterTypes()) {
        builder.append(cls.getClass()).append(", ");
    }
    builder.append("}\n");
    builder.append("TypeParameters:{");
    for (TypeVariable<Method> cls : method.getTypeParameters()) {
        builder.append(cls.getName()).append(", ");
    }
    builder.append("}\n");
    builder.append("DeclaredAnnotations:{");
    for (Annotation cls : method.getDeclaredAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("Annotations:{");
    for (Annotation cls : method.getAnnotations()) {
        builder.append(cls).append(", ");
    }
    builder.append("}\n");
    builder.append("ExceptionTypes:{");
    for (Class<?> cls : method.getExceptionTypes()) {
        builder.append(cls.getName()).append(", ");
        ;
    }
    builder.append("}\n");
    builder.append("ReturnType: ").append(method.getReturnType());
    builder.append("\nGenericReturnType: ").append(method.getGenericReturnType());
    builder.append("\nDeclaringClass: ").append(method.getDeclaringClass());
    builder.append("\n");

    System.out.println(builder.toString());
}

From source file:com.hubspot.utils.circuitbreaker.CircuitBreakerWrapper.java

/**
 * Wraps the supplied object toWrap in a CircuitBreaker conforming to the supplied CircuitBreakerPolicy.
 *///from   w  w w . j a  v a  2s .  c  om
public <T, W extends T> T wrap(W toWrap, Class<T> interfaceToProxy, CircuitBreakerPolicy policy)
        throws CircuitBreakerWrappingException {
    sanityCheck(toWrap, interfaceToProxy, policy);

    // walk the chain of interfaces implemented by T and check for their blacklisted methods
    Stack<Class<?>> implementedInterfaces = new Stack<Class<?>>();
    implementedInterfaces.addAll(Arrays.asList(interfaceToProxy.getInterfaces()));
    implementedInterfaces.add(interfaceToProxy);

    Map<Method, Class[]> blacklist = new HashMap();
    while (!implementedInterfaces.isEmpty()) {
        Class<?> implementedInterface = implementedInterfaces.pop();

        for (Method m : implementedInterface.getDeclaredMethods()) {
            // check that the blacklisted method throws CircuitBreakerException
            if (m.isAnnotationPresent(CircuitBreakerExceptionBlacklist.class)) {
                if (!ArrayUtils.contains(m.getExceptionTypes(), CircuitBreakerException.class)) {
                    throw new CircuitBreakerWrappingException(
                            "Wrapped methods must throw CircuitBreakerException");
                }

                CircuitBreakerExceptionBlacklist a = (CircuitBreakerExceptionBlacklist) m
                        .getAnnotation(CircuitBreakerExceptionBlacklist.class);
                blacklist.put(m, a.blacklist());
            }
        }

        implementedInterfaces.addAll(Arrays.asList(implementedInterface.getInterfaces()));
    }

    Class<?>[] interfaces = new Class<?>[] { interfaceToProxy };
    InvocationHandler handler = new CircuitBreakerInvocationHandler(toWrap, blacklist, policy);
    T newProxyInstance = (T) Proxy.newProxyInstance(getClass().getClassLoader(), interfaces, handler);
    return newProxyInstance;
}

From source file:net.sf.qooxdoo.rpc.RemoteCallUtils.java

/**
 * Check if a method throws the expected exception (used as a tag to
 * allow a method to be called)./*from w  ww  .j  a va 2  s .  co m*/
 */

protected boolean throwsExpectedException(Method method) {
    Class[] methodExceptionTypes = method.getExceptionTypes();
    int exceptionCount = methodExceptionTypes.length;
    for (int i = 0; i < exceptionCount; ++i) {
        if (RemoteServiceException.class.isAssignableFrom(methodExceptionTypes[i])) {
            return true;
        }
    }
    return false;
}

From source file:com.feedzai.fos.server.remote.impl.RemoteInterfacesTest.java

private void testMatch(Class<?> api, Class<?> remote, int remoteFieldAdditions) {
    Method[] apiMethods = api.getMethods();
    Method[] remoteMethods = remote.getMethods();

    Arrays.sort(apiMethods, buildComparator());
    Arrays.sort(remoteMethods, buildComparator());

    // Checks if @RemoteInterface is different from the class/interface itself.
    assertNotSame(/*from w ww  .j ava 2s. c  o  m*/
            String.format("@RemoteInterface cannot be the same for the class name in %s", api.getSimpleName()),
            api, remote);
    // Checks if the remote implementation can be assigned to Remote (i.e. if in the hierarchy extends/implements Remote).
    assertTrue(
            String.format("'%s' does not implement '%s'", remote.getSimpleName(), Remote.class.getSimpleName()),
            Remote.class.isAssignableFrom(remote));

    assertEquals(desc(api, null, "Number of methods matches"), apiMethods.length, remoteMethods.length);

    for (int i = 0; i < apiMethods.length; i++) {
        // Check if the names match
        Method expected = apiMethods[i];
        Method actual = remoteMethods[i];

        assertEquals(desc(api, actual, "Names match"), expected.getName(), actual.getName());
        assertTrue(desc(api, actual, "Number of arguments matches"), expected.getParameterTypes().length
                - actual.getParameterAnnotations().length <= remoteFieldAdditions);

        boolean remoteOrException = false;
        for (Class klass : actual.getExceptionTypes()) {
            remoteOrException = Exception.class.equals(klass) || RemoteException.class.equals(klass);
            if (remoteOrException) {
                break;
            }
        }

        // Checks if remote implementations throw Exception or RemoteException.
        assertTrue(desc(remote, actual,
                String.format("%s does not throw either RemoteException or Exception", actual.getName())),
                remoteOrException);
    }
}

From source file:com.impetus.kundera.metadata.processor.EntityListenersProcessor.java

/**
 * Gets the valid jpa annotations from method.
 * //ww w. j a  v  a 2  s. co  m
 * @param clazz
 *            the clazz
 * @param method
 *            the method
 * @param numberOfParams
 *            the number of params
 * 
 * @return the valid jpa annotations from method
 */
private List<Class<?>> getValidJPAAnnotationsFromMethod(Class<?> clazz, Method method, int numberOfParams) {
    List<Class<?>> annotations = new ArrayList<Class<?>>();

    for (Annotation methodAnnotation : method.getAnnotations()) {
        Class<?> methodAnnotationType = methodAnnotation.annotationType();

        if (isValidJPAEntityListenerAnnotation(methodAnnotationType)) {

            // verify method signature

            // verify exceptions
            boolean hasUncheckedExceptions = false;
            for (Class<?> exception : method.getExceptionTypes()) {
                if (!ReflectUtils.hasSuperClass(RuntimeException.class, exception)) {
                    hasUncheckedExceptions = true;
                    break;
                }
            }

            if (hasUncheckedExceptions) {
                log.info("Skipped method(" + clazz.getName() + "." + method.getName()
                        + ") Must not throw unchecked exceptions.");
                continue;
            }

            // return type must be "void"
            if (!method.getReturnType().getSimpleName().equals("void")) {
                log.info("Skipped method(" + clazz.getName() + "." + method.getName()
                        + ") Must have \"void\" return type.");
                continue;
            }
            // argument must be an Entity or Object
            Class<?>[] paramTypes = method.getParameterTypes();
            if (paramTypes.length != numberOfParams) {
                log.info("Skipped method(" + clazz.getName() + "." + method.getName() + ") Must have "
                        + numberOfParams + " parameter.");
                continue;
            }

            if (numberOfParams == 1) {
                Class<?> parameter = paramTypes[0];
                if (!parameter.getName().equals("java.lang.Object")) {
                    log.info("Skipped method(" + clazz.getName() + "." + method.getName()
                            + ") Must have only 1 \"Object\" type parameter.");
                    continue;
                }
            }

            annotations.add(methodAnnotationType);
        }
    }
    return annotations;
}

From source file:com.strandls.alchemy.rest.client.stubgenerator.ServiceStubGenerator.java

/**
 * Add a rest method to the parent class.
 *
 * @param jCodeModel/*from   ww  w . j  av a 2  s .  c  o  m*/
 *            the code model.
 * @param jParentClass
 *            the parent class.
 * @param method
 *            the method.
 * @param methodMetaData
 *            the method metadata.
 */
private void addMethod(final JCodeModel jCodeModel, final JDefinedClass jParentClass, final Method method,
        final RestMethodMetadata methodMetaData) {
    final String mehtodName = method.getName();

    final JType result = typeToJType(method.getReturnType(), method.getGenericReturnType(), jCodeModel);

    final JMethod jMethod = jParentClass.method(JMod.PUBLIC, result, mehtodName);

    @SuppressWarnings("unchecked")
    final Class<? extends Throwable>[] exceptionTypes = (Class<? extends Throwable>[]) method
            .getExceptionTypes();

    for (final Class<? extends Throwable> exceptionCType : exceptionTypes) {
        jMethod._throws(exceptionCType);
    }

    addSingleValueAnnotation(jMethod, Path.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getPath());

    addListAnnotation(jMethod, Produces.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getProduced());
    addListAnnotation(jMethod, Consumes.class, ANNOTATION_VALUE_PARAM_NAME, methodMetaData.getConsumed());

    final String httpMethod = methodMetaData.getHttpMethod();
    Class<? extends Annotation> httpMethodAnnotation = null;
    if (HttpMethod.GET.equals(httpMethod)) {
        httpMethodAnnotation = GET.class;
    } else if (HttpMethod.PUT.equals(httpMethod)) {
        httpMethodAnnotation = PUT.class;
    } else if (HttpMethod.POST.equals(httpMethod)) {
        httpMethodAnnotation = POST.class;
    } else if (HttpMethod.DELETE.equals(httpMethod)) {
        httpMethodAnnotation = DELETE.class;
    }

    addAnnotation(jMethod, httpMethodAnnotation);

    final Annotation[][] parameterAnnotations = methodMetaData.getParameterAnnotations();

    final Type[] argumentTypes = method.getGenericParameterTypes();
    final Class<?>[] argumentClasses = method.getParameterTypes();
    for (int i = 0; i < argumentTypes.length; i++) {
        final JType jType = typeToJType(argumentClasses[i], argumentTypes[i], jCodeModel);
        // we have lost the actual names, use generic arg names
        final String name = "arg" + i;
        final JVar param = jMethod.param(jType, name);
        if (parameterAnnotations.length > i) {
            for (final Annotation annotation : parameterAnnotations[i]) {
                final JAnnotationUse jAnnotation = param.annotate(annotation.annotationType());
                final String value = getValue(annotation);
                if (value != null) {
                    jAnnotation.param(ANNOTATION_VALUE_PARAM_NAME, value);
                }
            }
        }
    }
}

From source file:com.linecorp.armeria.server.docs.FunctionInfo.java

static FunctionInfo of(Method method, Map<Class<?>, ? extends TBase<?, ?>> sampleRequests,
        @Nullable String namespace, Map<String, String> docStrings) throws ClassNotFoundException {
    requireNonNull(method, "method");

    final String methodName = method.getName();

    final Class<?> serviceClass = method.getDeclaringClass().getDeclaringClass();
    final String serviceName = serviceClass.getName();
    final ClassLoader classLoader = serviceClass.getClassLoader();

    @SuppressWarnings("unchecked")
    Class<? extends TBase<?, ?>> argsClass = (Class<? extends TBase<?, ?>>) Class
            .forName(serviceName + '$' + methodName + "_args", false, classLoader);
    String sampleJsonRequest;/*from www .  j av a2 s.c o  m*/
    TBase<?, ?> sampleRequest = sampleRequests.get(argsClass);
    if (sampleRequest == null) {
        sampleJsonRequest = "";
    } else {
        TSerializer serializer = new TSerializer(ThriftProtocolFactories.TEXT);
        try {
            sampleJsonRequest = serializer.toString(sampleRequest, StandardCharsets.UTF_8.name());
        } catch (TException e) {
            throw new IllegalArgumentException(
                    "Failed to serialize to a memory buffer, this shouldn't ever happen.", e);
        }
    }

    @SuppressWarnings("unchecked")
    final FunctionInfo function = new FunctionInfo(namespace, methodName, argsClass,
            (Class<? extends TBase<?, ?>>) Class.forName(serviceName + '$' + methodName + "_result", false,
                    classLoader),
            (Class<? extends TException>[]) method.getExceptionTypes(), sampleJsonRequest, docStrings);
    return function;
}

From source file:de.bund.bva.pliscommon.serviceapi.core.serviceimpl.ServiceExceptionFassade.java

/**
 * {@inheritDoc}//from  w  w w .  j  a  v  a2 s.c  o  m
 */
@Override
public void validateConfiguration(Class<?> remoteBeanInterface, Object target) {

    Class<?> targetClass = AopUtils.getTargetClass(target);

    for (Method remoteBeanMethod : remoteBeanInterface.getMethods()) {
        Class<? extends PlisTechnicalToException> genericTechnicalToExceptionClass = this.exceptionMappingSource
                .getGenericTechnicalToException(remoteBeanMethod);
        if (genericTechnicalToExceptionClass == null) {
            throw new IllegalStateException("Fehler in der statischen Konfiguration der Exception-Fassade fr "
                    + remoteBeanInterface.getName() + ": Keine generische TO-Exception definiert");
        }
        if (!ArrayUtils.contains(remoteBeanMethod.getExceptionTypes(), genericTechnicalToExceptionClass)) {
            throw new IllegalStateException("Fehler in der statischen Konfiguration der Exception-Fassade fr "
                    + getMethodSignatureString(remoteBeanMethod) + ": Die generische TO-Exception "
                    + genericTechnicalToExceptionClass.getSimpleName()
                    + " ist nicht im RemoteBean-Interface deklariert");
        }

        Method coreMethod = this.methodMappingSource.getTargetMethod(remoteBeanMethod, targetClass);

        for (Class<?> exceptionClass : coreMethod.getExceptionTypes()) {
            if (PlisException.class.isAssignableFrom(exceptionClass)) {
                @SuppressWarnings("unchecked")
                Class<? extends PlisException> plisExceptionClass = (Class<? extends PlisException>) exceptionClass;
                Class<? extends PlisToException> plisToExceptionClass = this.exceptionMappingSource
                        .getToExceptionClass(remoteBeanMethod, plisExceptionClass);
                if (plisToExceptionClass == null) {
                    throw new IllegalStateException(
                            "Fehler in der statischen Konfiguration der Exception-Fassade fr "
                                    + getMethodSignatureString(remoteBeanMethod)
                                    + ": Keine TO-Exception fr AWK-Exception "
                                    + plisExceptionClass.getSimpleName() + " definiert");
                }
                if (!ArrayUtils.contains(remoteBeanMethod.getExceptionTypes(), plisToExceptionClass)) {
                    throw new IllegalStateException(
                            "Fehler in der statischen Konfiguration der Exception-Fassade fr "
                                    + getMethodSignatureString(remoteBeanMethod) + ": Die TO-Exception "
                                    + plisToExceptionClass.getSimpleName()
                                    + " ist nicht im RemoteBean-Interface deklariert");
                }
            }
        }
    }
}

From source file:org.gwtspringhibernate.reference.rlogman.spring.GwtServiceExporter.java

/**
 * Returns true if the {@link java.lang.reflect.Method Method} definition on
 * the service is specified to throw the exception contained in the
 * InvocationTargetException or false otherwise.
 * // w ww  .  ja  v a2s  .  co m
 * NOTE we do not check that the type is serializable here. We assume that
 * it must be otherwise the application would never have been allowed to
 * run.
 * 
 * @param serviceIntfMethod
 * @param e
 * @return
 */
private boolean isExpectedException(Method serviceIntfMethod, Throwable cause) {
    assert (serviceIntfMethod != null);
    assert (cause != null);

    Class[] exceptionsThrown = serviceIntfMethod.getExceptionTypes();
    if (exceptionsThrown.length <= 0) {
        // The method is not specified to throw any exceptions
        //
        return false;
    }

    Class causeType = cause.getClass();

    for (int index = 0; index < exceptionsThrown.length; ++index) {
        Class exceptionThrown = exceptionsThrown[index];
        assert (exceptionThrown != null);

        if (exceptionThrown.isAssignableFrom(causeType)) {
            return true;
        }
    }

    return false;
}