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:org.craftercms.commons.validation.validators.impl.ValidateParamsAspect.java

@Before("@within(org.craftercms.commons.validation.annotations.param.ValidateParams) || "
        + "@annotation(org.craftercms.commons.validation.annotations.param.ValidateParams)")
public void doValidation(JoinPoint joinPoint) {
    Object[] args = joinPoint.getArgs();
    Method method = AopUtils.getActualMethod(joinPoint);
    Annotation[][] allParamAnnotations = method.getParameterAnnotations();
    ValidationResult result = new ValidationResult(errorMessageBundle);

    if (ArrayUtils.isNotEmpty(allParamAnnotations)) {
        for (int i = 0; i < args.length; i++) {
            Object param = args[i];
            Annotation[] paramAnnotations = allParamAnnotations[i];

            for (Annotation annotation : paramAnnotations) {
                validateParam(annotation, param, result);
            }//from  w ww  . j a v a  2 s  . com
        }
    }

    if (result.hasErrors()) {
        String methodStr = method.toGenericString();

        result.setMessage(ValidationUtils.getErrorMessage(errorMessageBundle, INVALID_METHOD_PARAMS_ERROR_CODE,
                methodStr));

        throw new ValidationRuntimeException(result);
    }
}

From source file:com.snaplogic.snaps.uniteller.BaseService.java

/**
 * @param UFSResponseObj/*from w ww  .ja  va  2s . c o  m*/
 * @return Map
 * @throws IllegalAccessException
 * @throws IllegalArgumentException
 * @throws InvocationTargetException
 */
public Map<String, Object> processResponseObj(Object UFSResponseObj)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Map<String, Object> map = new HashMap<String, Object>();
    /* Preparing the map to write the values to output */
    if (UFSResponseObj != null) {
        Class<? extends Object> UFSResponse = UFSResponseObj.getClass();
        for (Method method : findGetters(UFSResponse)) {
            if (method.getReturnType().isPrimitive() || method.getReturnType().isAssignableFrom(String.class)
                    || method.getReturnType().isAssignableFrom(Calendar.class)) {
                map.put(method.getName().substring(3), method.invoke(UFSResponseObj));
            } else {
                log.debug(method.toGenericString());
                map.put(method.getName().substring(3), processNestedResponseObj(method.invoke(UFSResponseObj)));
            }
        }
    }
    return map;
}

From source file:org.springframework.aop.interceptor.AsyncExecutionAspectSupport.java

/**
 * Handles a fatal error thrown while asynchronously invoking the specified
 * {@link Method}.//from   www . j a v a  2s  .com
 * <p>If the return type of the method is a {@link Future} object, the original
 * exception can be propagated by just throwing it at the higher level. However,
 * for all other cases, the exception will not be transmitted back to the client.
 * In that later case, the current {@link AsyncUncaughtExceptionHandler} will be
 * used to manage such exception.
 * @param ex the exception to handle
 * @param method the method that was invoked
 * @param params the parameters used to invoke the method
 */
protected void handleError(Throwable ex, Method method, Object... params) throws Exception {
    if (Future.class.isAssignableFrom(method.getReturnType())) {
        ReflectionUtils.rethrowException(ex);
    } else {
        // Could not transmit the exception to the caller with default executor
        try {
            this.exceptionHandler.handleUncaughtException(ex, method, params);
        } catch (Throwable ex2) {
            logger.error("Exception handler for async method '" + method.toGenericString()
                    + "' threw unexpected exception itself", ex2);
        }
    }
}

From source file:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.java

/**
 * Register the given mapping./* w w  w. ja va2s . com*/
 * <p>This method may be invoked at runtime after initialization has completed.
 * @param mapping the mapping for the handler method
 * @param handler the handler
 * @param method the method
 */
public void registerMapping(T mapping, Object handler, Method method) {
    if (logger.isTraceEnabled()) {
        logger.trace("Register \"" + mapping + "\" to " + method.toGenericString());
    }
    this.mappingRegistry.register(mapping, handler, method);
}

From source file:de.zib.gndms.infra.system.PluggableTaskFlowProvider.java

@PreDestroy
public void destroyPlugins() {

    final Map<String, TaskFlowFactory> factories = getFactories();

    for (TaskFlowFactory factory : factories.values()) {
        for (Method method : factory.getClass().getDeclaredMethods()) {
            if (method.getAnnotation(PreDestroy.class) != null) {
                ReflectionUtils.makeAccessible(method);
                try {
                    method.invoke(factory, (Object[]) null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "THIS IS NOT HAPPENING!!! Method had been made accessible but is not accessible anyway",
                            e);//from w  ww  . j a  v a  2  s .  c  o  m
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(
                            "Could not call PreDestroy method (" + method.toGenericString() + ")", e);
                }
            }
        }
    }
}

From source file:org.xwiki.rendering.xdomxmlcurrent.internal.renderer.XDOMXMLChainingStreamRenderer.java

@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    Object result = null;/*from www . j  a v  a 2 s.  c o  m*/

    if (method.getName().equals("setContentHandler")) {
        this.contentHandler = (ContentHandler) args[0];
    } else if (method.getName().equals("getContentHandler")) {
        result = this.contentHandler;
    } else if (method.getName().startsWith("begin")) {
        beginEvent(method.getName(), args);
    } else if (method.getName().startsWith("end")) {
        endEvent(method.getName());
    } else if (method.getName().startsWith("on")) {
        onEvent(method.getName(), args);
    } else {
        throw new NoSuchMethodException(method.toGenericString());
    }

    return result;
}

From source file:de.zib.gndms.infra.system.PluggableTaskFlowProvider.java

public void loadPlugins(boolean checkDeps) {

    Map<String, TaskFlowFactory> plugins = new HashMap<String, TaskFlowFactory>(10);

    ServiceLoader<TaskFlowFactory> sl;
    if (getCl() != null)
        sl = ServiceLoader.load(TaskFlowFactory.class, getCl());
    else// ww  w  . j  av a2 s . c  om
        sl = ServiceLoader.load(TaskFlowFactory.class);

    for (TaskFlowFactory bp : sl) {
        try {
            register(bp, plugins);
        } catch (IllegalStateException e) {
            logger.warn(e.getMessage());
        }
    }

    setFactories(plugins);

    if (checkDeps)
        checkDeps();

    // call all PostConstruct methods
    for (TaskFlowFactory bp : sl) {
        for (Method method : bp.getClass().getDeclaredMethods()) {
            if (method.getAnnotation(PostConstruct.class) != null) {
                ReflectionUtils.makeAccessible(method);
                try {
                    method.invoke(bp, (Object[]) null);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(
                            "THIS IS NOT HAPPENING!!! Method had been made accessible but is not accessible anyway",
                            e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(
                            "Could not call PostConstruct method (" + method.toGenericString() + ")", e);
                }
            }
        }
    }

    // todo this is just for development change this for releases:
    //        if ( getFactories().size() == 0 )
    //            throw new IllegalStateException( "no plugs found" );
}

From source file:org.topazproject.otm.metadata.AnnotationClassMetaFactory.java

private void createMeta(ClassDefinition def, Class<?> clazz, String uriPrefix) throws OtmException {
    sf.addDefinition(def);/* ww w  .  ja  v  a  2 s.c o m*/

    ClassBinding bin = sf.getClassBinding(def.getName());
    bin.bind(EntityMode.POJO, new ClassBinder(clazz));

    Map<String, PropertyDefFactory> factories = new HashMap<String, PropertyDefFactory>();

    for (Method method : clazz.getDeclaredMethods()) {
        if (!isAnnotated(method))
            continue;

        if (method.getAnnotation(SubClassResolver.class) != null) {
            registerSubClassResolver(def, method);
            continue;
        }

        Property property = Property.toProperty(method);

        if (property == null)
            throw new OtmException("'" + method.toGenericString() + "' is not a valid getter or setter");

        PropertyDefFactory pi = factories.get(property.getName());

        if (pi != null) {
            if (method.equals(pi.property.getReadMethod()) || method.equals(pi.property.getWriteMethod()))
                continue;

            throw new OtmException("Duplicate property " + property);
        }

        validate(property, def);
        factories.put(property.getName(), new PropertyDefFactory(def, property));
    }

    if (def instanceof EntityDefinition) {
        if (clazz.getGenericSuperclass() instanceof ParameterizedType)
            addGenericsSyntheticProps(def, clazz, (ParameterizedType) clazz.getGenericSuperclass(), factories);

        for (Type t : clazz.getGenericInterfaces())
            if (t instanceof ParameterizedType)
                addGenericsSyntheticProps(def, clazz, (ParameterizedType) t, factories);

        Map<String, Map<String, String>> supersedes = new HashMap<String, Map<String, String>>();
        buildSupersedes((EntityDefinition) def, supersedes);

        for (String name : supersedes.keySet()) {
            PropertyDefFactory pi = factories.get(name);
            if (pi != null)
                pi.setSupersedes(supersedes.get(name));
        }
    }

    for (PropertyDefFactory fi : factories.values()) {
        PropertyDefinition d = fi.getDefinition(sf, uriPrefix);
        if (d != null) {
            sf.addDefinition(d);
            bin.addBinderFactory(new PropertyBinderFactory(fi.name, fi.property));
        }

        SearchableDefinition sd = fi.getSearchableDefinition(sf, d instanceof BlobDefinition);
        if (sd != null)
            sf.addDefinition(sd);
    }
}

From source file:net.sf.jabb.util.web.WebApplicationConfiguration.java

/**
 * Scan all the beans for menu items//from w ww  .j a  v a2  s . c  o m
 */
public void scanForMenuItems() {
    Map<String, Map<String, MenuItemExt>> allMenuItems = new PutIfAbsentMap<String, Map<String, MenuItemExt>>(
            new HashMap<String, Map<String, MenuItemExt>>(),
            new MapValueFactory<String, Map<String, MenuItemExt>>() {
                @Override
                public Map<String, MenuItemExt> createValue(String key) {
                    return new TreeMap<String, MenuItemExt>();
                }
            });
    //new HashMap<String, Map<String, MenuItemExt>>();   // <menuName, <path, MenuItemExt>>

    // Get all beans that may have menu items defined
    Map<String, Object> beans = appContext.getBeansWithAnnotation(WebMenu.class);
    beans.putAll(appContext.getBeansWithAnnotation(RequestMapping.class));

    // Find all menu items 
    for (Object bean : beans.values()) {
        Class<?> beanClass;
        if (bean instanceof Advised) { // if EnhancerBySpringCGLIB
            beanClass = ((Advised) bean).getTargetClass();
        } else {
            beanClass = bean.getClass();
        }

        // Check class level annotations first
        RequestMapping classRequestMapping = beanClass.getAnnotation(RequestMapping.class);
        WebMenu classWebMenu = beanClass.getAnnotation(WebMenu.class);
        if (true) {//classWebMenu != null && classWebMenu.value().length() != 0){   // not hidden
            MenuItemExt classMenuItem = new MenuItemExt(classWebMenu, classRequestMapping);

            String basePath = classMenuItem.path != null ? classMenuItem.path : "";
            if (classMenuItem.title != null && classMenuItem.title.length() > 0) { // it is also a visible menu item
                MenuItemExt existing = allMenuItems.get(classMenuItem.menuName).put(basePath, classMenuItem);
                if (existing != null) {
                    log.error("Duplicated web menu item definitions in " + beanClass.getName()
                            + ".\n\tExisting: " + existing + "\n\tCurrent: " + classMenuItem);
                }
            }

            // Then look into all the methods
            for (Method method : beanClass.getDeclaredMethods()) {
                RequestMapping methodRequestMapping = method.getAnnotation(RequestMapping.class);
                WebMenu methodWebMenu = method.getAnnotation(WebMenu.class);
                if (methodWebMenu != null && methodWebMenu.value().length() != 0) { // not hidden
                    MenuItemExt methodMenuItem = new MenuItemExt(methodWebMenu, methodRequestMapping,
                            classMenuItem);

                    if (methodMenuItem.menuName != null) {
                        MenuItemExt existing = allMenuItems.get(methodMenuItem.menuName)
                                .put(methodMenuItem.path, methodMenuItem);
                        if (existing != null) {
                            log.error("Duplicated web menu item definitions in " + beanClass.getName() + "."
                                    + method.toGenericString() + ".\n\tExisting: " + existing + "\n\tCurrent: "
                                    + methodMenuItem);
                        }
                    }
                }
            }
        }
    }

    // construct menu trees
    menus = new HashMap<String, WebMenuItem>();
    menuItemPaths = new HashMap<String, Map<String, WebMenuItem>>();

    for (Map.Entry<String, Map<String, MenuItemExt>> menuItems : allMenuItems.entrySet()) {
        String menuName = menuItems.getKey();
        Map<String, MenuItemExt> items = menuItems.getValue();
        WebMenuItem root = new WebMenuItem();
        root.title = menuName; // for the root, set its title as menu name
        root.breadcrumbs = new ArrayList<WebMenuItem>(1);
        root.breadcrumbs.add(root); // root is the first in breadcrumbs
        menus.put(menuName, root);
        menuItemPaths.put(menuName, new HashMap<String, WebMenuItem>());
        for (MenuItemExt itemExt : items.values()) {
            String path = itemExt.path;
            WebMenuItem parent = null;
            do {
                path = StringUtils.substringBeforeLast(path, "/");
                if (path == null || path.indexOf('/') == -1) {
                    parent = root;
                    break;
                }
                parent = items.get(path);
            } while (parent == null);
            parent.addSubItem(itemExt);
        }

        // clean up the tree
        cleanUpMenuTree(root, menuName);
        log.info("Menu '" + menuName + "' loaded:\n" + root);
    }
}

From source file:com.chiorichan.event.EventBus.java

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

    Map<Class<? extends Event>, Set<RegisteredListener>> ret = new HashMap<Class<? extends Event>, Set<RegisteredListener>>();
    Set<Method> methods;
    try {/*from   w  w w. j  a v a2  s  . co 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) {
        Loader.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])) {
            Loader.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;
                }
                Loader.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;
}