Example usage for java.lang.reflect Method isAnnotationPresent

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

Introduction

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

Prototype

@Override
public boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) 

Source Link

Usage

From source file:com.orion.plugin.Plugin.java

/**
 * Register a <tt>Command</tt> for this <tt>Plugin</tt>
 * //from  w  w  w .ja v  a  2 s .  co  m
 * @author Daniele Pantaleone
 * @param  name The name of the <tt>Command</tt>
 * @param  alias An alias for the <tt>Command</tt>
 * @param  group The minimum <tt>Group</tt> that can access the <tt>Command</tt>
 **/
protected void registerCommand(String name, String alias, String group) {

    try {

        // Checking name and alias value
        if ((name != null) && (name.trim().isEmpty()))
            name = null;
        if ((alias != null) && (alias.trim().isEmpty()))
            alias = null;

        // Checking if we got a proper command name as input
        // If it's detected as NULL the command will not be registered
        if (name == null)
            throw new CommandRegisterException("command name detected as NULL or empty string");

        // Trimming and lowercasing the name
        name = name.toLowerCase().trim();

        // Checking if the command name is already mapped over another method
        if (this.regcommands.containsKey(name))
            throw new CommandRegisterException("command !" + name + " is already mapped over another command");

        // Checking if the command alias is already mapped over another method
        if (alias != null) {

            // Trimming and lowercasing the alias
            alias = alias.toLowerCase().trim();

            if (this.regcommands.containsKey(alias)) {
                this.warn("Skipping alias registration for command !" + name + ": alias !" + alias
                        + " is already mapped over another command");
                alias = null;
            }

        }

        // Getting the Group object
        Group minGroup = this.groups.getByMagic(group);

        // Checking minGroup
        if (minGroup == null) {
            minGroup = this.groups.getByKeyword("superadmin");
            this.warn("Minimum required group level detected as NULL for command !" + name
                    + ". Casting to default: " + minGroup.getName());
        }

        // Getting the plugin method
        Method method = this.getClass().getMethod(
                "Cmd" + Character.toUpperCase(name.charAt(0)) + name.substring(1).toLowerCase(), Command.class);

        if (method.isAnnotationPresent(Dependency.class)) {

            // The specified command has some dependancies that need
            // to be checked before to register it in the command list
            Dependency dependancy = method.getAnnotation(Dependency.class);

            if ((dependancy.console().equals(UrT42Console.class))
                    && (!this.console.getClass().equals(UrT42Console.class))) {
                this.log.debug("Skipping command !" + name + " registration. !" + name
                        + " is available as from Urban Terror 4.2");
                return;
            }

        }

        RegisteredCommand command = new RegisteredCommand(method, this, minGroup);
        this.regcommands.put(name, alias, command);
        this.debug("Registered command [ name : " + name + " | alias : " + alias + " | minLevel : "
                + minGroup.getLevel() + " ]");

    } catch (ClassNotFoundException | SQLException | NoSuchMethodException | SecurityException e) {

        // Logging the exception
        this.error("Unable to register command !" + name, e);

    } catch (CommandRegisterException e) {

        // Log a warning so the user will notice
        this.warn("Unable to register command", e);

    }

}

From source file:org.b3log.latke.ioc.JavassistMethodHandler.java

@Override
public Object invoke(final Object proxy, final Method method, final Method proceed, final Object[] params)
        throws Throwable {
    LOGGER.trace("Processing invocation [" + method.toString() + "]");

    AtomicInteger calls = CALLS.get();
    if (null == calls) {
        synchronized (this) {
            if (null == calls) {
                calls = new AtomicInteger(0);
                CALLS.set(calls);//  ww  w  . ja v  a2 s .c o  m
            }
        }
    }
    calls.incrementAndGet();

    // Invocation with transaction handle
    final boolean withTransactionalAnno = method.isAnnotationPresent(Transactional.class);
    JdbcTransaction transaction = JdbcRepository.TX.get();
    final boolean alreadyInTransaction = null != transaction;
    final boolean needHandleTrans = withTransactionalAnno && !alreadyInTransaction;

    // Transaction Propagation: REQUIRED (Support a current transaction, create a new one if none exists)
    if (needHandleTrans) {
        try {
            transaction = new JdbcTransaction();
        } catch (final SQLException e) {
            LOGGER.log(Level.ERROR, "Failed to initialize JDBC transaction", e);

            throw new IllegalStateException("Begin a transaction failed");
        }

        JdbcRepository.TX.set(transaction);
    }

    Object ret;
    try {
        ret = proceed.invoke(proxy, params);

        if (needHandleTrans) {
            transaction.commit();
        }
    } catch (final InvocationTargetException e) {
        if (needHandleTrans) {
            if (transaction.isActive()) {
                transaction.rollback();
            }
        }

        throw e.getTargetException();
    }

    if (0 == calls.decrementAndGet()) {
        CALLS.set(null);
        final Connection connection = JdbcRepository.CONN.get();
        if (null != connection) {
            connection.close();
            JdbcRepository.CONN.set(null);
        }
    }

    return ret;
}

From source file:com.zenesis.qx.remote.ProxyTypeImpl.java

/**
 * Constructor, used for defining interfaces which are to be proxied
 * @param className/*from w ww  .jav a  2  s. c  o  m*/
 * @param methods
 */
public ProxyTypeImpl(ProxyType superType, Class clazz, Set<ProxyType> interfaces) {
    super();
    if (interfaces == null)
        interfaces = Collections.EMPTY_SET;
    this.superType = superType;
    this.interfaces = interfaces;
    this.clazz = clazz;

    MethodsCompiler methodsCompiler = new MethodsCompiler();

    // Get a complete list of methods from the interfaces that the new class has to 
    //   implement; we include methods marked as DoNotProxy so that we can check for 
    //   conflicting instructions
    if (!clazz.isInterface()) {
        // Get a full list of the interfaces which our class has to implement
        HashSet<ProxyType> allInterfaces = new HashSet<ProxyType>();
        getAllInterfaces(allInterfaces, interfaces);

        for (ProxyType ifcType : allInterfaces) {
            try {
                methodsCompiler.addMethods(Class.forName(ifcType.getClassName()), true);
            } catch (ClassNotFoundException e) {
                throw new IllegalStateException("Cannot find class " + ifcType.getClassName());
            }
        }
    }

    boolean defaultProxy = false;
    if (clazz.isInterface())
        defaultProxy = true;
    else {
        for (Class tmp = clazz; tmp != null; tmp = tmp.getSuperclass()) {
            if (factoryMethod == null) {
                for (Method method : tmp.getDeclaredMethods()) {
                    if (method.isAnnotationPresent(FactoryMethod.class)) {
                        if (!Modifier.isStatic(method.getModifiers()))
                            throw new IllegalStateException("Cannot use method " + method
                                    + " as FactoryMethod because it is not static");
                        factoryMethod = method;
                        method.setAccessible(true);
                        break;
                    }
                }
            }
            if (tmp.isAnnotationPresent(AlwaysProxy.class)) {
                defaultProxy = true;
                break;
            } else if (tmp.isAnnotationPresent(ExplicitProxyOnly.class)) {
                break;
            }
        }
    }

    // If the class does not have any proxied interfaces or the class is marked with
    //   the AlwaysProxy annotation, then we take methods from the class definition
    methodsCompiler.addMethods(clazz, defaultProxy);

    methodsCompiler.checkValid();
    methodsCompiler.removeSuperTypeMethods();

    // Load properties
    HashMap<String, ProxyEvent> events = new HashMap<String, ProxyEvent>();
    HashMap<String, ProxyProperty> properties = new HashMap<String, ProxyProperty>();
    Properties annoProperties = (Properties) clazz.getAnnotation(Properties.class);
    if (annoProperties != null) {
        for (Property anno : annoProperties.value()) {
            ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }
    for (Field field : clazz.getDeclaredFields()) {
        Property anno = field.getAnnotation(Property.class);
        if (anno != null) {
            ProxyProperty property = new ProxyPropertyImpl(clazz,
                    anno.value().length() > 0 ? anno.value() : field.getName(), anno, annoProperties);
            properties.put(property.getName(), property);
            ProxyEvent event = property.getEvent();
            if (event != null)
                events.put(event.getName(), event);
        }
    }

    for (Method method : clazz.getDeclaredMethods()) {
        String name = method.getName();
        if (name.length() < 4 || !name.startsWith("get") || !Character.isUpperCase(name.charAt(3)))
            continue;
        Property anno = method.getAnnotation(Property.class);
        if (anno == null)
            continue;

        name = Character.toLowerCase(name.charAt(3)) + name.substring(4);
        if (properties.containsKey(name))
            continue;

        ProxyProperty property = new ProxyPropertyImpl(clazz, anno.value().length() > 0 ? anno.value() : name,
                anno, annoProperties);
        properties.put(property.getName(), property);
        ProxyEvent event = property.getEvent();
        if (event != null)
            events.put(event.getName(), event);
    }

    // Classes need to have all inherited properties added
    if (!clazz.isInterface()) {
        for (ProxyType ifc : interfaces)
            addProperties((ProxyTypeImpl) ifc, properties);
    }

    // Remove property accessors
    for (ProxyProperty prop : properties.values())
        methodsCompiler.removePropertyAccessors((ProxyPropertyImpl) prop);

    // Load events
    if (clazz.isAnnotationPresent(Events.class)) {
        Events annoEvents = (Events) clazz.getAnnotation(Events.class);
        for (Event annoEvent : annoEvents.value()) {
            if (!events.containsKey(annoEvent.value()))
                events.put(annoEvent.value(), new ProxyEvent(annoEvent));
        }
    }

    // Classes need to have all inherited events added
    if (!clazz.isInterface()) {
        for (ProxyType type : interfaces)
            addEvents((ProxyTypeImpl) type, events);
    }

    // Save
    this.properties = properties.isEmpty() ? null : properties;
    this.events = events.isEmpty() ? null : events;
    this.methods = methodsCompiler.toArray();
}

From source file:org.mifos.framework.struts.action.BaseAction.java

@SuppressWarnings("unchecked")
protected boolean isCloseSessionAnnotationPresent(@SuppressWarnings("unused") ActionForm actionForm,
        HttpServletRequest request) {//from  w ww .  j av a 2s.c  om
    boolean isAnnotationPresent = false;
    try {
        String methodName = request.getParameter(MethodNameConstants.METHOD);
        Method methodToExecute = this.clazz.getMethod(methodName, new Class[] { ActionMapping.class,
                ActionForm.class, HttpServletRequest.class, HttpServletResponse.class });
        isAnnotationPresent = methodToExecute.isAnnotationPresent(CloseSession.class);
    } catch (NoSuchMethodException e) {
        throw new RuntimeException(e);
    }
    return isAnnotationPresent;
}

From source file:com.gu.management.spring.ManagementUrlDiscoveryService.java

private Collection<String> getUrlsForController(String baseUrl, Object controller) {
    List<String> urlsForController = Lists.newArrayList();

    if (controller instanceof MultiActionController) {
        MultiActionController multiController = (MultiActionController) controller;
        MethodNameResolver methodNameResolver = multiController.getMethodNameResolver();

        // look for an explicit mapping first
        if (methodNameResolver instanceof PropertiesMethodNameResolver) {
            Set<Object> keySet = ((PropertiesMethodNameResolver) methodNameResolver).getMappings().keySet();
            for (Object key : keySet) {
                LOGGER.debug(String.format("Adding %s due to explict mapping in MultiActionController", key));
                urlsForController.add(((String) key));
            }//from www . ja  va 2s.  c om
            return urlsForController;
        }

        // now look for auto mappings
        for (Method method : controller.getClass().getDeclaredMethods()) {
            if (isRequestableMethod(method)) {
                String methodPath = replaceDoubleStarWithValue(method.getName(), baseUrl);
                LOGGER.debug(String.format("Adding %s due to implicit mapping in MultiActionController",
                        methodPath));
                urlsForController.add(methodPath);
            }
        }

        return urlsForController;
    }

    for (Method method : controller.getClass().getDeclaredMethods()) {
        if (method.isAnnotationPresent(RequestMapping.class)) {
            for (String url : method.getAnnotation(RequestMapping.class).value()) {
                LOGGER.debug(String.format("Adding %s due to @RequestMapping attribute", url));
                urlsForController.add(url);
            }
        }
    }

    if (controller instanceof Controller && urlsForController.isEmpty()) {
        String methodPath = replaceDoubleStarWithValue("", baseUrl);
        LOGGER.debug(String.format(
                "Adding %s because it maps to a simple controller and we haven't found anything else",
                methodPath));
        urlsForController.add(methodPath);
    }

    return urlsForController;
}

From source file:com.evolveum.midpoint.prism.parser.PrismBeanInspector.java

private List<String> getPropOrderUncached(Class<? extends Object> beanClass) {
    List<String> propOrder;

    // Superclass first!
    Class superclass = beanClass.getSuperclass();
    if (superclass.equals(Object.class) || superclass.getAnnotation(XmlType.class) == null) {
        propOrder = new ArrayList<>();
    } else {//  w  w w  .  j  a  v a 2  s  . c  o  m
        propOrder = new ArrayList<>(getPropOrder(superclass));
    }

    XmlType xmlType = beanClass.getAnnotation(XmlType.class);
    if (xmlType == null) {
        throw new IllegalArgumentException(
                "Cannot marshall " + beanClass + " it does not have @XmlType annotation");
    }

    String[] myPropOrder = xmlType.propOrder();
    if (myPropOrder != null) {
        for (String myProp : myPropOrder) {
            if (StringUtils.isNotBlank(myProp)) {
                // some properties starts with underscore..we don't want to serialize them with underscore, so remove it..
                if (myProp.startsWith("_")) {
                    myProp = myProp.replace("_", "");
                }
                propOrder.add(myProp);
            }
        }
    }

    Field[] fields = beanClass.getDeclaredFields();
    for (int i = 0; i < fields.length; i++) {
        Field field = fields[i];
        if (field.isAnnotationPresent(XmlAttribute.class)) {
            propOrder.add(field.getName());
        }
    }

    Method[] methods = beanClass.getDeclaredMethods();
    for (int i = 0; i < methods.length; i++) {
        Method method = methods[i];
        if (method.isAnnotationPresent(XmlAttribute.class)) {
            //            System.out.println("methodName: " + method.getName());
            String propname = getPropertyNameFromGetter(method.getName());
            //StringUtils.uncapitalize(StringUtils.removeStart("get", method.getName()))
            propOrder.add(propname);
        }
    }

    return propOrder;
}

From source file:com.hablutzel.cmdline.CommandLineApplication.java

/**
 * This method scans the subclass for annotations
 * that denote the command line options and arguments,
 * and configures the systems so that the members that
 * have been annotated in that way are set up for calling
 * at command line processing time//from  w  ww . j a v  a 2  s. co  m
 *
 */
private final void configure() throws CommandLineException {

    // Find all the fields in our subclass
    for (Method method : this.getClass().getDeclaredMethods()) {

        // If this method is marked with a  command line option, then configure
        // a corresponding commons-cli command line option here
        if (method.isAnnotationPresent(CommandLineOption.class)) {
            CommandLineOption commandLineOption = method.getDeclaredAnnotation(CommandLineOption.class);
            if (commandLineOption != null) {

                // Get the basic information about the option - the name and description
                String shortName = commandLineOption.shortForm().equals("") ? null
                        : commandLineOption.shortForm();
                String longName = commandLineOption.longForm().equals("") ? null : commandLineOption.longForm();
                String description = commandLineOption.usage();

                // If both the short and long name are null, then use the field name as the long name
                if (shortName == null && longName == null) {
                    longName = method.getName();
                }

                // The signature of the method determines what kind of command line
                // option is allowed. Basically, if the method does not take an argument,
                // then the option does not take arguments either. In this case, the
                // method is just called when the option is present.
                //
                // If the method does take argument, there are restrictions on the arguments
                // that are allowed. If there is a single argument, then the method will be
                // called for each argument supplied to the option. Generally in this case you
                // want the maximum number of option arguments to be 1, and you are just getting
                // the value of the argument. On the other hand, if the single argument is either
                // and array or a List<>, then the arguments will be passed in as an argument
                // or list respectively.
                //
                // Methods with more than 1 argument are not allowed. Methods with return types
                // other than boolean are not allowed. Methods that throw an exception other than
                // org.apache.commons.cli.CommandLineException are not allowed,
                //
                // If the method returns a boolean, and calling that method returns FALSE, then the
                // command line main function will not be called.
                //
                // The class of the argument has to be convertable using common-beanutils
                // conversion facilities
                CommandLineMethodHelper helper = getHelperForCommandOption(method, commandLineOption);

                // Now create and configure an option based on what the method is capable of handling
                // and the command line option parameters
                boolean allowsArguments = helper.methodType != MethodType.Boolean;
                Option option = new Option(shortName, longName, allowsArguments, description);

                // Configure it
                option.setRequired(commandLineOption.required());
                if (option.hasArg()) {
                    option.setType(helper.elementType);
                    option.setArgs(commandLineOption.maximumArgumentCount());
                    option.setValueSeparator(commandLineOption.argumentSeparator());
                    option.setOptionalArg(commandLineOption.optionalArgument());
                }

                // Remember it, both in the commons-cli options set and
                // in our list of elements for later post-processing
                options.addOption(option);
                optionHelperMap.put(option, helper);
            }

            // This was not a command line option method - is it the main command line method?
        } else if (method.isAnnotationPresent(CommandLineMain.class)) {

            // Make sure we only have one
            if (mainHelper != null) {
                throw new CommandLineException("Cannot have two main methods specified");
            } else {
                mainHelper = getHelperForCommandLineMain(method);
            }
        }
    }
}

From source file:org.b3log.latke.servlet.handler.AdviceHandler.java

/**
 * get BeforeRequestProcessAdvice from annotation.
 *
 * @param invokeHolder the real invoked method
 * @param processorClass the class of the invoked methond
 * @return the list of BeforeRequestProcessAdvice
 *//*  w w  w.  ja  va2 s.  c  o  m*/
private List<Class<? extends BeforeRequestProcessAdvice>> getBeforeList(final Method invokeHolder,
        final Class<?> processorClass) {
    // before invoke(first class before advice and then method before advice).
    final List<Class<? extends BeforeRequestProcessAdvice>> beforeAdviceClassList = new ArrayList<Class<? extends BeforeRequestProcessAdvice>>();

    if (processorClass.isAnnotationPresent(Before.class)) {
        final Class<? extends BeforeRequestProcessAdvice>[] ac = processorClass.getAnnotation(Before.class)
                .adviceClass();

        beforeAdviceClassList.addAll(Arrays.asList(ac));
    }
    if (invokeHolder.isAnnotationPresent(Before.class)) {
        final Class<? extends BeforeRequestProcessAdvice>[] ac = invokeHolder.getAnnotation(Before.class)
                .adviceClass();

        beforeAdviceClassList.addAll(Arrays.asList(ac));
    }

    return beforeAdviceClassList;
}

From source file:com.evolveum.midpoint.repo.sql.query2.definition.ClassDefinitionParser.java

private JpaEntityDefinition parseClass(Class jpaClass) {

    Class jaxbClass = getJaxbClassForEntity(jpaClass);
    JpaEntityDefinition entity = new JpaEntityDefinition(jpaClass, jaxbClass);
    LOGGER.trace("### {}", entity);

    addVirtualDefinitions(jpaClass, entity);
    Method[] methods = jpaClass.getMethods();

    for (Method method : methods) {
        String methodName = method.getName();
        if (Modifier.isStatic(method.getModifiers()) || "getClass".equals(methodName)
                || (!methodName.startsWith("is") && !methodName.startsWith("get"))
                || method.getAnnotation(NotQueryable.class) != null) {
            //it's not getter for queryable property
            continue;
        }//from  w ww.j  a  v a  2  s .co m

        if (method.isAnnotationPresent(Transient.class)) {
            continue;
        }

        LOGGER.trace("# {}", method);

        JpaLinkDefinition linkDefinition;
        OwnerGetter ownerGetter = method.getAnnotation(OwnerGetter.class);
        if (ownerGetter != null) {
            String jpaName = getJpaName(method);
            JpaDataNodeDefinition nodeDefinition = new JpaEntityPointerDefinition(ownerGetter.ownerClass());
            // Owner is considered as not embedded, so we generate left outer join to access it
            // (instead of implicit inner join that would be used if we would do x.owner.y = '...')
            linkDefinition = new JpaLinkDefinition(new ParentPathSegment(), jpaName, null, false,
                    nodeDefinition);
        } else {
            linkDefinition = parseMethod(method);
        }
        entity.addDefinition(linkDefinition);
    }
    return entity;
}