Example usage for java.lang Class getAnnotations

List of usage examples for java.lang Class getAnnotations

Introduction

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

Prototype

public Annotation[] getAnnotations() 

Source Link

Usage

From source file:org.callimachusproject.auth.AuthorizationManager.java

private void getAnnotationValues(Class<?> cls, Set<String> roles, Set<String> set) {
    for (Annotation ann : cls.getAnnotations()) {
        try {/*  w ww.  jav a2 s.  c  o  m*/
            Method value = ann.annotationType().getMethod("value");
            Iri iri = value.getAnnotation(Iri.class);
            if (iri != null && roles.contains(iri.value())) {
                Object obj = value.invoke(ann);
                if (obj instanceof String[]) {
                    set.addAll(Arrays.asList((String[]) obj));
                }
            }
        } catch (NoSuchMethodException e) {
            continue;
        } catch (IllegalAccessException e) {
            continue;
        } catch (IllegalArgumentException e) {
            logger.error(e.toString(), e);
        } catch (InvocationTargetException e) {
            logger.error(e.toString(), e);
        }
    }
    for (Class<?> face : cls.getInterfaces()) {
        getAnnotationValues(face, roles, set);
    }
    if (cls.getSuperclass() != null) {
        getAnnotationValues(cls.getSuperclass(), roles, set);
    }
}

From source file:com.tesora.dve.sql.logfile.LogFileTest.java

public static LogFileTestFileConfiguration findConfig(Class<?> onClass) {
    for (final Annotation anno : onClass.getAnnotations()) {
        if (anno.annotationType().equals(LogFileTestFileConfiguration.class)) {
            return (LogFileTestFileConfiguration) anno;
        }//from   ww w . j a  v a 2s .  com
    }
    return null;
}

From source file:net.ymate.platform.core.beans.impl.DefaultBeanFactory.java

public void init() throws Exception {
    if (this.__beanLoader == null) {
        if (this.__parentFactory != null) {
            this.__beanLoader = this.__parentFactory.getLoader();
        }//from w  w  w . j  a v a2s .c om
        if (this.__beanLoader == null) {
            this.__beanLoader = new DefaultBeanLoader();
        }
    }
    if (!__packageNames.isEmpty())
        for (String _packageName : __packageNames) {
            List<Class<?>> _classes = this.__beanLoader.load(_packageName);
            for (Class<?> _class : _classes) {
                // ?????
                if (!_class.isAnnotation() && !_class.isEnum() && !_class.isInterface()) {
                    Annotation[] _annotations = _class.getAnnotations();
                    if (_annotations != null && _annotations.length > 0) {
                        for (Annotation _anno : _annotations) {
                            IBeanHandler _handler = __beanHandlerMap.get(_anno.annotationType());
                            if (_handler != null) {
                                Object _instance = _handler.handle(_class);
                                if (_instance != null) {
                                    if (_instance instanceof BeanMeta) {
                                        __addClass((BeanMeta) _instance);
                                    } else {
                                        __addClass(BeanMeta.create(_instance, _class));
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
}

From source file:org.apache.streams.plugins.StreamsScalaSourceGenerator.java

/**
 * detect which Classes are Pojo Classes.
 * @param classes List of candidate Pojo Classes
 * @return List of actual Pojo Classes//from  w  w  w.  j  av  a2 s  .  c  om
 */
public List<Class<?>> detectPojoClasses(List<Class<?>> classes) {

    List<Class<?>> result = new ArrayList<>();

    for (Class clazz : classes) {
        try {
            clazz.newInstance().toString();
        } catch (Exception ex) {
            //
        }
        // super-halfass way to know if this is a jsonschema2pojo
        if (clazz.getAnnotations().length >= 1) {
            result.add(clazz);
        }
    }

    return result;
}

From source file:org.nuunframework.cli.NuunCliPlugin.java

boolean hasAnnotationDeep(Class<? extends Annotation> from, Class<? extends Annotation> toFind) {

    if (from.equals(toFind)) {
        return true;
    }/*from w  ww  .  j a  v a 2s .co m*/

    for (Annotation anno : from.getAnnotations()) {
        Class<? extends Annotation> annoClass = anno.annotationType();
        if (!annoClass.getPackage().getName().startsWith("java.lang") && hasAnnotationDeep(annoClass, toFind)) {
            return true;
        }
    }

    return false;
}

From source file:plaid.compilerjava.CompilerCore.java

private void handleClassInPlaidPath(Class<?> classRep, String className, PackageRep plaidpath) {
    for (Annotation a : classRep.getAnnotations()) {
        String thePackage = null;
        MemberRep member = null;//from www  .ja v a 2 s  .c  om

        if (a instanceof RepresentsField) {
            RepresentsField f = (RepresentsField) a;
            thePackage = f.inPackage();
            member = new FieldRep(f.name());
        } else if (a instanceof RepresentsMethod) {
            RepresentsMethod m = (RepresentsMethod) a;
            thePackage = m.inPackage();
            member = new MethodRep(m.name());
        } else if (a instanceof RepresentsState) {
            RepresentsState s = (RepresentsState) a;
            thePackage = s.inPackage();
            JSONObject obj = (JSONObject) JSONValue.parse(s.jsonRep());
            if (obj == null) {
                System.out.println("break");
            }
            StateRep state = StateRep.parseJSONObject(obj);
            member = state;
        }
        if (member != null) { //if this was a plaid generated java file
            if (!className.startsWith(thePackage))
                throw new RuntimeException("Package " + thePackage + "of member " + member.getName()
                        + " does not match file path " + className + ".");

            plaidpath.addMember(thePackage, member);
        }
    }
}

From source file:org.kie.workbench.common.screens.datamodeller.backend.server.DataModelTestUtil.java

public DataObject createDataObject(Class clazz) throws NoSuchMethodException, SecurityException,
        IllegalAccessException, IllegalArgumentException, InvocationTargetException {
    Class superClass = clazz.getSuperclass();
    String superClassName = null;
    if (superClass != null && !superClass.equals(Object.class)) {
        superClassName = superClass.getCanonicalName();
    }/*from w w w  .  j av  a2s .  com*/
    DataObject dataObj = createDataObject(clazz.getPackage().getName(), clazz.getSimpleName(), superClassName);
    addAnnotations(dataObj, clazz.getAnnotations());

    for (Field field : clazz.getDeclaredFields()) {
        String fieldName = field.getName();
        String fieldType = field.getType().getCanonicalName();
        ObjectProperty fieldProp = addProperty(dataObj, fieldName, fieldType, true, false, null);

        addAnnotations(fieldProp, field.getAnnotations());
    }

    return dataObj;
}

From source file:org.richfaces.tests.metamer.ftest.MatrixConfigurator.java

private Annotation[] getAnnotationsForAllSuperClasses(Class<?> testClass) {
    List<Annotation> annotations = new LinkedList<Annotation>();

    Class<?> currentClass = testClass;
    while (currentClass != Object.class) {
        annotations.addAll(Arrays.asList(currentClass.getAnnotations()));
        if (currentClass == AbstractMetamerTest.class) {
            break;
        }//from  ww  w  .  j  a  v  a 2  s  . c  o m
        currentClass = currentClass.getSuperclass();
    }

    // needs to be returned in reversed order because of the lowel level annnotations needs to be processed first
    Collections.reverse(annotations);

    return annotations.toArray(new Annotation[annotations.size()]);
}

From source file:org.getobjects.appserver.publisher.GoClassRegistry.java

protected void processClassAnnotations(final GoJavaClass _goCls, final Class _cls) {
    String pb = null, access = null;
    boolean isPrivate = false, isPublic = false;
    String[] anonPerms = null, authPerms = null;

    // We could stop if all knows have been processed, but that situation
    // doesn't actually happen.
    for (final Annotation a : _cls.getAnnotations()) {
        if (a instanceof ProtectedBy)
            pb = ((ProtectedBy) a).value();
        else if (a instanceof Private)
            isPrivate = true;/*  w  ww  .j  a  va2  s  .  co  m*/
        else if (a instanceof Public)
            isPublic = true;
        else if (a instanceof DefaultAccess)
            access = ((DefaultAccess) a).value();
        else if (a instanceof DefaultRoles) {
            anonPerms = ((DefaultRoles) a).anonymous();
            authPerms = ((DefaultRoles) a).authenticated();
        }
    }

    /* object protections, only one can be set */

    if (pb != null || isPrivate || isPublic) {
        if (isPrivate) {
            if (pb != null || isPublic) {
                log.error("declared Private on a class which already has a "
                        + "another protection (ProtectedBy or Public)");
            }
            _goCls.securityInfo().declareObjectPrivate();
        } else if (pb != null) {
            if (isPublic) {
                log.error(
                        "declared ProtectedBy on a class which already has a " + "another protection (Public)");
            }
            _goCls.securityInfo().declareObjectProtected(pb);
            ;
        } else if (isPublic)
            _goCls.securityInfo().declareObjectPublic();
    }

    /* roles, multiple can be set */

    Map<String, ArrayList<String>> permToRoles = null;
    if (anonPerms != null && anonPerms.length > 0) {
        if (permToRoles == null)
            permToRoles = new HashMap<String, ArrayList<String>>(4);
        fillPermissionToRoleMap(permToRoles, GoRole.Anonymous, anonPerms);
    }
    if (authPerms != null && authPerms.length > 0) {
        if (permToRoles == null)
            permToRoles = new HashMap<String, ArrayList<String>>(4);
        fillPermissionToRoleMap(permToRoles, GoRole.Authenticated, authPerms);
    }

    if (permToRoles != null) {
        final GoSecurityInfo si = _goCls.securityInfo();
        for (final String perm : permToRoles.keySet()) {
            final List<String> roles = permToRoles.get(perm);
            si.declareRolesAsDefaultForPermission(roles.toArray(new String[roles.size()]), perm);
        }
    }

    /* access */

    if (access != null) {
        if (!access.equals("allow") && !access.equals("deny"))
            log.error("Invalid default-access argument: " + access);
        else
            _goCls.securityInfo().setDefaultAccess(access);
    }
}

From source file:org.sindice.rdfcommons.beanmapper.StaticBeanDeserializer.java

public <T> T deserialize(DeserializationContext context, Class<T> clazz, Annotation[] annotations,
        Identifier identifier, QueryEndpoint endPoint) throws DeserializationException {

    if (identifier != null) {
        throw new IllegalArgumentException("for static deserialization the identifier is expected to be null.");
    }//from w  w w. ja va2s .co m

    final Identifier staticIdentifier = getIdentifier(clazz, annotations);

    // Create the bean instance.
    final T instance;
    try {
        instance = clazz.newInstance();
    } catch (Exception e) {
        throw new DeserializationException(String
                .format("Error while creating instance of class %s: defualt constructor required.", clazz));
    }
    context.registerInstance(staticIdentifier, instance);

    // Define the bean map.
    final BeanMap beanMap = new BeanMap(instance);

    // Extracts the class property URLs.
    final Map<String, Method> propertyURLs = new HashMap<String, Method>();
    final String classURL = getClassURL(clazz);
    String propertyName;
    Method propertyWriteMethod;
    for (Map.Entry<String, Object> entry : (Set<Map.Entry<String, Object>>) beanMap.entrySet()) {
        // Skipping self description.
        if ("class".equals(entry.getKey())) {
            continue;
        }
        propertyName = entry.getKey();
        propertyWriteMethod = beanMap.getWriteMethod(propertyName);
        propertyURLs.put(getPropertyURL(classURL, propertyName, propertyWriteMethod), propertyWriteMethod);
    }

    // Retrieve the class triples.
    endPoint.addQuery((String) staticIdentifier.getId(), "?prop", "?value");
    ResultSet rs = endPoint.execute();

    // Coupling object properties with actual ones.
    Object property;
    Object value;
    Class propertyType;
    while (rs.hasNext()) {
        property = rs.getVariableValue("?prop");
        value = rs.getVariableValue("?value");
        rs.next();

        propertyWriteMethod = propertyURLs.get(property);
        if (propertyWriteMethod == null) {
            context.reportIssue(String.format("Cannot find write method for property URL %s", property));
            continue;
        }
        propertyType = propertyWriteMethod.getParameterTypes()[0];

        // Deserializing recursively.
        Object deserialized = context.deserialize(context, propertyType, propertyType.getAnnotations(),
                new Identifier(value, Identifier.Type.resource), endPoint);

        try {
            propertyWriteMethod.invoke(instance, deserialized);
        } catch (Exception e) {
            throw new DeserializationException(
                    String.format("Error while invoking write method %s of instance %s on value %s[%s]",
                            propertyWriteMethod, instance, deserialized, deserialized.getClass()));
        }
    }
    return instance;
}