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:jsa.endpoint.cxf.RestRouteBuilder.java

private List<Object> getAdditionalProviders(Class<?> restDecorator) {
    List<Object> providers = new LinkedList<Object>();

    // add global API module config
    if (jaxRsConfig != null) {
        jaxRsConfig.addProviders(providers);
    }/*from  w w  w.  java  2 s  . c o  m*/

    // add local API config
    ExposeRest rest = restDecorator.getAnnotation(ExposeRest.class);
    Class<?>[] localProviders = rest.providers();
    for (Class<?> providerClass : localProviders) {
        try {
            providers.add(providerClass.newInstance());
        } catch (Exception e) {
            log.warn("Could not instantiate provider : " + providerClass, e);
        }
    }

    // if nothing so far, put JSON Provider
    if (providers.isEmpty()) {
        providers.add(new JacksonJsonProvider());
    }

    // add default ones
    providers.add(new SourceCodeHandler(context));
    providers.add(new WadlGeneratorExt());

    return providers;
}

From source file:hivemall.docs.FuncsListGenerator.java

private void generate(@Nonnull File outputFile, @Nonnull String preface,
        @Nonnull Map<String, List<String>> headers) throws MojoExecutionException {
    Reflections reflections = new Reflections("hivemall");
    Set<Class<?>> annotatedClasses = reflections.getTypesAnnotatedWith(Description.class);

    StringBuilder sb = new StringBuilder();
    Map<String, Set<String>> packages = new HashMap<>();

    Pattern func = Pattern.compile("_FUNC_(\\(.*?\\))(.*)", Pattern.DOTALL);

    for (Class<?> annotatedClass : annotatedClasses) {
        Deprecated deprecated = annotatedClass.getAnnotation(Deprecated.class);
        if (deprecated != null) {
            continue;
        }/* w w  w.  j  a va  2 s .  c om*/

        Description description = annotatedClass.getAnnotation(Description.class);

        String value = description.value().replaceAll("\n", " ");
        Matcher matcher = func.matcher(value);
        if (matcher.find()) {
            value = asInlineCode(description.name() + matcher.group(1)) + escapeHtml(matcher.group(2));
        }
        sb.append(asListElement(value));

        StringBuilder sbExtended = new StringBuilder();
        if (!description.extended().isEmpty()) {
            sbExtended.append(description.extended());
            sb.append("\n");
        }

        String extended = sbExtended.toString();
        if (extended.isEmpty()) {
            sb.append("\n");
        } else {
            if (extended.toLowerCase().contains("select")) { // extended description contains SQL statements
                sb.append(indent(asCodeBlock(extended, "sql")));
            } else {
                sb.append(indent(asCodeBlock(extended)));
            }
        }

        String packageName = annotatedClass.getPackage().getName();
        if (!packages.containsKey(packageName)) {
            Set<String> set = new TreeSet<>();
            packages.put(packageName, set);
        }
        Set<String> List = packages.get(packageName);
        List.add(sb.toString());

        StringUtils.clear(sb);
    }

    try (PrintWriter writer = new PrintWriter(outputFile)) {
        // license header
        writer.println("<!--");
        try {
            File licenseFile = new File(basedir, "resources/license-header.txt");
            FileReader fileReader = new FileReader(licenseFile);

            try (BufferedReader bufferedReader = new BufferedReader(fileReader)) {
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    writer.println(indent(line));
                }
            }
        } catch (IOException e) {
            throw new MojoExecutionException("Failed to read license file");
        }
        writer.println("-->\n");

        writer.println(preface);

        writer.println("\n<!-- toc -->\n");

        for (Map.Entry<String, List<String>> e : headers.entrySet()) {
            writer.println(e.getKey() + "\n");
            List<String> packageNames = e.getValue();
            for (String packageName : packageNames) {
                for (String desc : packages.get(packageName)) {
                    writer.println(desc);
                }
            }
        }

        writer.flush();
    } catch (FileNotFoundException e) {
        throw new MojoExecutionException("Output file is not found");
    }
}

From source file:cn.afterturn.easypoi.excel.imports.sax.parse.SaxRowRead.java

private void initParams(Class<?> pojoClass, ImportParams params) {
    try {//from  w ww. j a v a  2  s. c  o  m

        Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
        ExcelTarget etarget = pojoClass.getAnnotation(ExcelTarget.class);
        if (etarget != null) {
            targetId = etarget.value();
        }
        getAllExcelField(targetId, fileds, excelParams, excelCollection, pojoClass, null, null);
    } catch (Exception e) {
        LOGGER.error(e.getMessage(), e);
        throw new ExcelImportException(e.getMessage());
    }

}

From source file:com.neelo.glue.ApplicationModule.java

public void register(Class<?> resourceClass) {
    log.info("Registering: " + resourceClass.getName());

    Resource resource = null;/*from   www  . j a va 2  s . c om*/

    if (resourceClass.isAnnotationPresent(Resource.class)) {
        resource = resourceClass.getAnnotation(Resource.class);
    } else {
        log.warn("Class not registerd. Missing " + Resource.class.getSimpleName() + " annotation");
        return;
    }

    ResourceBuilder builder = new ResourceBuilder(resourceClass, resource.path(), resource.layout());

    Method[] methods = resourceClass.getDeclaredMethods();
    for (Method method : methods) {
        if (method.isAnnotationPresent(Get.class)) {
            Get get = method.getAnnotation(Get.class);

            RouteBuilder route = builder.get(method, get.path(), get.content());

            route.setLayout(StringUtils.isNotBlank(get.layout()) ? get.layout() : resource.layout());
            if (StringUtils.isNotBlank(get.name()))
                route.setName(get.name());

            routes.add(route);
        } else if (method.isAnnotationPresent(Post.class)) {
            Post post = method.getAnnotation(Post.class);

            RouteBuilder route = builder.post(method, post.path(), post.content());

            route.setLayout(StringUtils.isNotBlank(post.layout()) ? post.layout() : resource.layout());
            if (StringUtils.isNotBlank(post.name()))
                route.setName(post.name());

            routes.add(route);
        }
    }
}

From source file:com.parse.simple.SimpleParseCache.java

public synchronized String getClassName(Class<?> klass) {
    String name = SimpleParseCache.get().classNameCache.get(klass);

    if (name != null) {
        return name;
    }//from   w  ww .j  a v a  2  s.  c o  m

    final ParseClassName classAnnotation = klass.getAnnotation(ParseClassName.class);

    if (classAnnotation != null) {
        name = classAnnotation.value();
    } else {
        name = klass.getSimpleName();
    }

    SimpleParseCache.get().classNameCache.put(klass, name); // assert(name)

    return name;
}

From source file:com.thinkbiganalytics.feedmgr.sla.ServiceLevelAgreementActionConfigTransformer.java

public List<ServiceLevelAgreementActionValidation> validateAction(String actionConfigurationClassName) {
    List<ServiceLevelAgreementActionValidation> validation = null;
    try {// ww  w.j  av a  2  s  .c o m
        Class<? extends ServiceLevelAgreementActionConfiguration> configurationClass = ClassNameChangeRegistry
                .findClass(actionConfigurationClassName);
        ServiceLevelAgreementActionConfig annotation = (ServiceLevelAgreementActionConfig) configurationClass
                .getAnnotation(ServiceLevelAgreementActionConfig.class);
        Class<? extends ServiceLevelAgreementAction>[] actions = annotation.actionClasses();
        if (actions != null) {
            List<Class<? extends ServiceLevelAgreementAction>> actionClassList = Lists.newArrayList(actions);
            validation = ServiceLevelAgreementActionUtil.validateActionConfiguration(actionClassList);
        } else {
            validation.add(new ServiceLevelAgreementActionValidation(false,
                    "No Actions are defined for :" + actionConfigurationClassName));
        }

    } catch (ClassNotFoundException e) {
        validation.add(new ServiceLevelAgreementActionValidation(false,
                "ImmutableAction Configuration Not Found: " + e.getMessage()));
    }

    return validation;

}

From source file:com.google.api.ads.adwords.awreporting.model.csv.CsvReportEntitiesMapping.java

/**
 * Initializes the report type definition map.
 *
 * The base package is scanned in order to find the candidates to report beans, and the map of
 * {@code ReportDefinitionReportType} to the report bean class is created, based on the annotated
 * classes.//w  w w.ja va 2 s . c  o m
 *
 */
public void initializeReportMap() {

    List<Class<? extends Report>> reportBeans;
    try {
        reportBeans = this.findReportBeans(this.packageToScan);

    } catch (ClassNotFoundException e) {
        LOGGER.severe("Class not found in classpath: " + e.getMessage());
        throw new IllegalStateException(e);
    } catch (IOException e) {
        LOGGER.severe("Could not read class file: " + e.getMessage());
        throw new IllegalStateException(e);
    }

    for (Class<? extends Report> reportBeanClass : reportBeans) {
        CsvReport csvReport = reportBeanClass.getAnnotation(CsvReport.class);
        this.reportDefinitionMap.put(csvReport.value(), reportBeanClass);

        Set<String> propertyExclusions = new HashSet<String>();
        String[] reportExclusionsArray = csvReport.reportExclusions();
        propertyExclusions.addAll(Arrays.asList(reportExclusionsArray));

        List<String> propertiesToSelect = this.findReportPropertiesToSelect(reportBeanClass,
                propertyExclusions);
        this.reportProperties.put(csvReport.value(), propertiesToSelect);
    }
}

From source file:com.bstek.dorado.view.registry.ComponentTypeRegister.java

@SuppressWarnings("unchecked")
protected ComponentTypeRegisterInfo getRegisterInfo() throws Exception {
    Class<? extends Component> cl = null;
    if (StringUtils.isNotEmpty(classType)) {
        cl = ClassUtils.forName(classType);
    }/*w w w .  j  av  a2s.  co m*/

    Widget widget = null;
    if (cl != null) {
        widget = cl.getAnnotation(Widget.class);
        if (widget != null && StringUtils.isEmpty(name) && StringUtils.isNotEmpty(widget.name())) {
            name = widget.name();
        }
    }

    if (StringUtils.isEmpty(name)) {
        int i = beanName.lastIndexOf(".");
        if (i >= 0) {
            name = beanName.substring(i + 1);
        }
    }

    ComponentTypeRegisterInfo registerInfo = createRegisterInfo(name);
    registerInfo.setClassType(cl);
    if (widget != null) {
        registerInfo.setCategory(widget.category());
    }

    int clientTypesValue = ClientType.parseClientTypes(clientTypes);
    if (clientTypesValue > 0) {
        registerInfo.setClientTypes(clientTypesValue);
    }
    return registerInfo;
}

From source file:org.jdbcluster.metapersistence.cluster.ClusterFactory.java

/**
 * creates an instance of a Cluster//from  ww w  .j  a va  2 s. c o  m
 * Cluster interceptor is <b>not called</b> if dao!=null
 * Cluster privileges are <b>not checked</b> if dao!=null 
 * @param clusterClass class of cluster
 * @param dao dao object to be presetted
 * @param daoIsPersistent if dao Object is persistent dont call interceptor and pivilegeInterceptor
 * @param user saves the given User object into the newly created Cluster object.
 * @return the new Cluster instance.
 */
@SuppressWarnings("unchecked")
public static <T extends Cluster> T newInstance(Class<? extends ICluster> clusterClass, Object dao,
        boolean daoIsPersistent, IUser user) {

    Assert.notNull(clusterClass, "Class<?> may not be null");

    PrivilegeChecker pc = PrivilegeCheckerImpl.getInstance();
    Cluster cluster = null;
    try {
        //create a new instance with given classname
        cluster = (Cluster) clusterClass.newInstance();
    } catch (InstantiationException e) {
        throw new ClusterTypeException(
                "specified class [" + clusterClass.getName()
                        + "] object cannot be instantiated because it is an interface or is an abstract class",
                e);
    } catch (IllegalAccessException e) {
        throw new ClusterTypeException(
                "the currently executed ctor for class [" + clusterClass.getName() + "] does not have access",
                e);
    }
    if (user != null) {
        cluster.setUser(user);
    }
    if (dao != null)
        cluster.setDao(dao);
    else {
        DaoLink classAnno = clusterClass.getAnnotation(DaoLink.class);
        if (classAnno != null)
            cluster.setDao(Dao.newInstance(classAnno.dAOClass()));
    }

    if (!daoIsPersistent) {
        /*
         * call of cluster interceptor
         */
        if (!getClusterInterceptor().clusterNew(cluster))
            throw new ConfigurationException(
                    "ClusterInterceptor [" + getClusterInterceptor().getClass().getName() + "] returned false");

        /*
         * privilege check (only static privileges are checked)
         */
        if (cluster instanceof PrivilegedCluster) {
            if (!pc.userPrivilegeIntersect(user, (PrivilegedCluster) cluster))
                throw new PrivilegeException(
                        "No sufficient privileges for new Cluster class [" + clusterClass.getName() + "]");
        }
    }
    cluster.setClusterType(ClusterTypeFactory.newInstance(clusterClass));
    return (T) cluster;
}

From source file:nivance.jpa.cassandra.prepare.core.CassandraSessionFactoryBean.java

public String getTableName(Class<?> entityClass) {
    if (entityClass == null) {
        throw new InvalidDataAccessApiUsageException(
                "No class parameter provided, entity table name can't be determined!");
    }/*from  w  w w .  ja va  2 s. co m*/
    Table table = entityClass.getAnnotation(Table.class);
    if (table == null) {
        throw new InvalidDataAccessApiUsageException("Tablename is null:: " + entityClass.getName());
    }

    //      CassandraPersistentEntity<?> entity = mappingContext.getPersistentEntity(entityClass);
    //      if (entity == null) {
    //         throw new InvalidDataAccessApiUsageException("No Persitent Entity information found for the class "
    //               + entityClass.getName());
    //      }
    return table.name();
}