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:dk.netarkivet.archive.webinterface.BatchGUI.java

/**
 * Creates the HTML code for the arguments of the constructor. It reads the resources for the batchjob, where the
 * metadata for the constructor is defined in the 'resources' annotation for the class.
 * <p>/*from w  ww.ja  v a  2 s.co  m*/
 * <br/>
 * E.g. The UrlSearch batchjob. Which has the following resources:<br/>
 *
 * @param c The class whose constructor should be used.
 * @param locale The language package.
 * @return The HTML code for the arguments for executing the batchjob.
 * @Resource(name="regex", description="The regular expression for the " + "urls.", type=java.lang.String.class)<br/>
 * @Resource(name="mimetype", type=java.lang.String.class)<br/>
 * Though the batchjob takes three arguments (thus one undefined). <br/>
 * <br/>
 * <p>
 * Arguments:&lt;br/&gt;<br/>
 * regex (The regular expression for the urls.)&lt;br/&gt;<br/>
 * &lt;input name="arg1" size="50" value=""&gt;&lt;br/&gt;<br/>
 * mimetype&lt;br/&gt;<br/>
 * &lt;input name="arg2" size="50" value=""&gt;&lt;br/&gt;<br/>
 * Argument 3 (missing argument metadata)&lt;br/&gt;<br/>
 * &lt;input name="arg3" size="50" value=""&gt;&lt;br/&gt;<br/>
 * <p>
 * <br/>
 * Which will look like: <br/>
 * <br/>
 * <p>
 * Arguments:<br/>
 * regex (The regular expression for the urls.)<br/>
 * <input name="arg1" size="50" value="" /><br/>
 * mimetype<br/>
 * <input name="arg2" size="50" value="" /><br/>
 * Argument 3 (missing argument metadata)<br/>
 * <input name="arg3" size="50" value="" /><br/>
 * <p>
 * TODO this does not work until batchjobs can be used with arguments.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
private static String getHTMLarguments(Class c, Locale locale) {
    Constructor con = findStringConstructor(c);
    Type[] params = con.getParameterTypes();

    // If no parameters, then return no content (new line).
    if (params.length < 1) {
        return "<br/>\n";
    }

    // Retrieve the resources (metadata for the arguments).
    Resources r = (Resources) c.getAnnotation(Resources.class);
    if (r == null) {
        return "<br/>\n";
    }
    Resource[] resource = r.value();

    StringBuilder res = new StringBuilder();

    res.append(I18N.getString(locale, "batchpage;Arguments", new Object[] {}) + ":<br/>\n");

    if (resource.length < params.length) {
        // warn about no metadata.
        res.append(I18N.getString(locale, "batchpage;Bad.argument.metadata.for.the.constructor", con.toString())
                + ".<br/>\n");
        // make default 'arguments'.
        for (int i = 1; i <= params.length; i++) {
            res.append(I18N.getString(locale, "batchpage;Argument.i", i) + "<br/>\n");
            res.append("<input name=\"arg" + i + "\" size=\"" + Constants.HTML_INPUT_SIZE
                    + "\" value=\"\"><br/>\n");
        }
    } else {
        // handle the case, when there is arguments.
        int parmIndex = 0;
        // retrieve the arguments from the resources.
        for (int i = 0; i < resource.length && parmIndex < params.length; i++) {
            if (resource[i].type() == params[parmIndex]) {
                // Use the resource to describe the argument.
                parmIndex++;
                res.append(resource[i].name());
                if (resource[i].description() != null && !resource[i].description().isEmpty()) {
                    res.append(" (" + resource[i].description() + ")");
                }
                res.append("<br/>\n");
                res.append("<input name=\"arg" + parmIndex + "\" size=\"" + Constants.HTML_INPUT_SIZE
                        + "\" value=\"\"><br/>\n");
            }
        }
        // If some arguments did not have a resource description, then
        // use a default 'unknown argument' input box.
        if (parmIndex < params.length) {
            for (int i = parmIndex + 1; i <= params.length; i++) {
                res.append(I18N.getString(locale, "batchpage;Argument.i.missing.argument.metadata", i)
                        + "<br/>\n");
                res.append("<input name=\"arg" + i + "\" size=\"" + Constants.HTML_INPUT_SIZE
                        + "\" value=\"\"><br/>\n");
            }
        }
    }

    res.append("<br/>\n");

    return res.toString();
}

From source file:br.gov.frameworkdemoiselle.internal.configuration.ConfigurationLoader.java

private String getPrefix(Field field, Class<?> type) {
    String prefix = "";

    Configuration classAnnotation = type.getAnnotation(Configuration.class);
    if (!Strings.isEmpty(classAnnotation.prefix())) {
        prefix = classAnnotation.prefix() + ".";
    }/*from   www  .j a  v  a  2 s . c  om*/

    return prefix;
}

From source file:de.xaniox.heavyspleef.commands.base.proxy.ProxyExecution.java

public void attachProxy(Proxy proxy) {
    Validate.isTrue(!isProxyAttached(proxy), "Proxy already attached");
    Class<? extends Proxy> clazz = proxy.getClass();

    Priority priority = Priority.NORMAL;
    if (clazz.isAnnotationPresent(ProxyPriority.class)) {
        ProxyPriority priorityAnnotation = clazz.getAnnotation(ProxyPriority.class);
        priority = priorityAnnotation.value();
    }/*from w  w w. jav  a2  s.  c  o  m*/

    String[] filter = null;
    if (clazz.isAnnotationPresent(Filter.class)) {
        Filter filterAnnotation = clazz.getAnnotation(Filter.class);
        filter = filterAnnotation.value();
    }

    ProxyHolder holder = new ProxyHolder();
    holder.proxy = proxy;
    holder.priority = priority;
    holder.filter = filter;

    proxies.add(holder);
    //Finally sort the list to get an appropriate order
    Collections.sort(proxies);
}

From source file:com.github.kongchen.swagger.docgen.mavenplugin.SpringMavenDocumentSource.java

private Map<String, SpringResource> analyzeController(Class<?> clazz, Map<String, SpringResource> resourceMap,
        String description) throws ClassNotFoundException {

    for (int i = 0; i < clazz.getAnnotation(RequestMapping.class).value().length; i++) {
        String controllerMapping = clazz.getAnnotation(RequestMapping.class).value()[i];
        String resourceName = Utils.parseResourceName(clazz);
        for (Method m : clazz.getMethods()) {
            if (m.isAnnotationPresent(RequestMapping.class)) {
                RequestMapping methodReq = m.getAnnotation(RequestMapping.class);
                if (methodReq.value() == null || methodReq.value().length == 0
                        || Utils.parseResourceName(methodReq.value()[0]).equals("")) {
                    if (resourceName.length() != 0) {
                        String resourceKey = Utils.createResourceKey(resourceName,
                                Utils.parseVersion(controllerMapping));
                        if ((!(resourceMap.containsKey(resourceKey)))) {
                            resourceMap.put(resourceKey,
                                    new SpringResource(clazz, resourceName, resourceKey, description));
                        }//  w  w  w  .ja  va  2 s  .co  m
                        resourceMap.get(resourceKey).addMethod(m);
                    }
                }
            }
        }
    }
    clazz.getFields();
    clazz.getDeclaredFields(); //<--In case developer declares a field without an associated getter/setter.
    //this will allow NoClassDefFoundError to be caught before it triggers bamboo failure.

    return resourceMap;
}

From source file:com.github.gekoh.yagen.api.DefaultNamingStrategy.java

@Override
public String classToTableName(String className) {
    try {//from   ww  w . j ava2 s .co  m
        Class<?> aClass = Class.forName(className);
        if (aClass.isAnnotationPresent(javax.persistence.Table.class)) {
            String tableName = aClass.getAnnotation(javax.persistence.Table.class).name();
            if (StringUtils.isNotEmpty(tableName)) {
                return tableName(tableName);
            }
        }
    } catch (ClassNotFoundException ignore) {
    }
    return super.classToTableName(className);
}

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

private Integer saveAuditLog(Class<?> targetCls, Object bean, String username, Integer sAccountId,
        Integer activityStreamId) {
    Auditable auditAnnotation = targetCls.getAnnotation(Auditable.class);
    if (auditAnnotation != null) {
        String key;//from   w w w.  j  av  a 2 s  .  co  m
        String changeSet = "";
        try {

            int typeid = (Integer) PropertyUtils.getProperty(bean, "id");
            key = bean.toString() + ClassInfoMap.getType(targetCls) + typeid;

            Object oldValue = caches.get(key);
            if (oldValue != null) {
                AuditLog auditLog = new AuditLog();
                auditLog.setPosteduser(username);
                auditLog.setModule(ClassInfoMap.getModule(targetCls));
                auditLog.setType(ClassInfoMap.getType(targetCls));
                auditLog.setTypeid(typeid);
                auditLog.setSaccountid(sAccountId);
                auditLog.setPosteddate(new GregorianCalendar().getTime());
                changeSet = AuditLogUtil.getChangeSet(oldValue, bean);
                auditLog.setChangeset(changeSet);
                auditLog.setObjectClass(oldValue.getClass().getName());
                if (activityStreamId != null) {
                    auditLog.setActivitylogid(activityStreamId);
                }

                return auditLogService.saveWithSession(auditLog, "");
            }
        } catch (Exception e) {
            LOG.error("Error when save audit for save action of service " + targetCls.getName() + "and bean: "
                    + BeanUtility.printBeanObj(bean) + " and changeset is " + changeSet, e);
            return null;
        }
    }

    return null;
}

From source file:com.searchbox.framework.web.ApplicationConversionService.java

@Override
public void afterPropertiesSet() throws Exception {

    LOGGER.info("Scanning for SearchComponents");
    Map<Class<?>, String> conditionUrl = new HashMap<Class<?>, String>();
    ClassPathScanningCandidateComponentProvider scanner;

    // Getting all the SearchElements
    scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(SearchCondition.class));
    for (BeanDefinition bean : scanner.findCandidateComponents("com.searchbox")) {
        try {/*  w  w w.j  a v a 2  s . c  om*/
            Class<?> clazz = Class.forName(bean.getBeanClassName());
            String urlParam = clazz.getAnnotation(SearchCondition.class).urlParam();
            conditionUrl.put(clazz, urlParam);
        } catch (Exception e) {
            LOGGER.error("Could not introspect SearchElement: " + bean, e);
        }
    }

    // Getting all converters for SearchConditions
    scanner = new ClassPathScanningCandidateComponentProvider(false);
    scanner.addIncludeFilter(new AnnotationTypeFilter(SearchConverter.class));
    for (BeanDefinition bean : scanner.findCandidateComponents("com.searchbox")) {
        try {
            Class<?> clazz = Class.forName(bean.getBeanClassName());
            for (Type i : clazz.getGenericInterfaces()) {
                ParameterizedType pi = (ParameterizedType) i;
                for (Type piarg : pi.getActualTypeArguments()) {
                    if (AbstractSearchCondition.class.isAssignableFrom(((Class<?>) piarg))) {
                        Class<?> conditionClass = ((Class<?>) piarg);
                        searchConditions.put(conditionUrl.get(conditionClass), ((Class<?>) piarg));
                        this.addConverter((Converter<?, ?>) clazz.newInstance());
                        LOGGER.info("Registered Converter " + clazz.getSimpleName() + " for "
                                + ((Class<?>) piarg).getSimpleName() + " with prefix: "
                                + conditionUrl.get(conditionClass));
                    }
                }
            }
        } catch (Exception e) {
            LOGGER.error("Could not create Converter for: " + bean.getBeanClassName(), e);
        }
    }

    this.addConverter(new Converter<String, SearchboxEntity>() {
        @Override
        public SearchboxEntity convert(String slug) {
            return searchboxRepository.findBySlug(slug);
        }
    });

    this.addConverter(new Converter<SearchboxEntity, String>() {
        @Override
        public String convert(SearchboxEntity searchbox) {
            return searchbox.getSlug();
        }
    });

    this.addConverter(new Converter<Long, SearchboxEntity>() {
        @Override
        public SearchboxEntity convert(java.lang.Long id) {
            return searchboxRepository.findOne(id);
        }
    });

    this.addConverter(new Converter<SearchboxEntity, Long>() {
        @Override
        public Long convert(SearchboxEntity searchbox) {
            return searchbox.getId();
        }
    });

    this.addConverter(new Converter<String, PresetEntity>() {
        @Override
        public PresetEntity convert(String slug) {
            return presetRepository.findPresetDefinitionBySlug(slug);
        }
    });

    this.addConverter(new Converter<Long, PresetEntity>() {
        @Override
        public PresetEntity convert(java.lang.Long id) {
            return presetRepository.findOne(id);
        }
    });

    this.addConverter(new Converter<PresetEntity, String>() {
        @Override
        public String convert(PresetEntity presetDefinition) {
            return new StringBuilder().append(presetDefinition.getSlug()).toString();
        }
    });

    this.addConverter(new Converter<Class<?>, String>() {
        @Override
        public String convert(Class<?> source) {
            return source.getName();
        }
    });

    this.addConverter(new Converter<String, Class<?>>() {

        @Override
        public Class<?> convert(String source) {
            try {
                // TODO Such a bad hack...
                if (source.contains("class")) {
                    source = source.replace("class", "").trim();
                }
                return context.getClassLoader().loadClass(source);
                // Class.forName(source);
            } catch (ClassNotFoundException e) {
                LOGGER.error("Could not convert \"" + source + "\" to class.", e);
            }
            return null;
        }

    });
}

From source file:com.actionbarsherlock.ActionBarSherlock.java

/**
 * Register an ActionBarSherlock implementation.
 *
 * @param implementationClass Target implementation class which extends
 * {@link ActionBarSherlock}. This class must also be annotated with
 * {@link Implementation}.//  ww  w.java  2s  . c o m
 */
public static void registerImplementation(Class<? extends ActionBarSherlock> implementationClass) {
    if (!implementationClass.isAnnotationPresent(Implementation.class)) {
        throw new IllegalArgumentException(
                "Class " + implementationClass.getSimpleName() + " is not annotated with @Implementation");
    } else if (IMPLEMENTATIONS.containsValue(implementationClass)) {
        if (DEBUG)
            Log.w(TAG, "Class " + implementationClass.getSimpleName() + " already registered");
        return;
    }

    Implementation impl = implementationClass.getAnnotation(Implementation.class);
    if (DEBUG)
        Log.i(TAG, "Registering " + implementationClass.getSimpleName() + " with qualifier " + impl);
    IMPLEMENTATIONS.put(impl, implementationClass);
}

From source file:atunit.spring.SpringContainer.java

protected void loadBeanDefinitions(Class<?> testClass, BeanDefinitionRegistry registry) {
    XmlBeanDefinitionReader xml = new XmlBeanDefinitionReader(registry);

    String resourceName = testClass.getSimpleName() + ".xml";
    Context ctxAnno = testClass.getAnnotation(Context.class);
    if (ctxAnno != null) {
        resourceName = ctxAnno.value();/*from  w  w w  .  j  a  v  a  2 s .  c  o  m*/
    }
    URL xmlUrl = testClass.getResource(resourceName);
    if (xmlUrl != null) {
        xml.loadBeanDefinitions(new UrlResource(xmlUrl));
    } else if (ctxAnno != null) {
        // is this the appropriate exception here?
        throw new ApplicationContextException("Could not find context file named " + resourceName);
    }
}

From source file:adalid.core.ExportOperation.java

private void annotateExportOperationClass(Class<?> type) {
    Class<?> annotatedClass = XS1.getAnnotatedClass(type, ExportOperationClass.class);
    if (annotatedClass != null) {
        ExportOperationClass annotation = annotatedClass.getAnnotation(ExportOperationClass.class);
        if (annotation != null) {
            String name = annotation.name();
            if (StringUtils.isNotBlank(name)) {
                _exportName = name;/*from  www  . j  av  a2 s.c  o  m*/
            }
            _viewName = annotation.view();
            _viewFieldName = annotation.viewField();
            _queryType = annotation.type();
            _rowsLimit = Math.max(0, annotation.rowsLimit());
            _detailRowsLimit = Math.max(0, annotation.detailRowsLimit());
            _summaryRowsLimit = Math.max(0, annotation.summaryRowsLimit());
            _chartRowsLimit = Math.max(0, annotation.chartRowsLimit());
            _sortOption = annotation.sortOption();
            _annotatedWithExportOperationClass = true;
            if (StringUtils.isNotBlank(_viewFieldName)) {
                Operation declaringOperation = this;
                Entity declaringEntity = declaringOperation.getDeclaringEntity();
                Class<?>[] validTypes = new Class<?>[] { View.class };
                String[] strings = new String[] { declaringOperation.getName(), getName(), "viewField" };
                String role = StringUtils.join(strings, ".");
                _viewField = XS1.getField(true, role, _viewFieldName, declaringEntity.getClass(), Entity.class,
                        validTypes);
                if (_viewField != null) {
                    _view = XS1.getView(_viewField, declaringEntity);
                }
            }
        }
    }
}