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:com.jedi.oracle.OracleTypeUtils.java

private static void findCustomTypesRecursive(List<Field> fields, Map<String, Class<?>> map) {
    for (Field field : fields) {
        Class fieldType = field.getType();
        if (List.class.isAssignableFrom(fieldType)) {
            ParameterizedType listType = (ParameterizedType) field.getGenericType();
            fieldType = (Class<?>) listType.getActualTypeArguments()[0];
        }/*from  w  ww . j a v a2 s  . co m*/

        if (fieldType.isAnnotationPresent(CustomTypeMapping.class)) {
            CustomTypeMapping mapping = (CustomTypeMapping) fieldType.getAnnotation(CustomTypeMapping.class);
            map.put(mapping.name(), fieldType);
            List<Field> oracleObjectFields = FieldUtils.getFieldsListWithAnnotation(fieldType,
                    OracleObjectMapping.class);
            if (oracleObjectFields != null && !oracleObjectFields.isEmpty()) {
                findCustomTypesRecursive(oracleObjectFields, map);
            }
        }
    }
}

From source file:cn.teamlab.wg.framework.struts2.breadcrumb.BreadCrumbInterceptor.java

@SuppressWarnings("unchecked")
protected static BreadCrumb findAnnotation(Class aclass, Method method) {
    BreadCrumb crumb = null;//  w w  w  .  j  a va 2s  . c o  m

    /*
     * Check if it is an annotated method
     */
    if (method != null) {
        crumb = method.getAnnotation(BreadCrumb.class);
    }

    /*
     * Check if we have an annotated class
     */
    if (crumb == null) {
        crumb = (BreadCrumb) aclass.getAnnotation(BreadCrumb.class);
    }

    return crumb;
}

From source file:com.google.code.simplestuff.bean.BusinessObjectContext.java

/**
 * Retrieve a {@link BusinessObjectDescriptor} object for a
 * {@link BusinessObject} class bean./*from   w w  w.j  ava 2 s  . co  m*/
 * 
 * @param objectClass The class of the bean to check.
 * @param annotationObjectClass The class to use for retrieving the
 *        {@link BusinessField} annotated field.
 * @return A {@link BusinessObjectDescriptor} for the bean class passed.
 */
private static BusinessObjectDescriptor getBusinessObjectDescriptor(Class<? extends Object> objectClass,
        Class<? extends Object> annotationObjectClass) {

    BusinessObjectDescriptor businessObjectDescriptor = new BusinessObjectDescriptor();

    if (objectClass == null) {
        businessObjectDescriptor.setNearestBusinessObjectClass(null);
        return businessObjectDescriptor;
    } else {
        if (objectClass.isAnnotationPresent(BusinessObject.class)) {

            businessObjectDescriptor.setAnnotatedFields(getAnnotatedFields(annotationObjectClass));
            businessObjectDescriptor.setClassToBeConsideredInComparison(
                    objectClass.getAnnotation(BusinessObject.class).includeClassAsBusinessField());
            businessObjectDescriptor.setNearestBusinessObjectClass(objectClass);
            return businessObjectDescriptor;
        } else {
            return getBusinessObjectDescriptor(objectClass.getSuperclass(), annotationObjectClass);
        }

    }
}

From source file:io.swagger.jaxrs.ParameterExtractor.java

public static List<Parameter> getParameters(Swagger swagger, Class cls, Method method) {
    List<Parameter> parameters = new ArrayList<>();
    Type[] genericParameterTypes = method.getGenericParameterTypes();
    Annotation[][] paramAnnotations = method.getParameterAnnotations();
    for (int i = 0; i < genericParameterTypes.length; i++) {
        Type type = null;/*from   w  w w  .  j a  v a2  s.c  o m*/
        if (SynapseEndpointServiceMarker.class.isAssignableFrom(cls)) {
            //an RPC style endpoint (implements SynapseEndpointServiceMarker)
            type = TypeFactory.defaultInstance().constructType(ParameterWrapper.class, cls);
        } else if (cls.getAnnotation(Service.class) != null) {
            //an endpoint with @Service annotation
            if (genericParameterTypes[i] instanceof ParameterizedType && Request.class
                    .isAssignableFrom((Class<?>) ((ParameterizedType) genericParameterTypes[i]).getRawType())) {
                //if Request or Event Object
                type = TypeFactory.defaultInstance().constructType(
                        ((ParameterizedType) genericParameterTypes[i]).getActualTypeArguments()[0], cls);
            } else {
                type = TypeFactory.defaultInstance().constructType(genericParameterTypes[i], cls);
            }

        }

        extractParameters(swagger, parameters, type, Arrays.asList(paramAnnotations[i]));
    }
    return parameters;
}

From source file:eu.udig.omsbox.utils.OmsBoxUtils.java

/**
 * Generate the module documentation in the configuration area.
 * // ww w.j av  a2s. c  o m
 * @param moduleClassName the class for which to generate the doc.
 * @throws Exception
 */
@SuppressWarnings("nls")
public static void generateModuleDocumentation(String moduleClassName) throws Exception {

    Class<?> moduleClass = OmsModulesManager.getInstance().getModulesClass(moduleClassName);

    StringBuilder sb = new StringBuilder();
    sb.append("<html><body>\n");

    // modules documentation
    Documentation documentation = moduleClass.getAnnotation(Documentation.class);
    String documentationStr = null;
    if (documentation != null) {
        documentationStr = AnnotationUtilities.getLocalizedDocumentation(documentation);
        if (documentationStr.length() == 0) {
            documentationStr = null;
        } else if (documentationStr.equals(" - ")) {
            documentationStr = null;
        }
    }
    if (documentation != null && documentationStr != null) {
        if (documentationStr.endsWith(DOCSSUFFIX)) {
            // have to get the file
            String modulePackage = moduleClassName.substring(0, moduleClassName.lastIndexOf('.'));
            String path = modulePackage.replaceAll("\\.", "/") + "/" + documentationStr;
            InputStream inStream = OmsModulesManager.getInstance().getResourceAsStream(path);
            // InputStream inStream = moduleClass.getResourceAsStream(documentationStr);
            if (inStream != null) {
                BufferedReader br = null;
                try {
                    br = new BufferedReader(new InputStreamReader(inStream));
                    StringBuilder tmpSb = new StringBuilder();
                    String line = "";
                    while ((line = br.readLine()) != null) {
                        tmpSb.append(line).append(NEWLINE);
                    }
                    documentationStr = tmpSb.toString();
                } finally {
                    if (br != null)
                        br.close();
                }
            }
        }
        sb.append("<h2>Description</h2>").append(NEWLINE);
        sb.append(NEWLINE);
        sb.append("<blockquote>");
        sb.append(documentationStr);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
        sb.append(NEWLINE);
    } else {
        // try with module description
        Description description = moduleClass.getAnnotation(Description.class);
        String descriptionStr = AnnotationUtilities.getLocalizedDescription(description);
        if (description != null) {
            sb.append("<h2>Description</h2>").append(NEWLINE);
            sb.append(NEWLINE);
            sb.append("<blockquote>");
            sb.append(descriptionStr);
            sb.append("</blockquote>");
            sb.append(NEWLINE);
            sb.append(NEWLINE);
        }
    }
    // general info
    sb.append("<h2>General Information</h2>").append(NEWLINE);
    sb.append(NEWLINE);
    // general info: status
    Status status = moduleClass.getAnnotation(Status.class);
    if (status != null) {
        sb.append("<blockquote>");
        sb.append("Module status: " + getStatusString(status.value())).append(NEWLINE);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
    }

    // general info: script name
    Name name = moduleClass.getAnnotation(Name.class);
    String nameStr = AnnotationUtilities.getLocalizedName(name);
    if (name != null) {
        sb.append("<blockquote>");
        sb.append(" Name to use in a script: <b>" + nameStr + "</b>").append(NEWLINE);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
    }
    // general info: authors
    Author author = moduleClass.getAnnotation(Author.class);
    if (author != null) {
        String authorNameStr = author.name();
        String[] authorNameSplit = authorNameStr.split(",");

        String authorContactStr = author.contact();
        String[] authorContactSplit = authorContactStr.split(",");

        sb.append("<blockquote>");
        sb.append(" Authors ").append(NEWLINE);
        sb.append(HTMLNEWLINE);
        sb.append("<ul>").append(NEWLINE);
        for (String authorName : authorNameSplit) {
            sb.append("<li>").append(authorName.trim());
        }
        sb.append("</li>").append(NEWLINE);
        sb.append("</ul>").append(NEWLINE);
        sb.append(NEWLINE);
        sb.append(HTMLNEWLINE);
        sb.append(HTMLNEWLINE);
        // if (authorContactStr.startsWith("http")) {
        // authorContactStr = "<a href=\"" + authorContactStr + "\">" + authorContactStr +
        // "</a>";
        // }
        sb.append(" Contacts: ").append(NEWLINE);
        sb.append(HTMLNEWLINE);
        sb.append("<ul>").append(NEWLINE);
        for (String authorContact : authorContactSplit) {
            sb.append("<li>").append(authorContact.trim());
        }
        sb.append("</li>").append(NEWLINE);
        sb.append("</ul>").append(NEWLINE);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
    }
    // general info: license
    License license = moduleClass.getAnnotation(License.class);
    if (license != null) {
        String licenseStr = AnnotationUtilities.getLocalizedLicense(license);
        sb.append("<blockquote>");
        sb.append(" License: " + licenseStr).append(NEWLINE);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
    }
    // general info: keywords
    Keywords keywords = moduleClass.getAnnotation(Keywords.class);
    if (keywords != null) {
        String keywordsStr = AnnotationUtilities.getLocalizedKeywords(keywords);
        sb.append("<blockquote>");
        sb.append(" Keywords: " + keywordsStr).append(NEWLINE);
        sb.append("</blockquote>");
        sb.append(NEWLINE);
    }
    sb.append(NEWLINE);

    // gather input fields
    Object annotatedObject = moduleClass.newInstance();
    ComponentAccess cA = new ComponentAccess(annotatedObject);

    // parameters
    sb.append("<h2>Parameters</h2>").append(NEWLINE);
    sb.append(NEWLINE);
    sb.append("<blockquote>");
    // parameters: fields
    Collection<Access> inputs = cA.inputs();
    StringBuilder sbTmp = new StringBuilder();
    collectParameters(sbTmp, inputs);
    toTable(sb, sbTmp, "Input parameters");
    sb.append(NEWLINE);
    Collection<Access> outputs = cA.outputs();
    sbTmp = new StringBuilder();
    collectParameters(sbTmp, outputs);
    toTable(sb, sbTmp, "Output parameters");
    sb.append("</blockquote>");
    sb.append(NEWLINE);
    sb.append(NEWLINE);

    sb.append("</body></html>");

    File configurationsFolder = OmsBoxPlugin.getDefault().getConfigurationsFolder();
    File htmlDocsFolder = new File(configurationsFolder, OMSBOXHTMLDOCS);
    if (!htmlDocsFolder.exists()) {
        if (!htmlDocsFolder.mkdir()) {
            throw new RuntimeException();
        }
    }

    File htmlDocs = new File(htmlDocsFolder, moduleClassName + ".html");
    FileUtils.writeStringToFile(htmlDocs, sb.toString());
}

From source file:eagle.log.entity.meta.EntityDefinitionManager.java

@SuppressWarnings("unchecked")
public static EntityDefinition createEntityDefinition(Class<? extends TaggedLogAPIEntity> cls) {

    final EntityDefinition ed = new EntityDefinition();

    ed.setEntityClass(cls);/*from   ww  w  .ja v a 2  s .c om*/
    // parse cls' annotations
    Table table = cls.getAnnotation(Table.class);
    if (table == null || table.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty table name annotated with @Table");
    }
    String tableName = table.value();
    if (EagleConfigFactory.load().isTableNamePrefixedWithEnvironment()) {
        tableName = EagleConfigFactory.load().getEnv() + "_" + tableName;
    }
    ed.setTable(tableName);

    ColumnFamily family = cls.getAnnotation(ColumnFamily.class);
    if (family == null || family.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty column family name annotated with @ColumnFamily");
    }
    ed.setColumnFamily(family.value());

    Prefix prefix = cls.getAnnotation(Prefix.class);
    if (prefix == null || prefix.value().isEmpty()) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty prefix name annotated with @Prefix");
    }
    ed.setPrefix(prefix.value());

    TimeSeries ts = cls.getAnnotation(TimeSeries.class);
    if (ts == null) {
        throw new IllegalArgumentException(
                "Entity class must have a non-empty timeseries name annotated with @TimeSeries");
    }
    ed.setTimeSeries(ts.value());

    Service service = cls.getAnnotation(Service.class);
    if (service == null || service.value().isEmpty()) {
        ed.setService(cls.getSimpleName());
    } else {
        ed.setService(service.value());
    }

    Metric m = cls.getAnnotation(Metric.class);
    Map<String, Class<?>> dynamicFieldTypes = new HashMap<String, Class<?>>();
    if (m != null) {
        // metric has to be timeseries
        if (!ts.value()) {
            throw new IllegalArgumentException("Metric entity must be time series as well");
        }
        MetricDefinition md = new MetricDefinition();
        md.setInterval(m.interval());
        ed.setMetricDefinition(md);
    }

    java.lang.reflect.Field[] fields = cls.getDeclaredFields();
    for (java.lang.reflect.Field f : fields) {
        Column column = f.getAnnotation(Column.class);
        if (column == null || column.value().isEmpty()) {
            continue;
        }
        Class<?> fldCls = f.getType();
        // intrusive check field type for metric entity
        checkFieldTypeForMetric(ed.getMetricDefinition(), f.getName(), fldCls, dynamicFieldTypes);
        Qualifier q = new Qualifier();
        q.setDisplayName(f.getName());
        q.setQualifierName(column.value());
        EntitySerDeser<?> serDeser = _serDeserMap.get(fldCls);
        if (serDeser == null) {
            throw new IllegalArgumentException(fldCls.getName() + " in field " + f.getName() + " of entity "
                    + cls.getSimpleName() + " has no serializer associated ");
        } else {
            q.setSerDeser((EntitySerDeser<Object>) serDeser);
        }
        ed.getQualifierNameMap().put(q.getQualifierName(), q);
        ed.getDisplayNameMap().put(q.getDisplayName(), q);
        // TODO: should refine rules, consider fields like "hCol", getter method should be gethCol() according to org.apache.commons.beanutils.PropertyUtils
        final String propertyName = f.getName().substring(0, 1).toUpperCase() + f.getName().substring(1);
        String getterName = "get" + propertyName;
        try {
            Method method = cls.getMethod(getterName);
            ed.getQualifierGetterMap().put(f.getName(), method);
        } catch (Exception e) {
            // Check if the type is boolean
            getterName = "is" + propertyName;
            try {
                Method method = cls.getMethod(getterName);
                ed.getQualifierGetterMap().put(f.getName(), method);
            } catch (Exception e1) {
                throw new IllegalArgumentException(
                        "Field " + f.getName() + " hasn't defined valid getter method: " + getterName, e);
            }
        }
        if (LOG.isDebugEnabled())
            LOG.debug("Field registered " + q);
    }

    // TODO: Lazy create because not used at all
    // dynamically create bean class
    if (ed.getMetricDefinition() != null) {
        Class<?> metricCls = createDynamicClassForMetric(cls.getName() + "_SingleTimestamp", dynamicFieldTypes);
        ed.getMetricDefinition().setSingleTimestampEntityClass(metricCls);
    }

    final Partition partition = cls.getAnnotation(Partition.class);
    if (partition != null) {
        final String[] partitions = partition.value();
        ed.setPartitions(partitions);
        // Check if partition fields are all tag fields. Partition field can't be column field, must be tag field.
        for (String part : partitions) {
            if (!ed.isTag(part)) {
                throw new IllegalArgumentException("Partition field can't be column field, must be tag field. "
                        + "Partition name: " + part);
            }
        }
    }

    final Indexes indexes = cls.getAnnotation(Indexes.class);
    if (indexes != null) {
        final Index[] inds = indexes.value();
        final IndexDefinition[] indexDefinitions = new IndexDefinition[inds.length];
        for (int i = 0; i < inds.length; ++i) {
            final Index ind = inds[i];
            indexDefinitions[i] = new IndexDefinition(ed, ind);
        }
        ed.setIndexes(indexDefinitions);
    }

    final ServicePath path = cls.getAnnotation(ServicePath.class);
    if (path != null) {
        if (path.path() != null && (!path.path().isEmpty())) {
            ed.setServiceCreationPath(path.path());
        }
    }

    return ed;
}

From source file:de.Keyle.MyPet.entity.MyPet.java

public static float[] getEntitySize(Class<? extends MyPetMinecraftEntity> entityMyPetClass) {
    EntitySize es = entityMyPetClass.getAnnotation(EntitySize.class);
    if (es != null) {
        return new float[] { es.height(), es.width() };
    }// w w  w.  j a  v  a  2  s .c  o m
    return new float[] { 0, 0 };
}

From source file:com.github.gekoh.yagen.ddl.TableConfig.java

private static javax.persistence.Table getTableAnnotation(Class type) {
    Class entityClass = getClassOfTableAnnotation(type);
    if (entityClass != null) {
        return (javax.persistence.Table) entityClass.getAnnotation(javax.persistence.Table.class);
    }/*from   w ww  . j a  v a2  s  .  c  o m*/
    return null;
}

From source file:com.cloudera.api.model.ApiModelTest.java

private static boolean isApiType(Class<?> type) {
    return type.getAnnotation(XmlRootElement.class) != null;
}

From source file:net.minecraftforge.fml.relauncher.CoreModManager.java

private static FMLPluginWrapper loadCoreMod(LaunchClassLoader classLoader, String coreModClass, File location) {
    String coreModName = coreModClass.substring(coreModClass.lastIndexOf('.') + 1);
    try {/*from w ww  .java 2 s.c  o  m*/
        FMLRelaunchLog.fine("Instantiating coremod class %s", coreModName);
        classLoader.addTransformerExclusion(coreModClass);
        Class<?> coreModClazz = Class.forName(coreModClass, true, classLoader);
        Name coreModNameAnn = coreModClazz.getAnnotation(IFMLLoadingPlugin.Name.class);
        if (coreModNameAnn != null && !Strings.isNullOrEmpty(coreModNameAnn.value())) {
            coreModName = coreModNameAnn.value();
            FMLRelaunchLog.finer("coremod named %s is loading", coreModName);
        }
        MCVersion requiredMCVersion = coreModClazz.getAnnotation(IFMLLoadingPlugin.MCVersion.class);
        if (!Arrays.asList(rootPlugins).contains(coreModClass)
                && (requiredMCVersion == null || Strings.isNullOrEmpty(requiredMCVersion.value()))) {
            FMLRelaunchLog.log(Level.WARN,
                    "The coremod %s does not have a MCVersion annotation, it may cause issues with this version of Minecraft",
                    coreModClass);
        } else if (requiredMCVersion != null
                && !FMLInjectionData.mccversion.equals(requiredMCVersion.value())) {
            FMLRelaunchLog.log(Level.ERROR,
                    "The coremod %s is requesting minecraft version %s and minecraft is %s. It will be ignored.",
                    coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
            return null;
        } else if (requiredMCVersion != null) {
            FMLRelaunchLog.log(Level.DEBUG,
                    "The coremod %s requested minecraft version %s and minecraft is %s. It will be loaded.",
                    coreModClass, requiredMCVersion.value(), FMLInjectionData.mccversion);
        }
        TransformerExclusions trExclusions = coreModClazz
                .getAnnotation(IFMLLoadingPlugin.TransformerExclusions.class);
        if (trExclusions != null) {
            for (String st : trExclusions.value()) {
                classLoader.addTransformerExclusion(st);
            }
        }
        DependsOn deplist = coreModClazz.getAnnotation(IFMLLoadingPlugin.DependsOn.class);
        String[] dependencies = new String[0];
        if (deplist != null) {
            dependencies = deplist.value();
        }
        SortingIndex index = coreModClazz.getAnnotation(IFMLLoadingPlugin.SortingIndex.class);
        int sortIndex = index != null ? index.value() : 0;

        IFMLLoadingPlugin plugin = (IFMLLoadingPlugin) coreModClazz.newInstance();
        String accessTransformerClass = plugin.getAccessTransformerClass();
        if (accessTransformerClass != null) {
            FMLRelaunchLog.log(Level.DEBUG, "Added access transformer class %s to enqueued access transformers",
                    accessTransformerClass);
            accessTransformers.add(accessTransformerClass);
        }
        FMLPluginWrapper wrap = new FMLPluginWrapper(coreModName, plugin, location, sortIndex, dependencies);
        loadPlugins.add(wrap);
        FMLRelaunchLog.fine("Enqueued coremod %s", coreModName);
        return wrap;
    } catch (ClassNotFoundException cnfe) {
        if (!Lists.newArrayList(rootPlugins).contains(coreModClass))
            FMLRelaunchLog.log(Level.ERROR, cnfe, "Coremod %s: Unable to class load the plugin %s", coreModName,
                    coreModClass);
        else
            FMLRelaunchLog.fine("Skipping root plugin %s", coreModClass);
    } catch (ClassCastException cce) {
        FMLRelaunchLog.log(Level.ERROR, cce,
                "Coremod %s: The plugin %s is not an implementor of IFMLLoadingPlugin", coreModName,
                coreModClass);
    } catch (InstantiationException ie) {
        FMLRelaunchLog.log(Level.ERROR, ie, "Coremod %s: The plugin class %s was not instantiable", coreModName,
                coreModClass);
    } catch (IllegalAccessException iae) {
        FMLRelaunchLog.log(Level.ERROR, iae, "Coremod %s: The plugin class %s was not accessible", coreModName,
                coreModClass);
    }
    return null;
}