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:io.hummer.util.ws.AbstractNode.java

protected boolean isRESTfulService() {
    Class<?> c = getClass();
    do {//  ww w . ja va2 s  .  c o  m
        if (c.isAnnotationPresent(Path.class))
            return true;
        for (Method m : c.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Path.class))
                return true;
        }
        c = c.getSuperclass();
    } while (c != null && c != Object.class);
    return false;
}

From source file:com.xiovr.unibot.bot.impl.BotGameConfigImpl.java

@Override
// public void loadSettings(Settings instance, Class<?> clazz, String fn)
public void loadSettings(Settings instance, String fn) {

    Class<?> clazz = instance.getClass().getInterfaces()[0];
    //      File file = new File("/" + DIR_PATH + "/" + fn);
    File file = new File(fn);
    Properties props = null;//from ww  w  .  ja  va2  s  .c o m
    try {
        props = BotUtils.loadProperties(file);

        // botEnvironment.setClientIp((props.getProperty("client.ip",
        // "127.0.0.1"));
    } catch (IOException e) {
        // e.printStackTrace();
        //         logger.warn("Can't load settings /" + DIR_PATH + "/" + fn
        //               + ". Create new settings file.");
        logger.warn("Can't load settings " + fn + ". Create new settings file.");
        props = createSettings(clazz, fn, "Bot v" + VERSION);

    }
    Method[] methods = clazz.getMethods();
    for (Method method : methods) {
        // Find setters
        if (method.getName().startsWith("set")) {

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

                Annotation annotation = method.getAnnotation(Param.class);
                Param param = (Param) annotation;
                if (param.name().equals("") || param.values().length == 0) {
                    throw new RuntimeException("Wrong param in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                Class<?>[] paramClazzes = method.getParameterTypes();
                if (paramClazzes.length != 1) {
                    throw new RuntimeException("Error contract design in class " + clazz.getCanonicalName()
                            + " with method " + method.getName());
                }
                // Check param belongs to List
                Class<?> paramClazz = paramClazzes[0];

                try {
                    if (List.class.isAssignableFrom(paramClazz)) {
                        // Oh, its array...
                        // May be its InetSocketAddress?

                        Type[] gpt = method.getGenericParameterTypes();
                        if (gpt[0] instanceof ParameterizedType) {
                            ParameterizedType type = (ParameterizedType) gpt[0];
                            Type[] typeArguments = type.getActualTypeArguments();

                            for (Type typeArgument : typeArguments) {
                                Class<?> classType = ((Class<?>) typeArgument);
                                if (InetSocketAddress.class.isAssignableFrom(classType)) {
                                    List<InetSocketAddress> isaArr = new ArrayList<>();
                                    int cnt = Integer.parseInt(props.getProperty(param.name() + ".count", "2"));
                                    for (int i = 0; i < cnt; ++i) {
                                        String defaultHostname = "";
                                        String defaultPort = "";
                                        if (param.values().length > i * 2) {
                                            defaultHostname = param.values()[i * 2];
                                            defaultPort = param.values()[i * 2 + 1];
                                        } else {
                                            defaultHostname = DEFAULT_HOSTNAME;
                                            defaultPort = String.valueOf(DEFAULT_PORT);
                                        }
                                        InetSocketAddress isa = new InetSocketAddress(
                                                props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".ip",
                                                        defaultHostname),
                                                Integer.parseInt(props.getProperty(
                                                        param.name() + "." + String.valueOf(i) + ".port",
                                                        defaultPort)));
                                        // invocableClazz.getMethod(method.getName(),
                                        // InetSocketAddress.class).invoke(
                                        // instance, isa);
                                        isaArr.add(isa);

                                    }

                                    method.invoke(instance, isaArr);

                                } else {
                                    throw new RuntimeException("Settings param in class "
                                            + clazz.getCanonicalName() + " with method " + method.getName()
                                            + " not implemented yet");
                                }
                            }

                        }
                    } else if (paramClazz.isPrimitive()) {
                        if (int.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Integer.parseInt(props.getProperty(param.name(), param.values()[0])));
                        } else if (long.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Long.parseLong(props.getProperty(param.name(), param.values()[0])));
                        } else if (boolean.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Boolean.parseBoolean(props.getProperty(param.name(), param.values()[0])));
                        } else if (double.class.isAssignableFrom(paramClazz)) {
                            method.invoke(instance,
                                    Double.parseDouble(props.getProperty(param.name(), param.values()[0])));
                        }

                    } else if (String.class.isAssignableFrom(paramClazz)) {
                        method.invoke(instance, props.getProperty(param.name(), param.values()[0]));
                    } else {
                        throw new RuntimeException("Settings param in class " + clazz.getCanonicalName()
                                + " with method " + method.getName() + " not implemented yet");
                    }
                } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

From source file:com.github.fharms.camel.entitymanager.CamelEntityManagerHandler.java

private Object createBeanProxy(Object bean) {
    MethodInterceptor handler = invocation -> {
        Method method = invocation.getMethod();
        switch (method.getName()) {
        case "hashCode":
            return hashCode();
        case "equals":
            return (invocation.getThis() == invocation.getArguments()[0]);
        case "toString":
            return toString();
        }/*from  www  .  j  a v a  2s  . c o m*/

        if (entityManagerLocal.get() == null && !method.isAnnotationPresent(IgnoreCamelEntityManager.class)) {
            Arrays.stream(invocation.getArguments()).filter(f -> f instanceof Exchange).findFirst()
                    .map(Exchange.class::cast)
                    .map(o -> o.getIn().getHeader(CAMEL_ENTITY_MANAGER, EntityManager.class))
                    .ifPresent(em -> addThreadLocalEntityManager(em));
        }
        return invocation.proceed();
    };

    ProxyFactory factory = new ProxyFactory(bean);
    factory.addAdvice(handler);

    return factory.getProxy();
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

@SuppressWarnings("unchecked")
private void setupFor(Class<? extends Serializable> clz) {
    if (fieldNamesByClass.get(clz) == null) {
        List<String> fields = new ArrayList<>();
        List<Method> methods = new ArrayList<>();
        for (Method method : clz.getMethods()) {
            String columnName = null;
            if (method.isAnnotationPresent(Id.class) && method.isAnnotationPresent(GeneratedValue.class)
                    && method.getAnnotation(GeneratedValue.class).strategy() == GenerationType.IDENTITY) {
                // Ignore pk with identity strategy.
            } else if (method.isAnnotationPresent(Column.class)) {
                columnName = extractColumnName(method, clz);
            } else if (method.isAnnotationPresent(JoinColumn.class)
                    && method.getAnnotation(JoinColumn.class).insertable()) {
                columnName = method.getAnnotation(JoinColumn.class).name();
            } else if (method.isAnnotationPresent(EmbeddedId.class)) {
                // Handle Attribute override annotation ...
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride override : overrides.value()) {
                        fields.add(override.column().name());
                    }//  www  .j  av a2  s . com
                }
                methods.add(method);
            } else if (method.getReturnType().isAnnotationPresent(Embeddable.class)) {
                methods.add(method);
                // Embeddables can have column names remapped using attribute overrides.
                // We expect all attributes to be overridden. 
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride overrideAnnotation : overrides.value()) {
                        fields.add(overrideAnnotation.column().name());
                    }
                } else {
                    // Use the column names from the embeddable class. Assumption: @Column annotation exists.
                    for (Method embedded : method.getReturnType().getMethods()) {
                        if (embedded.isAnnotationPresent(Column.class)) {
                            fields.add(extractColumnName(embedded,
                                    (Class<? extends Serializable>) method.getReturnType()));
                        }
                    }
                }
            }
            if (columnName != null) {
                // Certain one-to-on join situations can lead to multiple columns with the same column-name.
                if (!fields.contains(columnName)) {
                    fields.add(columnName);
                    methods.add(method);
                }
            } // end if annotation present
        }
        extractorsByClass.put(clz, getExtractor(clz, methods));
        StringBuilder builder = new StringBuilder();
        for (String field : fields) {
            builder.append(",").append(field);
        }
        fieldNamesByClass.put(clz, builder.substring(1));
    }
}

From source file:com.zht.common.rabc.service.impl.RbacPermissionServiceImpl.java

@Override
public void scanPacgeToloadPermis(String packagz) {
    Set<Class<?>> calssSet = PermissionUtil.scanAllController(packagz);
    if (calssSet == null || calssSet.size() == 0) {
        throw new ServiceLogicalException("??");
    }//from w w  w.  j  av  a2s. c o m
    List<RbacPermission> pList = new ArrayList<RbacPermission>();
    for (Class<?> calzz : calssSet) {
        Method[] methods = calzz.getDeclaredMethods();
        String clazzUrl = "";
        if (calzz.isAnnotationPresent(RequestMapping.class)) {
            RequestMapping rm = calzz.getAnnotation(RequestMapping.class);
            String[] clazzUrlArray = rm.value();
            clazzUrl = clazzUrlArray[0];
        }
        if (methods == null || methods.length == 0) {
            continue;
        }
        for (Method method : methods) {
            String url = "";
            if (method.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping mrp = method.getAnnotation(RequestMapping.class);
                String[] methodUrl = mrp.value();
                System.out.println(clazzUrl + methodUrl[0]);//permission--URL
                url = clazzUrl + methodUrl[0];
            }
            if (method.isAnnotationPresent(RequiresPermissions.class)) {
                Annotation rp = method.getAnnotation(RequiresPermissions.class);
                String[] methodRPerms = ((RequiresPermissions) rp).value();//permission--Code
                if (methodRPerms != null && methodRPerms.length > 1) {// pemis
                    for (String str : methodRPerms) {
                        RbacPermission perms = new RbacPermission();
                        perms.setUrl(url);
                        perms.setCode(str);
                        perms.setName("SCAN");
                        perms.setEnabled(true);
                        perms.setType("P");
                        pList.add(perms);
                    }
                } else if (methodRPerms != null && methodRPerms.length == 1) {
                    RbacPermission perms = new RbacPermission();
                    perms.setUrl(url);
                    perms.setCode(methodRPerms[0]);
                    pList.add(perms);
                    perms.setName("SCAN");
                    perms.setEnabled(true);
                    perms.setType("P");
                    pList.add(perms);
                } else if (methodRPerms == null || methodRPerms.length == 0) {
                    RbacPermission perms = new RbacPermission();
                    perms.setUrl(url);
                    perms.setCode("");
                    perms.setName("SCAN");
                    perms.setEnabled(true);
                    perms.setType("P");
                    pList.add(perms);
                    pList.add(perms);
                }
            }

        }
        for (RbacPermission p : pList) {
            $base_save(p);
        }
    }
}

From source file:com.jsmartframework.web.manager.BeanHelper.java

void setBeanMethods(Class<?> clazz) {
    if (!beanMethods.containsKey(clazz)) {
        List<Method> postConstructs = new ArrayList<>();
        List<Method> preDestroys = new ArrayList<>();
        List<Method> postSubmits = new ArrayList<>();
        List<Method> postActions = new ArrayList<>();
        List<Method> preSubmits = new ArrayList<>();
        List<Method> preActions = new ArrayList<>();
        List<String> unescapes = new ArrayList<>();
        List<Method> executeAccess = new ArrayList<>();

        for (Method method : clazz.getMethods()) {
            if (method.isAnnotationPresent(PostConstruct.class)) {
                postConstructs.add(method);
            }/*from   w  w  w.jav  a  2  s.  com*/
            if (method.isAnnotationPresent(PreDestroy.class)) {
                preDestroys.add(method);
            }
            if (method.isAnnotationPresent(PostSubmit.class)) {
                postSubmits.add(method);
            }
            if (method.isAnnotationPresent(PostAction.class)) {
                postActions.add(method);
            }
            if (method.isAnnotationPresent(PreSubmit.class)) {
                preSubmits.add(method);
            }
            if (method.isAnnotationPresent(PreAction.class)) {
                preActions.add(method);
            }
            if (method.isAnnotationPresent(Unescape.class)) {
                Matcher matcher = SET_METHOD_PATTERN.matcher(method.getName());
                if (matcher.find()) {
                    unescapes.add(matcher.group(1));
                }
            }
            if (method.isAnnotationPresent(ExecuteAccess.class)) {
                executeAccess.add(method);
            }
        }

        beanMethods.put(clazz, clazz.getMethods());
        executeAccessMethods.put(clazz, executeAccess.toArray(new Method[executeAccess.size()]));
        postConstructMethods.put(clazz, postConstructs.toArray(new Method[postConstructs.size()]));
        preDestroyMethods.put(clazz, preDestroys.toArray(new Method[preDestroys.size()]));
        postSubmitMethods.put(clazz, postSubmits.toArray(new Method[postSubmits.size()]));
        postActionMethods.put(clazz, postActions.toArray(new Method[postActions.size()]));
        preSubmitMethods.put(clazz, preSubmits.toArray(new Method[preSubmits.size()]));
        preActionMethods.put(clazz, preActions.toArray(new Method[preActions.size()]));
        unescapeMethods.put(clazz, unescapes.toArray(new String[unescapes.size()]));
    }
}

From source file:org.apache.nifi.authorization.AuthorizerFactoryBean.java

private void performMethodInjection(final Authorizer instance, final Class authorizerClass)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (final Method method : authorizerClass.getMethods()) {
        if (method.isAnnotationPresent(AuthorizerContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);// ww w  . j  av  a2 s  .  co  m

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorizerClass.getSuperclass();
    if (parentClass != null && Authorizer.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}

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

protected Boolean canProxy(Class clazz, Method method) {
    if (method.isAnnotationPresent(AlwaysProxy.class)
            || method.isAnnotationPresent(com.zenesis.qx.remote.annotations.Method.class))
        return true;
    for (Class tmp : clazz.getInterfaces())
        if (Proxied.class.isAssignableFrom(tmp)) {
            Boolean test = canProxy(tmp, method);
            if (test != null)
                return test;
        }//  www  .  jav  a  2  s  .  com
    Class superClazz = clazz.getSuperclass();
    if (superClazz != null && Proxied.class.isAssignableFrom(superClazz))
        return canProxy(superClazz, method);
    return null;
}

From source file:org.apache.nifi.authorization.AuthorityProviderFactoryBean.java

private void performMethodInjection(final AuthorityProvider instance, final Class authorityProviderClass)
        throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    for (final Method method : authorityProviderClass.getMethods()) {
        if (method.isAnnotationPresent(AuthorityProviderContext.class)) {
            // make the method accessible
            final boolean isAccessible = method.isAccessible();
            method.setAccessible(true);//  w  ww .java2  s .  co m

            try {
                final Class<?>[] argumentTypes = method.getParameterTypes();

                // look for setters (single argument)
                if (argumentTypes.length == 1) {
                    final Class<?> argumentType = argumentTypes[0];

                    // look for well known types
                    if (NiFiProperties.class.isAssignableFrom(argumentType)) {
                        // nifi properties injection
                        method.invoke(instance, properties);
                    } else if (ApplicationContext.class.isAssignableFrom(argumentType)) {
                        // spring application context injection
                        method.invoke(instance, applicationContext);
                    }
                }
            } finally {
                method.setAccessible(isAccessible);
            }
        }
    }

    final Class parentClass = authorityProviderClass.getSuperclass();
    if (parentClass != null && AuthorityProvider.class.isAssignableFrom(parentClass)) {
        performMethodInjection(instance, parentClass);
    }
}

From source file:com.phoenixnap.oss.ramlapisync.parser.SpringMvcResourceParser.java

@Override
protected boolean isActionOnResourceWithoutCommand(Method method) {
    if (!method.isAnnotationPresent(RequestMapping.class)) {
        return true;
    } else {/*from   w  ww.  j a v  a  2s.  co m*/
        RequestMapping requestMapping = getRequestMapping(method);
        if (requestMapping.value().length == 0) {
            return true;
        }

        String url = requestMapping.value()[0];
        if (StringUtils.hasText(url)) {
            return true;
        }
        logger.debug("Parsing url: [" + url + "]");
        List<ApiParameterMetadata> apiParameters = getApiParameters(method, true, false);
        for (ApiParameterMetadata parameterMetadata : apiParameters) {
            url.replace(parameterMetadata.getName(), "");
        }
        url = url.replaceAll("[^\\w]", "");
        if (StringUtils.hasText(url)) {
            return false;
        }
    }
    return true;
}