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:org.azrul.langkuik.Langkuik.java

public void initLangkuik(final EntityManagerFactory emf, final UI ui,
        final RelationManagerFactory relationManagerFactory, List<Class<?>> customTypeInterfaces) {

    List<Class<?>> rootClasses = new ArrayList<>();
    for (ManagedType<?> entity : emf.getMetamodel().getManagedTypes()) {
        Class<?> clazz = entity.getJavaType();
        if (clazz.getAnnotation(WebEntity.class).isRoot() == true) {
            rootClasses.add(clazz);//from w ww.  ja v  a 2 s  .c  o  m
        }
    }

    //Manage custom type
    if (customTypeInterfaces == null) {
        customTypeInterfaces = new ArrayList<>();
    }
    //add system level custom type
    customTypeInterfaces.add(AttachmentCustomType.class);
    //create DAOs for custom types
    final List<DataAccessObject<?>> customTypeDaos = new ArrayList<>();
    for (Class<?> clazz : customTypeInterfaces) {
        customTypeDaos.add(new HibernateGenericDAO(emf, clazz));
    }

    //Setup page
    VerticalLayout main = new VerticalLayout();
    VerticalLayout content = new VerticalLayout();
    final Navigator navigator = new Navigator(ui, content);
    final HorizontalLayout breadcrumb = new HorizontalLayout();

    MenuBar menubar = new MenuBar();
    menubar.setId("MENUBAR");
    main.addComponent(menubar);
    main.addComponent(breadcrumb);
    main.addComponent(content);

    final Deque<History> history = new ArrayDeque<>();
    final Configuration config = Configuration.getInstance();

    history.push(new History("START", "Start"));
    StartView startView = new StartView(history, breadcrumb);
    navigator.addView("START", startView);
    MenuBar.MenuItem create = menubar.addItem("Create", null);
    MenuBar.MenuItem view = menubar.addItem("View", null);

    final PageParameter pageParameter = new PageParameter(customTypeDaos, emf, relationManagerFactory, history,
            config, breadcrumb);

    for (final Class rootClass : rootClasses) {
        final WebEntity myObject = (WebEntity) rootClass.getAnnotation(WebEntity.class);
        final DataAccessObject<?> dao = new HibernateGenericDAO<>(emf, rootClass);
        create.addItem("New " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                Object object = dao.createNew(true);
                BeanView<Object, ?> createNewView = new BeanView<>(object, null, null, pageParameter);
                String targetView = "CREATE_NEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) createNewView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "Create new " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
        view.addItem("View " + myObject.name(), new MenuBar.Command() {
            @Override
            public void menuSelected(MenuBar.MenuItem selectedItem) {
                PlainTableView<?> seeApplicationView = new PlainTableView<>(rootClass, pageParameter);
                String targetView = "VIEW_APPLICATION_" + UUID.randomUUID().toString();
                navigator.addView(targetView, (View) seeApplicationView);
                history.clear();
                history.push(new History("START", "Start"));
                History his = new History(targetView, "View " + myObject.name());
                history.push(his);
                navigator.navigateTo(targetView);
            }
        });
    }

    menubar.addItem("Logout", null).addItem("Logout", new MenuBar.Command() {
        @Override
        public void menuSelected(MenuBar.MenuItem selectedItem) {
            ConfirmDialog.show(ui, "Please Confirm:", "Are you really sure you want to log out?", "I am",
                    "Not quite", new ConfirmDialog.Listener() {
                        @Override
                        public void onClose(ConfirmDialog dialog) {
                            if (dialog.isConfirmed()) {
                                HttpServletRequest req = (HttpServletRequest) VaadinService.getCurrentRequest();
                                HttpServletResponse resp = (HttpServletResponse) VaadinService
                                        .getCurrentResponse();
                                Authentication auth = SecurityContextHolder.getContext().getAuthentication();
                                SecurityContextLogoutHandler ctxLogOut = new SecurityContextLogoutHandler();
                                ctxLogOut.logout(req, resp, auth);
                            }
                        }
                    });

        }
    });
    navigator.navigateTo("START");
    ui.setContent(main);
}

From source file:pl.bristleback.server.bristle.conf.resolver.action.ActionClassesResolver.java

private ActionClassInformation prepareActionClass(Object actionClass, Class<?> actionClassType,
        String actionClassBeanName) {
    ActionClassInformation actionClassInformation = new ActionClassInformation();

    ActionClass actionClassAnnotation = actionClassType.getAnnotation(ActionClass.class);
    String actionClassName = resolveActionClassName(actionClassType, actionClassAnnotation);
    actionClassInformation.setName(actionClassName);
    actionClassInformation.setSpringBeanName(actionClassBeanName);
    actionClassInformation.setType(actionClassType);
    actionClassInformation.setSingleton(springIntegration.isSingleton(actionClassBeanName));

    if (actionClassInformation.isSingleton()) {
        actionClassInformation.setSingletonActionClassInstance(actionClass);
    }//from  ww w  .  jav a2 s. co m
    return actionClassInformation;
}

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

@Before("(execution(public * com.esofthead.mycollab..service..*.updateWithSession(..)) || (execution(public * com.esofthead.mycollab..service..*.updateSelectiveWithSession(..)))) && args(bean, username)")
public void traceBeforeUpdateActivity(JoinPoint joinPoint, Object bean, String username) {

    Advised advised = (Advised) joinPoint.getThis();
    Class<?> cls = advised.getTargetSource().getTargetClass();

    Auditable auditAnnotation = cls.getAnnotation(Auditable.class);
    if (auditAnnotation != null) {
        try {/*  ww w  . j  a v  a2  s  . c om*/
            int typeid = (Integer) PropertyUtils.getProperty(bean, "id");
            int sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            // store old value to map, wait until the update process
            // successfully then add to log item

            // get old value
            Object service = advised.getTargetSource().getTarget();
            Method findMethod;
            Object oldValue;
            try {
                findMethod = cls.getMethod("findById", int.class, int.class);
            } catch (Exception e) {
                findMethod = cls.getMethod("findByPrimaryKey", Serializable.class, int.class, int.class);
            }
            oldValue = findMethod.invoke(service, typeid, sAccountId);
            String key = bean.toString() + ClassInfoMap.getType(cls) + typeid;

            caches.put(key, oldValue);
        } catch (Exception e) {
            LOG.error("Error when save audit for save action of service " + cls.getName(), e);
        }
    }
}

From source file:com.meltmedia.cadmium.core.config.impl.YamlConfigurationParser.java

/**
 * //from w w  w .  j a  v  a 2 s . c  om
 * @return A new Representer Instance with the tags specified by the {@link configurationClasses} list.
 */
private Constructor getClassTags() {
    Constructor constructor = new YamlLenientConstructor();
    if (configurationClasses != null) {
        for (Class<?> configClass : configurationClasses) {
            CadmiumConfig configAnnotation = configClass.getAnnotation(CadmiumConfig.class);
            if (configAnnotation != null) {
                String key = configAnnotation.value();
                if (StringUtils.isEmptyOrNull(key)) {
                    key = configClass.getCanonicalName();
                }

                if (key != null) {
                    constructor.addTypeDescription(new TypeDescription(configClass, "!" + key));
                    logger.trace("Adding configuration tag {} for class {}", "!" + key, configClass);
                }
            }
        }
    }
    return constructor;
}

From source file:com.google.code.rees.scope.spring.SpringConversationArbitrator.java

@Override
protected String[] getConversationsWithInheritance(Class<?> clazz, String actionSuffix) {
    List<String> conversations = new ArrayList<String>();
    for (Class<?> conversationControllerClass : getConversationControllers(clazz)) {
        if (clazz.isAnnotationPresent(ConversationController.class)) {
            ConversationController controller = conversationControllerClass
                    .getAnnotation(ConversationController.class);
            String[] newConversations = controller.conversations();
            if (controller.value().equals(ConversationController.DEFAULT_VALUE)) {
                if (newConversations.length == 0) {
                    newConversations = new String[] {
                            NamingUtil.getConventionName(conversationControllerClass, actionSuffix) };
                }//w ww  .  ja  v a  2 s  .  com
            } else {
                conversations.add(controller.value());
            }
            conversations.addAll(Arrays.asList(newConversations));
        } else {
            com.google.code.rees.scope.spring.ConversationController controller = conversationControllerClass
                    .getAnnotation(com.google.code.rees.scope.spring.ConversationController.class);
            String[] newConversations = controller.conversations();
            if (controller.value()
                    .equals(com.google.code.rees.scope.spring.ConversationController.DEFAULT_VALUE)) {
                if (newConversations.length == 0) {
                    newConversations = new String[] {
                            NamingUtil.getConventionName(conversationControllerClass, actionSuffix) };
                }
            } else {
                conversations.add(controller.value());
            }
            conversations.addAll(Arrays.asList(newConversations));
        }
    }
    return conversations.toArray(new String[] {});
}

From source file:org.activiti.spring.components.aop.ActivitiStateAnnotationBeanPostProcessor.java

public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
    // first sift through and get all the methods
    // then get all the annotations
    // then build the metadata and register the metadata
    final Class<?> targetClass = AopUtils.getTargetClass(bean);
    final org.activiti.spring.annotations.ActivitiComponent component = targetClass
            .getAnnotation(org.activiti.spring.annotations.ActivitiComponent.class);

    ReflectionUtils.doWithMethods(targetClass, new ReflectionUtils.MethodCallback() {
        @SuppressWarnings("unchecked")
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {

            State state = AnnotationUtils.getAnnotation(method, State.class);

            String processName = component.processKey();

            if (StringUtils.hasText(state.process())) {
                processName = state.process();
            }/*from w  w w. j a  va 2  s  . co m*/

            String stateName = state.state();

            if (!StringUtils.hasText(stateName)) {
                stateName = state.value();
            }

            Assert.notNull(stateName, "You must provide a stateName!");

            Map<Integer, String> vars = new HashMap<Integer, String>();
            Annotation[][] paramAnnotationsArray = method.getParameterAnnotations();

            int ctr = 0;
            int pvMapIndex = -1;
            int procIdIndex = -1;

            for (Annotation[] paramAnnotations : paramAnnotationsArray) {
                ctr += 1;

                for (Annotation pa : paramAnnotations) {
                    if (pa instanceof ProcessVariable) {
                        ProcessVariable pv = (ProcessVariable) pa;
                        String pvName = pv.value();
                        vars.put(ctr, pvName);
                    } else if (pa instanceof ProcessVariables) {
                        pvMapIndex = ctr;
                    } else if (pa instanceof ProcessId) {
                        procIdIndex = ctr;
                    }
                }
            }

            ActivitiStateHandlerRegistration registration = new ActivitiStateHandlerRegistration(vars, method,
                    bean, stateName, beanName, pvMapIndex, procIdIndex, processName);
            registry.registerActivitiStateHandler(registration);
        }
    }, new ReflectionUtils.MethodFilter() {
        public boolean matches(Method method) {
            return null != AnnotationUtils.getAnnotation(method, State.class);
        }
    });

    return bean;
}

From source file:com.impetus.kundera.metadata.MetadataBuilder.java

private void setSchemaAndPU(Class<?> clazz, EntityMetadata metadata) {
    Table table = clazz.getAnnotation(Table.class);
    if (table != null) {
        //            log.debug("In set schema and pu, class is " + clazz.getName());
        // Set Name of persistence object
        metadata.setTableName(!StringUtils.isBlank(table.name()) ? table.name() : clazz.getSimpleName());
        // Add named/native query related application metadata.
        addNamedNativeQueryMetadata(clazz);
        // set schema name and persistence unit name (if provided)
        String schemaStr = table.schema();

        MetadataUtils.setSchemaAndPersistenceUnit(metadata, schemaStr, puProperties);
    }//from  ww  w .j  ava2 s.  com
    if (metadata.getPersistenceUnit() == null) {
        //            log.debug("In set schema and pu, pu is " + persistenceUnit);
        metadata.setPersistenceUnit(persistenceUnit);
    }
}

From source file:com.mycollab.aspect.AuditLogAspect.java

@Before("(execution(public * com.mycollab..service..*.updateWithSession(..)) || (execution(public * com.mycollab..service..*.updateSelectiveWithSession(..)))) && args(bean, username)")
public void traceBeforeUpdateActivity(JoinPoint joinPoint, Object bean, String username) {
    Advised advised = (Advised) joinPoint.getThis();
    Class<?> cls = advised.getTargetSource().getTargetClass();

    Traceable auditAnnotation = cls.getAnnotation(Traceable.class);
    if (auditAnnotation != null) {
        try {//from   w  ww. j ava2  s  . c o m
            Integer typeId = (Integer) PropertyUtils.getProperty(bean, "id");
            Integer sAccountId = (Integer) PropertyUtils.getProperty(bean, "saccountid");
            // store old value to map, wait until the update process
            // successfully then add to log item

            // get old value
            Object service = advised.getTargetSource().getTarget();
            Method findMethod;
            Object oldValue;
            try {
                findMethod = cls.getMethod("findById", Integer.class, Integer.class);
            } catch (Exception e) {
                findMethod = cls.getMethod("findByPrimaryKey", Integer.class, Integer.class);
            }
            oldValue = findMethod.invoke(service, typeId, sAccountId);
            String key = bean.toString() + ClassInfoMap.getType(cls) + typeId;

            cacheService.putValue(AUDIT_TEMP_CACHE, key, oldValue);
        } catch (Exception e) {
            LOG.error("Error when save audit for save action of service " + cls.getName(), e);
        }
    }
}

From source file:org.datamongo.jira.datamongo1064.mapper.EmbeddedObjectTypeInformationMapper.java

/**
 * Scans the mapping base package for classes annotated with {@link Embeddable}.
 * //from  w w  w .j a  v a 2 s.com
 * @see #getMappingBasePackage()
 * @return
 * @throws ClassNotFoundException
 */
protected Map<Class<?>, String> getInitialEntitySet() throws ClassNotFoundException {

    String[] basePackage = this.basePackage;
    Map<Class<?>, String> initialEntitySet = new HashMap<Class<?>, String>();

    if (basePackage != null) {
        for (String packageBase : basePackage) {
            if (StringUtils.hasText(packageBase)) {
                ClassPathScanningCandidateComponentProvider componentProvider = new ClassPathScanningCandidateComponentProvider(
                        false);
                componentProvider.addIncludeFilter(new AnnotationTypeFilter(Embeddable.class));

                for (BeanDefinition candidate : componentProvider.findCandidateComponents(packageBase)) {
                    Class<?> forName = ClassUtils.forName(candidate.getBeanClassName(),
                            AbstractMongoConfiguration.class.getClassLoader());
                    String alias = forName.getAnnotation(TypeAlias.class) != null
                            ? forName.getAnnotation(TypeAlias.class).value()
                            : forName.getName();
                    initialEntitySet.put(forName, alias);
                }
            }
        }
    }

    return initialEntitySet;
}

From source file:com.sixt.service.framework.injection.ConfigurationModule.java

private Object findConfigurationPlugin(Injector injector) {
    Object retval = null;//from  www  .  ja va 2s . c  o  m
    String pluginName = serviceProperties.getProperty("configuration");
    if (StringUtils.isBlank(pluginName)) {
        return null;
    }
    if (configurationPlugins == null) { // only scan if not already set
        configurationPlugins = new FastClasspathScanner().scan()
                .getNamesOfClassesWithAnnotation(ConfigurationPlugin.class);
    }
    boolean found = false;
    for (String plugin : configurationPlugins) {
        try {
            @SuppressWarnings("unchecked")
            Class<? extends ConfigurationPlugin> pluginClass = (Class<? extends ConfigurationPlugin>) Class
                    .forName(plugin);
            ConfigurationPlugin anno = pluginClass.getAnnotation(ConfigurationPlugin.class);
            if (anno != null && pluginName.equals(anno.name())) {
                retval = injector.getInstance(pluginClass);
                found = true;
                break;
            }
        } catch (ClassNotFoundException e) {
            logger.error("ConfigurationPlugin not found", e);
        }
    }
    if (!found) {
        logger.warn("Configuration plugin '{}' was not found in the class path", pluginName);
    }
    return retval;
}