Example usage for java.lang.reflect Method toGenericString

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

Introduction

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

Prototype

@Override
public String toGenericString() 

Source Link

Document

Returns a string describing this Method , including type parameters.

Usage

From source file:com.chiorichan.plugin.loader.JavaPluginLoader.java

public Map<Class<? extends Event>, Set<RegisteredListener>> createRegisteredListeners(Listener listener,
        final Plugin plugin) {
    Validate.notNull(plugin, "Plugin can not be null");
    Validate.notNull(listener, "Listener can not be null");

    boolean useTimings = Loader.getEventBus().useTimings();
    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {/*from  w  ww .j a va  2 s  .c o m*/
        Method[] publicMethods = listener.getClass().getMethods();
        methods = new HashSet<Method>(publicMethods.length, Float.MAX_VALUE);
        for (Method method : publicMethods) {
            methods.add(method);
        }
        for (Method method : listener.getClass().getDeclaredMethods()) {
            methods.add(method);
        }
    } catch (NoClassDefFoundError e) {
        PluginManager.getLogger()
                .severe("Plugin " + plugin.getDescription().getFullName()
                        + " has failed to register events for " + listener.getClass() + " because "
                        + e.getMessage() + " does not exist.");
        return ret;
    }

    for (final Method method : methods) {
        final EventHandler eh = method.getAnnotation(EventHandler.class);
        if (eh == null)
            continue;
        final Class<?> checkClass;
        if (method.getParameterTypes().length != 1
                || !Event.class.isAssignableFrom(checkClass = method.getParameterTypes()[0])) {
            PluginManager.getLogger()
                    .severe(plugin.getDescription().getFullName()
                            + " attempted to register an invalid EventHandler method signature \""
                            + method.toGenericString() + "\" in " + listener.getClass());
            continue;
        }
        final Class<? extends Event> eventClass = checkClass.asSubclass(Event.class);
        method.setAccessible(true);
        Set<RegisteredListener> eventSet = ret.get(eventClass);
        if (eventSet == null) {
            eventSet = new HashSet<RegisteredListener>();
            ret.put(eventClass, eventSet);
        }

        for (Class<?> clazz = eventClass; Event.class.isAssignableFrom(clazz); clazz = clazz.getSuperclass()) {
            // This loop checks for extending deprecated events
            if (clazz.getAnnotation(Deprecated.class) != null) {
                Warning warning = clazz.getAnnotation(Warning.class);
                WarningState warningState = Loader.getInstance().getWarningState();
                if (!warningState.printFor(warning)) {
                    break;
                }
                PluginManager.getLogger().log(Level.WARNING, String.format(
                        "\"%s\" has registered a listener for %s on method \"%s\", but the event is Deprecated."
                                + " \"%s\"; please notify the authors %s.",
                        plugin.getDescription().getFullName(), clazz.getName(), method.toGenericString(),
                        (warning != null && warning.reason().length() != 0) ? warning.reason()
                                : "Server performance will be affected",
                        Arrays.toString(plugin.getDescription().getAuthors().toArray())),
                        warningState == WarningState.ON ? new AuthorNagException(null) : null);
                break;
            }
        }

        EventExecutor executor = new EventExecutor() {
            public void execute(Listener listener, Event event) throws EventException {
                try {
                    if (!eventClass.isAssignableFrom(event.getClass())) {
                        return;
                    }
                    method.invoke(listener, event);
                } catch (InvocationTargetException ex) {
                    throw new EventException(ex.getCause());
                } catch (Throwable t) {
                    throw new EventException(t);
                }
            }
        };
        if (useTimings) {
            eventSet.add(new TimedRegisteredListener(listener, executor, eh.priority(), plugin,
                    eh.ignoreCancelled()));
        } else {
            eventSet.add(
                    new RegisteredListener(listener, executor, eh.priority(), plugin, eh.ignoreCancelled()));
        }
    }
    return ret;
}

From source file:org.apache.axis2.jaxws.WebServiceExceptionLogger.java

/**
 * Logs an error if the exception thrown by @WebMethod m is not a checked exception.
 * If debug logging is enabled, all exceptions are logged.
 * @param method/*from  w  w  w  .  j a v  a 2  s.com*/
 * @param throwable
 * @param logFully (if true then the exception is logged, otherwise only the class and stack is logged)
 * @param serviceImplClass class of service implementation
 * @param serviceInstance 
 * @param args Object[] arguments pass to method
 */
public static void log(Method method, Throwable throwable, boolean logFully, Class serviceImplClass,
        Object serviceInstance, Object[] args) {

    // Must have debug or error logging enabled
    if (!log.isDebugEnabled() && !log.isErrorEnabled()) {
        return;
    }

    // Get the root of the exception
    Throwable rootT = null;
    if (throwable instanceof InvocationTargetException) {
        rootT = ((InvocationTargetException) throwable).getTargetException();
    }

    String name = rootT.getClass().getName();
    String stack = stackToString(rootT);

    // Determine if this is a checked exception or non-checked exception
    Class checkedException = JavaUtils.getCheckedException(rootT, method);

    if (checkedException == null) {
        // Only log errors for non-checked exceptions
        if (log.isErrorEnabled()) {
            String text = "";
            if (logFully) {
                text = Messages.getMessage("failureLogger", name, rootT.toString());

            } else {
                text = Messages.getMessage("failureLogger", name, stack);
            }
            log.error(text);
        }

    }

    // Full logging if debug is enabled.
    if (log.isDebugEnabled()) {
        log.debug("Exception invoking a method of " + serviceImplClass.toString() + " of instance "
                + serviceInstance.toString());
        log.debug("Exception type thrown: " + throwable.getClass().getName());
        if (rootT != null) {
            log.debug("Root Exception type thrown: " + rootT.getClass().getName());
        }
        if (checkedException != null) {
            log.debug("The exception is an instance of checked exception: " + checkedException.getName());
        }

        // Extra trace if ElementNSImpl incompatibility problem.
        // The incompatibility exception occurs if the JAXB Unmarshaller 
        // unmarshals to a dom element instead of a generated object.  This can 
        // result in class cast exceptions.  The solution is usually a missing
        // @XmlSeeAlso annotation in the jaxws or jaxb classes. 
        if (rootT.toString().contains("org.apache.xerces.dom.ElementNSImpl incompatible")) {
            log.debug("This exception may be due to a missing @XmlSeeAlso in the client's jaxws or"
                    + " jaxb classes.");
        }
        log.debug("Method = " + method.toGenericString());
        for (int i = 0; i < args.length; i++) {
            String value = (args[i] == null) ? "null" : args[i].getClass().toString();
            log.debug(" Argument[" + i + "] is " + value);
        }
    }
    return;

}

From source file:kenh.xscript.impl.BaseElement.java

@Override
public int invoke() throws UnsupportedScriptException {

    logger.info(getInfo());/*  ww  w .  j ava2 s  .  c om*/

    Annotation ignoreSuperClass = this.getClass().getAnnotation(IgnoreSuperClass.class);

    Method[] methods = this.getClass().getMethods();
    if (ignoreSuperClass != null)
        methods = this.getClass().getDeclaredMethods();

    for (Method method : methods) {

        String name = method.getName();
        Class[] classes = method.getParameterTypes();
        Annotation primal = method.getAnnotation(Primal.class);
        Annotation process = method.getAnnotation(Processing.class);
        Annotation[][] annotations = method.getParameterAnnotations();

        if (process == null && !name.equals(METHOD))
            continue;

        boolean parsedAll = true;
        if (primal != null)
            parsedAll = false;

        boolean find = true; // true, find the suitable method to invoke

        Object[] objs = new Object[annotations.length];

        if (annotations.length == 0) { // non-parameter method
            if (attributes.size() == 0)
                find = true;
            else {
                logger.trace("Failure(no parameter required): " + method.toGenericString());
                find = false;
            }
        } else {

            if (annotations.length != attributes.size())
                continue;

            for (int i = 0; i < annotations.length; i++) {

                boolean parsed = parsedAll; // parse all attribute
                boolean reparse = false; // has Reparse annotation

                Annotation[] anns = annotations[i];
                Class class2 = classes[i];

                if (anns == null) {
                    logger.trace("Failure(parameter without annotation): " + method.toGenericString());
                    find = false;
                    break;
                }
                String attributeName = null;
                for (Annotation ann : anns) {
                    if (ann instanceof Attribute) {
                        attributeName = ((Attribute) ann).value();
                    }
                    if (ann instanceof Primal) {
                        parsed = false;
                    }
                    if (ann instanceof Reparse) {
                        reparse = true;
                    }
                }

                if (StringUtils.isBlank(attributeName)) {
                    logger.trace("Failure(annotation value is empty): " + method.toGenericString());
                    find = false;
                    break;
                }
                if (!attributes.containsKey(attributeName)) {
                    logger.trace("Failure(can't find attribute[" + attributeName + "]): "
                            + method.toGenericString());
                    find = false;
                    break;
                }

                Object attrValue = null;
                try {
                    // parse the parameter of process method
                    if (parsed) {
                        if (reparse) {
                            attrValue = env.parse("{" + attributes.get(attributeName) + "}");
                        } else {
                            attrValue = env.parse(attributes.get(attributeName));
                        }
                    } else {
                        attrValue = attributes.get(attributeName);
                    }

                } catch (UnsupportedExpressionException e) {
                    logger.trace("Failure(error[" + attributeName + ", " + e.getMessage() + "]): "
                            + method.toGenericString());
                    find = false;
                    //break;
                    throw new UnsupportedScriptException(this, e);
                }
                Class class1 = attrValue.getClass();

                if (class2.isAssignableFrom(class1) || class2 == Object.class) {
                    objs[i] = attrValue;

                } else if (class1 == String.class) {
                    try {
                        Object obj = Environment.convert((String) attrValue, class2);
                        if (obj == null) {
                            logger.trace("Failure(Convert failure[" + attributeName + ", null]): "
                                    + method.toGenericString());
                            find = false;
                            break;
                        } else {
                            objs[i] = obj;
                        }
                    } catch (Exception e) {
                        logger.trace("Failure(Convert exception[" + attributeName + "]): "
                                + method.toGenericString());
                        find = false;
                        break;
                        //UnsupportedScriptException ex = new UnsupportedScriptException(this, e);
                        //throw ex;
                    }
                } else {
                    logger.trace("Failure(Unsupported class[" + attributeName + ", " + class1 + ", " + class2
                            + "]): " + method.toGenericString());
                    find = false;
                    break;
                }
            }
        }

        if (find) {
            try {
                logger.debug("Invoke: " + method.toGenericString());
                if (method.getReturnType() == int.class) {
                    return (Integer) method.invoke(this, objs);
                } else if (method.getReturnType() == Integer.class) {
                    return (Integer) method.invoke(this, objs);
                } else {
                    method.invoke(this, objs);
                    return NONE;
                }
            } catch (InvocationTargetException e) {
                Throwable t = e.getTargetException();
                if (t instanceof UnsupportedScriptException) {
                    throw (UnsupportedScriptException) t;
                } else {
                    UnsupportedScriptException ex = new UnsupportedScriptException(this, e);
                    throw ex;
                }

            } catch (Exception e) {
                UnsupportedScriptException ex = new UnsupportedScriptException(this, e);
                throw ex;
            }
        }
    }

    throw new UnsupportedScriptException(this, "Can't fine the method to process.");
}