Example usage for java.lang Class getAnnotation

List of usage examples for java.lang Class getAnnotation

Introduction

In this page you can find the example usage for java.lang Class getAnnotation.

Prototype

@SuppressWarnings("unchecked")
public <A extends Annotation> A getAnnotation(Class<A> annotationClass) 

Source Link

Usage

From source file:net.contextfw.web.application.internal.servlet.UriMappingFactory.java

@SuppressWarnings("unchecked")
public SortedSet<UriMapping> createMappings(Collection<Class<?>> origClasses, ClassLoader classLoader,
        InitializerProvider initializerProvider, InitHandler initHandler, PropertyProvider properties,
        RequestInvocationFilter filter) {

    // Note: This process creates some phantom chains from
    // views that do not have any url. Those chains are
    // however ingnored and are not such problem.

    SortedSet<UriMapping> mappings = new TreeSet<UriMapping>();

    try {/*  w w  w .  j  av  a 2  s . c  om*/
        for (Class<?> origClass : origClasses) {
            Class<?> cl = classLoader.loadClass(origClass.getCanonicalName());
            View annotation = cl.getAnnotation(View.class);
            if (annotation != null) {

                if (!Component.class.isAssignableFrom(cl)) {
                    throw new WebApplicationException(
                            "Class " + cl.getName() + " annotated with @View does " + "not extend Component");
                }

                List<Class<? extends Component>> chain = initializerProvider.getInitializerChain(cl);

                InitServlet servlet = new InitServlet(initHandler, chain, filter);

                for (String url : annotation.url()) {
                    if (!"".equals(url)) {
                        mappings.add(this.getMapping((Class<? extends Component>) cl, servlet, url));
                    }
                }

                for (String property : annotation.property()) {
                    if (!"".equals(property)) {
                        if (!properties.get().containsKey(property)) {
                            throw new WebApplicationException("No url bound to property: " + property);
                        }

                        String url = properties.get().getProperty(property);

                        if (url != null && !"".equals(url)) {
                            mappings.add(this.getMapping((Class<? extends Component>) cl, servlet, url));
                        } else {
                            throw new WebApplicationException("No url bound to view component. (class="
                                    + cl.getSimpleName() + ", property=" + property + ")");
                        }
                    }
                }
            }
        }
    } catch (ClassNotFoundException e) {
        throw new WebApplicationException(e);
    }

    return mappings;
}

From source file:com.github.lothar.security.acl.AclStrategyProviderImpl.java

private String strategyBeanName(Class<?> entityClass) {
    String strategyBeanName = properties.getOverrideStrategy();
    if (strategyBeanName != null) {
        logger.debug("Using override strategy: {}", strategyBeanName);
        return strategyBeanName;
    }// ww  w  . j  a  v a  2  s.c  om

    Acl acl = entityClass.getAnnotation(Acl.class);
    if (acl != null) {
        strategyBeanName = acl.value();
        logger.debug("{} annotation found on '{}', indicating strategy {}", Acl.class.getName(),
                entityClass.getSimpleName(), strategyBeanName);
    } else {
        logger.debug("No {} annotation found on '{}' > fall back on default strategy", Acl.class.getName(),
                entityClass.getSimpleName());
    }
    return strategyBeanName;
}

From source file:com.oakhole.Generate.java

/**
 * ?Entity//from  w w  w.ja  va  2s.c o m
 * @param filePath
 * @param entities
 */
private void fetchEntities(String packageName, String filePath, Set<Class<?>> entities) {

    // package
    File file = new File(filePath);

    if (!file.exists() || !file.isDirectory()) {
        logger.warn("{} neither exists nor the directory .", filePath);
        return;
    }

    // ?packageclass
    File[] subFiles = file.listFiles(new FileFilter() {
        @Override
        public boolean accept(File pathname) {
            return pathname.isDirectory() || pathname.getName().endsWith(".class");
        }
    });

    for (File subFile : subFiles) {

        // ?class?
        if (subFile.isDirectory()) {
            fetchEntities(packageName + "." + subFile.getName(), subFile.getAbsolutePath(), entities);
        } else {
            // ??
            String className = subFile.getName().substring(0, subFile.getName().length() - 6);
            try {
                Class object = Thread.currentThread().getContextClassLoader()
                        .loadClass(packageName + "." + className);
                if (object.getAnnotation(Entity.class) != null) {
                    entities.add(object);
                }
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
        }
    }
}

From source file:com.kloudtek.kloudmake.service.filestore.FileStore.java

@Override
public synchronized void start() throws KMRuntimeException {
    fileFragmentDefs.clear();/*  www  .j  a v a2  s  . c  o  m*/
    fileFragmentDefsTypeIndex.clear();
    Set<Class<?>> fileFragmentsClasses = context.getLibraryReflections()
            .getTypesAnnotatedWith(FileFragment.class);
    for (Class<?> clazz : fileFragmentsClasses) {
        if (clazz.getAnnotation(KMResource.class) == null) {
            throw new KMRuntimeException(
                    "Class " + clazz.getName() + " is annotated with @FileFragment but not @STResource");
        }
        FQName type = new FQName(clazz);
        FileFragmentDef def = new FileFragmentDef(clazz.getAnnotation(FileFragment.class).fileContentClass(),
                type);
        fileFragmentDefs.add(def);
        fileFragmentDefsTypeIndex.put(type, def);
    }
}

From source file:com.vecna.taglib.processor.JspAnnotationsProcessor.java

/**
 * Build a JSP tag model object from an annotated tag class
 * @param type tag class/*from w  ww  .  ja v a  2 s. co m*/
 * @return JSP tag model
 */
public JspTagModel getTagMetadata(Class<?> type) {
    JspTagModel metadata = new JspTagModel();
    JspTag jspTagAnnotation = type.getAnnotation(JspTag.class);
    metadata.bodyContent = jspTagAnnotation.bodyContent();
    metadata.name = jspTagAnnotation.name();
    metadata.tagClass = type.getName();
    metadata.dynamicAttributes = jspTagAnnotation.dynamicAttributes();

    for (JspVariable jspVariableAnnotation : jspTagAnnotation.variables()) {
        JspVariableModel variable = new JspVariableModel();
        variable.declare = jspVariableAnnotation.declare();

        variable.nameFromAttribute = StringUtils.stripToNull(jspVariableAnnotation.nameFromAttribute());
        variable.nameGiven = StringUtils.stripToNull(jspVariableAnnotation.nameGiven());

        variable.scope = jspVariableAnnotation.scope();
        variable.variableClass = jspVariableAnnotation.variableClass().getName();
        metadata.variables.add(variable);
    }

    for (PropertyDescriptor pd : PropertyUtils.getPropertyDescriptors(type)) {
        s_log.debug("processing property {}", pd.getName());
        if (pd.getWriteMethod() != null && pd.getWriteMethod().isAnnotationPresent(JspAttribute.class)) {
            s_log.debug("attribute metadata present on {}", pd.getName());
            JspAttributeModel attr = new JspAttributeModel();
            attr.name = pd.getName();
            attr.type = pd.getPropertyType().getName();
            JspAttribute jspAttributeAnnotation = pd.getWriteMethod().getAnnotation(JspAttribute.class);
            attr.required = jspAttributeAnnotation.required();
            attr.rtExprValue = jspAttributeAnnotation.rtExprValue();
            attr.fragment = jspAttributeAnnotation.fragment();

            attr.deferredMethod = jspAttributeAnnotation.deferredMethod() ? true : null;
            attr.deferredValue = jspAttributeAnnotation.deferredValue() ? true : null;

            metadata.attributes.add(attr);
        }
    }

    return metadata;
}

From source file:com.kumuluz.ee.security.KeycloakSecurityConfigurationUtilImpl.java

private String getKeycloakConfig(Class targetClass) {
    ObjectMapper mapper = new ObjectMapper();

    ConfigurationUtil configurationUtil = ConfigurationUtil.getInstance();

    Keycloak keycloakAnnotation = (Keycloak) targetClass.getAnnotation(Keycloak.class);

    String jsonString;// w w w .  ja  v a 2s.c o m
    ObjectNode json;
    String authServerUrl;
    String sslRequired;

    jsonString = configurationUtil.get("kumuluzee.security.keycloak.json").orElse("{}");
    json = toJSONObject(jsonString);

    if (jsonString.isEmpty() && keycloakAnnotation != null) {
        jsonString = keycloakAnnotation.json();
        json = toJSONObject(jsonString);

        authServerUrl = keycloakAnnotation.authServerUrl();
        sslRequired = keycloakAnnotation.sslRequired();

        if (!authServerUrl.isEmpty()) {
            json.put("auth-server-url", authServerUrl);
        }

        if (!sslRequired.isEmpty()) {
            json.put("ssl-required", sslRequired);
        }
    }

    return json.toString();
}

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

@Test
public void testRemoteInterfaces() throws Exception {
    for (Class klass : getClasses("com.feedzai.fos.server.remote.impl")) {
        if (klass.isAnnotationPresent(RemoteInterface.class)) {
            RemoteInterface implementation = (RemoteInterface) klass.getAnnotation(RemoteInterface.class);
            Class<?> matchingClass = implementation.of();
            testMatch(matchingClass, klass, 0);
        }//from   w  ww.  ja v  a  2s.c  o m
    }
}

From source file:com.esofthead.mycollab.common.interceptor.aspect.AuditLogAspect.java

@AfterReturning("(execution(public * com.esofthead.mycollab..service..*.updateWithSession(..)) || (execution(public * com.esofthead.mycollab..service..*.updateSelectiveWithSession(..))))  && args(bean, username)")
public void traceAfterUpdateActivity(JoinPoint joinPoint, Object bean, String username) {

    Advised advised = (Advised) joinPoint.getThis();
    Class<?> cls = advised.getTargetSource().getTargetClass();

    Traceable traceableAnnotation = cls.getAnnotation(Traceable.class);
    Integer activityStreamId = null;
    if (traceableAnnotation != null) {
        try {//from ww  w  . j  a  v a 2s. com
            ActivityStreamWithBLOBs activity = TraceableAspect.constructActivity(cls, traceableAnnotation, bean,
                    username, ActivityStreamConstants.ACTION_UPDATE);
            activityStreamId = activityStreamService.save(activity);
        } catch (Exception e) {
            LOG.error("Error when save activity for save action of service " + cls.getName(), e);
        }
    }

    try {
        Watchable watchableAnnotation = cls.getAnnotation(Watchable.class);
        if (watchableAnnotation != null) {
            String monitorType = ClassInfoMap.getType(cls);
            Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            int typeId = (Integer) PropertyUtils.getProperty(bean, "id");

            Integer extraTypeId = null;
            if (!"".equals(watchableAnnotation.extraTypeId())) {
                extraTypeId = (Integer) PropertyUtils.getProperty(bean, watchableAnnotation.extraTypeId());
            }

            MonitorItem monitorItem = new MonitorItem();
            monitorItem.setMonitorDate(new GregorianCalendar().getTime());
            monitorItem.setType(monitorType);
            monitorItem.setTypeid(typeId);
            monitorItem.setExtratypeid(extraTypeId);
            monitorItem.setUser(username);
            monitorItem.setSaccountid(sAccountId);
            monitorItemService.saveWithSession(monitorItem, username);

            // check whether the current user is in monitor list, if
            // not add him in
            if (!watchableAnnotation.userFieldName().equals("")) {
                String moreUser = (String) PropertyUtils.getProperty(bean, watchableAnnotation.userFieldName());
                if (moreUser != null && !moreUser.equals(username)) {
                    monitorItem.setId(null);
                    monitorItem.setUser(moreUser);
                    monitorItemService.saveWithSession(monitorItem, moreUser);
                }
            }
        }

        NotifyAgent notifyAgent = cls.getAnnotation(NotifyAgent.class);
        if (notifyAgent != null) {
            Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            Integer auditLogId = saveAuditLog(cls, bean, username, sAccountId, activityStreamId);
            int typeId = (Integer) PropertyUtils.getProperty(bean, "id");
            // Save notification email
            RelayEmailNotificationWithBLOBs relayNotification = new RelayEmailNotificationWithBLOBs();
            relayNotification.setChangeby(username);
            relayNotification.setChangecomment("");
            relayNotification.setSaccountid(sAccountId);
            relayNotification.setType(ClassInfoMap.getType(cls));
            relayNotification.setTypeid("" + typeId);
            relayNotification.setEmailhandlerbean(notifyAgent.value().getName());
            if (auditLogId != null) {
                relayNotification.setExtratypeid(auditLogId);
            }

            relayNotification.setAction(MonitorTypeConstants.UPDATE_ACTION);

            relayEmailNotificationService.saveWithSession(relayNotification, username);
        }
    } catch (Exception e) {
        LOG.error("Error when save audit for save action of service " + cls.getName() + "and bean: "
                + BeanUtility.printBeanObj(bean), e);
    }
}

From source file:jofc2.OFC.java

/**
 * ??//from  w w w . j  a  v  a2s.c  o m
 * @param c
 */
private void doAlias(Class<?> c) {
    /**
     * 
     */
    if (c.isAnnotationPresent(Alias.class)) {
        converter.alias(c.getAnnotation(Alias.class).value(), c);
    }

    /**
     * ??
     */
    for (Field f : c.getDeclaredFields()) {
        if (f.isAnnotationPresent(Alias.class)) {
            if (f.getAnnotation(Alias.class).value().equals("")) {
                System.out.println(f.getName());
            }
            converter.aliasField(f.getAnnotation(Alias.class).value(), c, f.getName());
        }
    }
}

From source file:com.doitnext.jsonschema.generator.SchemaGen.java

private static boolean handleProperties(Class<?> classz, StringBuilder sb, Map<String, String> declarations,
        String uriPrefix) {/*  w  ww . j  a  v  a 2 s  .c  o  m*/
    boolean result = false;
    String prepend = "";
    Set<String> processedFields = new HashSet<String>();
    sb.append("{");
    for (Field field : classz.getFields()) {
        JsonSchemaProperty propertyDecl = field.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null) {
            Class<?> propClassz = field.getType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    for (Method method : classz.getMethods()) {
        JsonSchemaProperty propertyDecl = method.getAnnotation(JsonSchemaProperty.class);
        if (propertyDecl != null && !processedFields.contains(propertyDecl.name())) {
            Class<?> propClassz = method.getReturnType();
            StringBuilder sb2 = new StringBuilder();
            boolean inline = true;
            sb2.append("{");
            if (!handleSimpleType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                if (!handleArrayType(propClassz, sb2, propertyDecl, declarations, uriPrefix)) {
                    inline = false;
                }
            }
            sb2.append("}");
            if (inline) {
                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":");
                sb.append(sb2.toString());
                prepend = ", ";
            } else {
                String id = null;
                JsonSchemaClass jsc = propClassz.getAnnotation(JsonSchemaClass.class);
                if (jsc != null)
                    id = jsc.id();
                else
                    id = propClassz.getName();
                declarations.put(id, sb2.toString());

                sb.append(prepend);
                sb.append("\"");
                sb.append(propertyDecl.name());
                sb.append("\":{\"$ref\":\"");
                if (!StringUtils.isEmpty(uriPrefix))
                    sb.append(uriPrefix);
                sb.append(id);
                sb.append("\"}");
                prepend = ", ";
            }
            processedFields.add(propertyDecl.name());
        }
    }
    sb.append("}");
    return result;
}