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.dbs.sdwt.jpa.JpaUniqueUtil.java

private List<String> validateSimpleUniqueConstraintsDefinedOnMethods(Identifiable<?> entity) {
    Class<?> entityClass = getClassWithoutInitializingProxy(entity);
    List<String> errors = newArrayList();
    for (Method method : entityClass.getMethods()) {
        Column column = entityClass.getAnnotation(Column.class);
        if (column != null && column.unique()) {
            Map<String, Object> values = newHashMap();
            String property = jpaUtil.methodToProperty(method);
            values.put(property, invokeMethod(method, entity));
            if (existsInDatabaseOnAllObjects(entity, values)) {
                errors.add(simpleUniqueConstraintError(entity, property));
            }/*from  w w w  .j  a v a  2  s .  c o  m*/
        }
    }
    return errors;
}

From source file:com.yunmel.syncretic.core.BaseService.java

/**
 * ??()//from ww  w  .j  a  va2 s  . c  o m
 * 
 * @param id id
 * @param Field ???
 * @param beans class ??class class
 * @return -1
 */
public int beforeDeleteTreeStructure(Object id, String Field, Class<?>... beans) {
    Map<String, Object> map = new HashMap<String, Object>();
    map.put("id", id);
    map.put("checkField", StrUtils.camelhumpToUnderline(Field));
    for (int i = 0; i < beans.length; i++) {
        Class<?> cl = beans[i];
        Table table = cl.getAnnotation(Table.class);
        if (table == null) {
            throw new RuntimeException("?table");
        }
        String tableName = table.name();
        // String tableName = StringConvert.camelhumpToUnderline(cl.getSimpleName());
        map.put("t" + i, tableName);
    }
    int count = 0; // baseMapper.beforeDeleteTreeStructure(map);
    return count > 0 ? -1 : count;
}

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

@Override
public void loadDocuments() throws GenerateException {
    Map<String, SpringResource> resourceMap = new HashMap<String, SpringResource>();
    SwaggerConfig swaggerConfig = new SwaggerConfig();
    swaggerConfig.setApiVersion(apiSource.getApiVersion());
    swaggerConfig.setSwaggerVersion(SwaggerSpec.version());
    List<ApiListingReference> apiListingReferences = new ArrayList<ApiListingReference>();
    List<AuthorizationType> authorizationTypes = new ArrayList<AuthorizationType>();

    //relate all methods to one base request mapping if multiple controllers exist for that mapping
    //get all methods from each controller & find their request mapping
    //create map - resource string (after first slash) as key, new SpringResource as value
    for (Class<?> c : apiSource.getValidClasses()) {
        RequestMapping requestMapping = (RequestMapping) c.getAnnotation(RequestMapping.class);
        String description = "";
        if (c.isAnnotationPresent(Api.class)) {
            description = ((Api) c.getAnnotation(Api.class)).value();
        }/*w  w  w.j av  a  2s .c  o m*/
        if (requestMapping != null && requestMapping.value().length != 0) {
            //This try/catch block is to stop a bamboo build from failing due to NoClassDefFoundError
            //This occurs when a class or method loaded by reflections contains a type that has no dependency
            try {
                resourceMap = analyzeController(c, resourceMap, description);
                List<Method> mList = new ArrayList<Method>(Arrays.asList(c.getMethods()));
                if (c.getSuperclass() != null) {
                    mList.addAll(Arrays.asList(c.getSuperclass().getMethods()));
                }
                for (Method m : mList) {
                    if (m.isAnnotationPresent(RequestMapping.class)) {
                        RequestMapping methodReq = m.getAnnotation(RequestMapping.class);
                        //isolate resource name - attempt first by the first part of the mapping
                        if (methodReq != null && methodReq.value().length != 0) {
                            for (int i = 0; i < methodReq.value().length; i++) {
                                String resourceKey = "";
                                String resourceName = Utils.parseResourceName(methodReq.value()[i]);
                                if (!(resourceName.equals(""))) {
                                    String version = Utils.parseVersion(requestMapping.value()[0]);
                                    //get version - first try by class mapping, then method
                                    if (version.equals("")) {
                                        //class mapping failed - use method
                                        version = Utils.parseVersion(methodReq.value()[i]);
                                    }
                                    resourceKey = Utils.createResourceKey(resourceName, version);
                                    if ((!(resourceMap.containsKey(resourceKey)))) {
                                        resourceMap.put(resourceKey,
                                                new SpringResource(c, resourceName, resourceKey, description));
                                    }
                                    resourceMap.get(resourceKey).addMethod(m);
                                }
                            }
                        }
                    }
                }
            } catch (NoClassDefFoundError e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
                //exception occurs when a method type or annotation is not recognized by the plugin
            } catch (ClassNotFoundException e) {
                LOG.error(e.getMessage());
                LOG.info(c.getName());
            }

        }
    }
    for (String str : resourceMap.keySet()) {
        ApiListing doc = null;
        SpringResource resource = resourceMap.get(str);

        try {
            doc = getDocFromSpringResource(resource, swaggerConfig);
            setBasePath(doc.basePath());
        } catch (Exception e) {
            LOG.error("DOC NOT GENERATED FOR: " + resource.getResourceName());
            e.printStackTrace();
        }
        if (doc == null)
            continue;
        ApiListingReference apiListingReference = new ApiListingReference(doc.resourcePath(), doc.description(),
                doc.position());
        apiListingReferences.add(apiListingReference);
        acceptDocument(doc);

    }
    // sort apiListingRefernce by position
    Collections.sort(apiListingReferences, new Comparator<ApiListingReference>() {
        @Override
        public int compare(ApiListingReference o1, ApiListingReference o2) {
            if (o1 == null && o2 == null)
                return 0;
            if (o1 == null && o2 != null)
                return -1;
            if (o1 != null && o2 == null)
                return 1;
            return o1.position() - o2.position();
        }
    });
    serviceDocument = new ResourceListing(swaggerConfig.apiVersion(), swaggerConfig.swaggerVersion(),
            scala.collection.immutable.List
                    .fromIterator(JavaConversions.asScalaIterator(apiListingReferences.iterator())),
            scala.collection.immutable.List.fromIterator(
                    JavaConversions.asScalaIterator(authorizationTypes.iterator())),
            swaggerConfig.info());
}

From source file:org.jsconf.core.ConfigurationFactory.java

public ConfigurationFactory withBean(Class<?> bean) {
    if (bean.isAnnotationPresent(ConfigurationProperties.class)) {
        ConfigurationProperties cf = bean.getAnnotation(ConfigurationProperties.class);
        return withBean(cf.value(), bean, cf.id(), cf.proxy());
    }/*from w  w w .  ja v  a 2 s. c  om*/
    throw new BeanInitializationException(
            String.format("Missing @ConfigurationProperties annotation on class %s", bean));
}

From source file:org.vaadin.addons.springsecurityviewprovider.SpringSecurityViewProvider.java

@Override
public View getView(String viewName) {
    View rv = null;/*  w  w w.j a  va2s . c  o  m*/

    // Retrieve the implementing class
    Class<? extends View> clazz = this.views.get(viewName);
    if (clazz != null) {
        // Try to find cached instance of caching is enabled and the view is cacheable
        if (isCachingEnabled() && clazz.getAnnotation(ViewDescription.class).cacheable()) {
            rv = this.cachedInstances.get(viewName);
            // retrieve the new instance and cache it if it's not already cached.
            if (rv == null)
                this.cachedInstances.put(viewName, rv = applicationContext.getBean(clazz));
        } else {
            rv = applicationContext.getBean(clazz);
        }
    }
    return rv;
}

From source file:io.gravitee.management.idp.core.plugin.impl.IdentityProviderManagerImpl.java

private <T> T create(Plugin plugin, Class<T> identityClass, Map<String, Object> properties) {
    if (identityClass == null) {
        return null;
    }//from   ww  w.ja v  a 2s.  c  om

    try {
        T identityObj = createInstance(identityClass);
        final Import annImport = identityClass.getAnnotation(Import.class);
        Set<Class<?>> configurations = (annImport != null) ? new HashSet<>(Arrays.asList(annImport.value()))
                : Collections.emptySet();

        ApplicationContext idpApplicationContext = pluginContextFactory
                .create(new AnnotationBasedPluginContextConfigurer(plugin) {
                    @Override
                    public Set<Class<?>> configurations() {
                        return configurations;
                    }

                    @Override
                    public ConfigurableEnvironment environment() {
                        return new StandardEnvironment() {
                            @Override
                            protected void customizePropertySources(MutablePropertySources propertySources) {
                                propertySources.addFirst(new MapPropertySource(plugin.id(), properties));
                                super.customizePropertySources(propertySources);
                            }
                        };
                    }
                });

        idpApplicationContext.getAutowireCapableBeanFactory().autowireBean(identityObj);

        return identityObj;
    } catch (Exception ex) {
        LOGGER.error("An unexpected error occurs while loading identity provider", ex);
        return null;
    }
}

From source file:com.flipkart.polyguice.dropwiz.PolyguiceApp.java

private void registerServlet(Class<?> type, Environment env) {
    LOGGER.debug("registering servlet: {}", type.getName());
    WebServlet ann = type.getAnnotation(WebServlet.class);
    String srvName = ann.name();/*from  w w  w. j  a  v  a2s  .c o  m*/
    if (StringUtils.isBlank(srvName)) {
        LOGGER.error("servlet {}: name could not be blank", type.getName());
        return;
    }
    String[] paths = ann.urlPatterns();
    if (paths == null || paths.length == 0) {
        paths = ann.value();
        if (paths == null || paths.length == 0) {
            LOGGER.error("url patterns missing for servlet {}", type.getName());
            return;
        }
    }
    int losu = ann.loadOnStartup();
    Servlet servlet = null;
    try {
        servlet = (Servlet) type.newInstance();
        polyguice.getComponentContext().inject(servlet);
    } catch (Exception exep) {
        LOGGER.error("error creating servlet {}", type.getName());
        return;
    }
    ServletRegistration.Dynamic dynamic = env.servlets().addServlet(srvName, servlet);
    dynamic.addMapping(paths);
    dynamic.setLoadOnStartup(losu);
    if (ann.initParams() == null) {
        return;
    }
    for (WebInitParam param : ann.initParams()) {
        String name = param.name();
        String value = param.value();
        if (StringUtils.isNoneBlank(name)) {
            dynamic.setInitParameter(name, value);
        }
    }
}

From source file:com.impetus.kundera.metadata.processor.EntityListenersProcessor.java

@Override
public final void process(final Class<?> entityClass, EntityMetadata metadata) {

    // list all external listeners first.
    EntityListeners entityListeners = (EntityListeners) entityClass.getAnnotation(EntityListeners.class);
    if (entityListeners != null) {
        Class<?>[] entityListenerClasses = entityListeners.value();
        if (entityListenerClasses != null) {
            // iterate through all EntityListeners
            for (Class<?> entityListener : entityListenerClasses) {

                // entityListener class must have a no-argument constructor
                try {
                    entityListener.getConstructor();
                } catch (NoSuchMethodException nsme) {
                    throw new PersistenceException("Skipped method(" + entityListener.getName()
                            + ") must have a default no-argument constructor.");
                }/*w w  w.j  a va 2  s .co m*/

                // iterate through all public methods
                for (Method method : entityListener.getDeclaredMethods()) {

                    // find valid jpa annotations for this method
                    List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityListener, method, 1);

                    // add them all to metadata
                    for (Class<?> jpaAnnotation : jpaAnnotations) {
                        CallbackMethod callBackMethod = metadata.new ExternalCallbackMethod(entityListener,
                                method);
                        addCallBackMethod(metadata, jpaAnnotation, callBackMethod);
                    }
                }
            }
        }
    }

    // list all internal listeners now.
    // iterate through all public methods of entityClass
    // since this is already an @Entity class, it will sure have a default
    // no-arg constructor
    for (Method method : entityClass.getDeclaredMethods()) {
        // find valid jpa annotations for this method
        List<Class<?>> jpaAnnotations = getValidJPAAnnotationsFromMethod(entityClass, method, 0);
        // add them all to metadata
        for (Class<?> jpaAnnotation : jpaAnnotations) {
            CallbackMethod callbackMethod = metadata.new InternalCallbackMethod(method);
            addCallBackMethod(metadata, jpaAnnotation, callbackMethod);
        }
    }
}

From source file:net.daum.clix.springframework.data.rest.client.repository.RestRepositories.java

private String getResourcePath(Class<?> repositoryInterface) {
    String path = StringUtils.uncapitalize(repositoryInterface.getSimpleName().replaceAll("Repository", ""));
    RestResource restResource = repositoryInterface.getAnnotation(RestResource.class);
    if (restResource != null && StringUtils.hasText(restResource.path())) {
        path = restResource.path();//from www. j  av  a 2 s  . c  o m
    }
    return path;
}