Example usage for java.lang.reflect AnnotatedElement getAnnotation

List of usage examples for java.lang.reflect AnnotatedElement getAnnotation

Introduction

In this page you can find the example usage for java.lang.reflect AnnotatedElement getAnnotation.

Prototype

<T extends Annotation> T getAnnotation(Class<T> annotationClass);

Source Link

Document

Returns this element's annotation for the specified type if such an annotation is present, else null.

Usage

From source file:com.adobe.acs.commons.models.injectors.impl.JsonValueMapValueInjector.java

@Override
public Object getValue(Object adaptable, String name, Type declaredType, AnnotatedElement element,
        DisposalCallbackRegistry callbackRegistry) {

    if (element.isAnnotationPresent(JsonValueMapValue.class)) {
        Resource resource = getResource(adaptable);
        JsonValueMapValue annotation = element.getAnnotation(JsonValueMapValue.class);
        String key = defaultIfEmpty(annotation.name(), name);
        String[] jsonStringArray = resource.getValueMap().get(key, String[].class);
        return parseValue(declaredType, jsonStringArray, key, resource);
    }// w w w. j  a  va  2s  . com

    return null;
}

From source file:org.jessma.ext.spring.SpringInjectFilter.java

private void analysisSpringBeans(ActionExecutor executor, Action action, AnnotatedElement element,
        Map<String, SpringBean> springBeanMap) throws Exception {
    SpringBean springBean = element.getAnnotation(SpringBean.class);

    if (springBean != null)
        GeneralHelper.tryPut(springBeanMap, springBean.value(), springBean);

    SpringBeans springBeans = element.getAnnotation(SpringBeans.class);

    if (springBeans != null) {
        SpringBean[] springBeanArr = springBeans.value();

        if (springBeanArr.length == 0)
            springBeanMap.put(null, null);
        else {/*  w w w  .  j av  a 2s .  c  o  m*/
            for (SpringBean springBean2 : springBeanArr)
                GeneralHelper.tryPut(springBeanMap, springBean2.value(), springBean2);
        }
    }
}

From source file:com.haulmont.cuba.gui.CompanionDependencyInjector.java

private void doInjection(AnnotatedElement element, Class annotationClass) {
    Class<?> type;/*  w w  w.j a  va2 s .c o m*/
    String name = null;
    if (annotationClass == Named.class)
        name = element.getAnnotation(Named.class).value();
    else if (annotationClass == Resource.class)
        name = element.getAnnotation(Resource.class).name();

    if (element instanceof Field) {
        type = ((Field) element).getType();
        if (StringUtils.isEmpty(name))
            name = ((Field) element).getName();
    } else if (element instanceof Method) {
        Class<?>[] types = ((Method) element).getParameterTypes();
        if (types.length != 1)
            throw new IllegalStateException("Can inject to methods with one parameter only");
        type = types[0];
        if (StringUtils.isEmpty(name)) {
            if (((Method) element).getName().startsWith("set"))
                name = StringUtils.uncapitalize(((Method) element).getName().substring(3));
            else
                name = ((Method) element).getName();
        }
    } else
        throw new IllegalStateException("Can inject to fields and setter methods only");

    Object instance = getInjectedInstance(type, name, element);
    if (instance == null) {
        log.warn("Unable to find an instance of type " + type + " named " + name);
    } else {
        assignValue(element, instance);
    }
}

From source file:io.wcm.sling.models.injectors.impl.AemObjectInjector.java

@Override
public InjectAnnotationProcessor createAnnotationProcessor(final Object adaptable,
        final AnnotatedElement element) {
    // check if the element has the expected annotation
    AemObject annotation = element.getAnnotation(AemObject.class);
    if (annotation != null) {
        return new AemObjectAnnotationProcessor(annotation);
    }/*  w  ww .  j  a  va  2 s  .c o  m*/
    return null;
}

From source file:de.escalon.hypermedia.hydra.serialize.JacksonHydraSerializer.java

private <T extends Annotation> T getAnnotation(AnnotatedElement annotated, Class<T> annotationClass) {
    T ret;/*from  w w  w .java  2s  .co  m*/
    if (annotated == null) {
        ret = null;
    } else {
        ret = annotated.getAnnotation(annotationClass);
    }
    return ret;
}

From source file:com.haulmont.cuba.gui.app.core.restore.EntityRestore.java

protected void buildLayout() {
    Object value = entities.getValue();
    if (value != null) {
        MetaClass metaClass = (MetaClass) value;
        MetaProperty deleteTsMetaProperty = metaClass.getProperty("deleteTs");
        if (deleteTsMetaProperty != null) {
            if (entitiesTable != null) {
                tablePanel.remove(entitiesTable);
            }/*from www .  ja v a  2 s.  c  o  m*/
            if (filter != null) {
                tablePanel.remove(filter);
            }

            ComponentsFactory componentsFactory = AppConfig.getFactory();

            entitiesTable = componentsFactory.createComponent(Table.class);
            entitiesTable.setFrame(frame);

            restoreButton = componentsFactory.createComponent(Button.class);
            restoreButton.setId("restore");
            restoreButton.setCaption(getMessage("entityRestore.restore"));

            ButtonsPanel buttonsPanel = componentsFactory.createComponent(ButtonsPanel.class);
            buttonsPanel.add(restoreButton);
            entitiesTable.setButtonsPanel(buttonsPanel);

            RowsCount rowsCount = componentsFactory.createComponent(RowsCount.class);
            entitiesTable.setRowsCount(rowsCount);

            final SimpleDateFormat dateTimeFormat = new SimpleDateFormat(getMessage("dateTimeFormat"));
            Formatter dateTimeFormatter = propertyValue -> {
                if (propertyValue == null) {
                    return StringUtils.EMPTY;
                }

                return dateTimeFormat.format(propertyValue);
            };

            //collect properties in order to add non-system columns first
            LinkedList<Table.Column> nonSystemPropertyColumns = new LinkedList<>();
            LinkedList<Table.Column> systemPropertyColumns = new LinkedList<>();
            List<MetaProperty> metaProperties = new ArrayList<>();
            for (MetaProperty metaProperty : metaClass.getProperties()) {
                //don't show embedded & multiple referred entities
                Range range = metaProperty.getRange();
                if (isEmbedded(metaProperty) || range.getCardinality().isMany()
                        || metadataTools.isSystemLevel(metaProperty)
                        || (range.isClass() && metadataTools.isSystemLevel(range.asClass()))) {
                    continue;
                }

                metaProperties.add(metaProperty);
                Table.Column column = new Table.Column(metaClass.getPropertyPath(metaProperty.getName()));
                if (!metadataTools.isSystem(metaProperty)) {
                    column.setCaption(getPropertyCaption(metaClass, metaProperty));
                    nonSystemPropertyColumns.add(column);
                } else {
                    column.setCaption(metaProperty.getName());
                    systemPropertyColumns.add(column);
                }

                if (range.isDatatype() && range.asDatatype().getJavaClass().equals(Date.class)) {
                    column.setFormatter(dateTimeFormatter);
                }
            }

            for (Table.Column column : nonSystemPropertyColumns) {
                entitiesTable.addColumn(column);
            }

            for (Table.Column column : systemPropertyColumns) {
                entitiesTable.addColumn(column);
            }

            DsContext dsContext = getDsContext();
            if (entitiesDs != null) {
                ((DsContextImplementation) dsContext).unregister(entitiesDs);
            }

            entitiesDs = DsBuilder.create(dsContext).setId("entitiesDs").setMetaClass(metaClass)
                    .setView(buildView(metaClass, metaProperties)).buildGroupDatasource();

            entitiesDs.setQuery("select e from " + metaClass.getName() + " e "
                    + "where e.deleteTs is not null order by e.deleteTs");

            entitiesDs.setSoftDeletion(false);
            entitiesDs.refresh();
            entitiesTable.setDatasource(entitiesDs);

            String filterId = metaClass.getName().replace("$", "") + "GenericFilter";

            filter = componentsFactory.createComponent(Filter.class);
            filter.setId(filterId);
            filter.setFrame(getFrame());

            StringBuilder sb = new StringBuilder("");
            for (MetaProperty property : metaClass.getProperties()) {
                AnnotatedElement annotatedElement = property.getAnnotatedElement();
                if (annotatedElement
                        .getAnnotation(com.haulmont.chile.core.annotations.MetaProperty.class) != null) {
                    sb.append(property.getName()).append("|");
                }
            }
            Element filterElement = Dom4j
                    .readDocument(String.format("<filter id=\"%s\">\n"
                            + "    <properties include=\".*\" exclude=\"\"/>\n" + "</filter>", filterId))
                    .getRootElement();

            String excludedProperties = sb.toString();
            if (StringUtils.isNotEmpty(excludedProperties)) {
                Element properties = filterElement.element("properties");
                properties.attribute("exclude")
                        .setValue(excludedProperties.substring(0, excludedProperties.lastIndexOf("|")));
            }
            filter.setXmlDescriptor(filterElement);
            filter.setUseMaxResults(true);
            filter.setDatasource(entitiesDs);

            entitiesTable.setSizeFull();

            entitiesTable.setMultiSelect(true);
            Action restoreAction = new ItemTrackingAction("restore")
                    .withCaption(getMessage("entityRestore.restore")).withHandler(event -> showRestoreDialog());
            entitiesTable.addAction(restoreAction);
            restoreButton.setAction(restoreAction);

            tablePanel.add(filter);
            tablePanel.add(entitiesTable);
            tablePanel.expand(entitiesTable, "100%", "100%");

            entitiesTable.refresh();

            ((FilterImplementation) filter).loadFiltersAndApplyDefault();
        }
    }
}

From source file:com.planet57.gshell.util.cli2.CliProcessor.java

private void discoverDescriptor(final Object bean, final AnnotatedElement element) {
    assert bean != null;
    assert element != null;

    Option opt = element.getAnnotation(Option.class);
    Argument arg = element.getAnnotation(Argument.class);

    if (opt != null && arg != null) {
        throw new IllegalAnnotationError(
                String.format("Element can only implement @Option or @Argument, not both: %s", element));
    }/*from  w w w  . j av  a2  s  . c o m*/

    if (opt != null) {
        log.trace("Discovered @Option for: {} -> {}", element, opt);

        OptionDescriptor desc = new OptionDescriptor(opt, SetterFactory.create(element, bean));

        // Make sure we have unique names
        for (OptionDescriptor tmp : optionDescriptors) {
            if (desc.getName() != null && desc.getName().equals(tmp.getName())) {
                throw new IllegalAnnotationError(
                        String.format("Duplicate @Option name: %s, on: %s", desc.getName(), element));
            }
            if (desc.getLongName() != null && desc.getLongName().equals(tmp.getLongName())) {
                throw new IllegalAnnotationError(
                        String.format("Duplicate @Option longName: %s, on: %s", desc.getLongName(), element));
            }
        }

        optionDescriptors.add(desc);
    } else if (arg != null) {
        log.trace("Discovered @Argument for: {} -> {}", element, arg);

        ArgumentDescriptor desc = new ArgumentDescriptor(arg, SetterFactory.create(element, bean));
        int index = arg.index();

        // Make sure the argument will fit in the list
        while (index >= argumentDescriptors.size()) {
            argumentDescriptors.add(null);
        }

        if (argumentDescriptors.get(index) != null) {
            throw new IllegalAnnotationError(
                    String.format("Duplicate @Argument index: %s, on: %s", index, element));
        }

        argumentDescriptors.set(index, desc);
    }
}

From source file:com.haulmont.cuba.gui.ControllerDependencyInjector.java

protected void doInjection(AnnotatedElement element, Class annotationClass) {
    Class<?> type;/*from   w ww  . j a  va2  s .c  o m*/
    String name = null;
    if (annotationClass == Named.class)
        name = element.getAnnotation(Named.class).value();
    else if (annotationClass == Resource.class)
        name = element.getAnnotation(Resource.class).name();
    else if (annotationClass == WindowParam.class)
        name = element.getAnnotation(WindowParam.class).name();

    boolean required = true;
    if (element.isAnnotationPresent(WindowParam.class))
        required = element.getAnnotation(WindowParam.class).required();

    if (element instanceof Field) {
        type = ((Field) element).getType();
        if (StringUtils.isEmpty(name))
            name = ((Field) element).getName();
    } else if (element instanceof Method) {
        Class<?>[] types = ((Method) element).getParameterTypes();
        if (types.length != 1)
            throw new IllegalStateException("Can inject to methods with one parameter only");
        type = types[0];
        if (StringUtils.isEmpty(name)) {
            if (((Method) element).getName().startsWith("set"))
                name = StringUtils.uncapitalize(((Method) element).getName().substring(3));
            else
                name = ((Method) element).getName();
        }
    } else {
        throw new IllegalStateException("Can inject to fields and setter methods only");
    }

    Object instance = getInjectedInstance(type, name, annotationClass, element);

    if (instance != null) {
        assignValue(element, instance);
    } else if (required) {
        Class<?> declaringClass = ((Member) element).getDeclaringClass();
        Class<? extends Frame> frameClass = frame.getClass();

        String msg;
        if (frameClass == declaringClass) {
            msg = String.format("CDI - Unable to find an instance of type '%s' named '%s' for instance of '%s'",
                    type, name, frameClass.getCanonicalName());
        } else {
            msg = String.format(
                    "CDI - Unable to find an instance of type '%s' named '%s' declared in '%s' for instance of '%s'",
                    type, name, declaringClass.getCanonicalName(), frameClass.getCanonicalName());
        }

        Logger log = LoggerFactory.getLogger(ControllerDependencyInjector.class);
        log.warn(msg);
    }
}

From source file:org.guicerecipes.spring.support.AutowiredMemberProvider.java

/**
 * Returns a new filter on the given member to respect the use of {@link Qualifier} annotations or annotations annotated with {@link Qualifier}
 *//*  ww w. ja v a 2 s  .  co  m*/
protected Predicate<Binding> createQualifierFilter(Member member, Annotation[] parameterAnnotations) {

    if (member instanceof AnnotatedElement) {
        AnnotatedElement annotatedElement = (AnnotatedElement) member;
        final Qualifier qualifier = annotatedElement.getAnnotation(Qualifier.class);
        if (qualifier != null) {
            final String expectedValue = qualifier.value();
            final boolean notEmptyValue = Strings.isNotEmpty(expectedValue);
            return new Predicate<Binding>() {
                public boolean matches(Binding binding) {
                    String value = annotationName(binding);

                    // we cannot use @Qualified as a binding annotation
                    // so we can't test for just a @Qualified binding with no text
                    // so lets just test for a non-empty string
                    if (notEmptyValue) {
                        return Comparators.equal(expectedValue, value);
                    } else {
                        return Strings.isNotEmpty(value);
                    }
                }

                @Override
                public String toString() {
                    return "@Autowired @Qualifier(" + expectedValue + ")";
                }
            };
        }

        // lets iterate through all of the annotations looking for a qualifier
        Set<Annotation> qualifiedAnnotations = Sets.newHashSet();
        Annotation[] annotations = annotatedElement.getAnnotations();
        for (Annotation annotation : annotations) {
            if (isQualified(annotation)) {
                qualifiedAnnotations.add(annotation);
            }
        }
        if (parameterAnnotations != null) {
            for (Annotation annotation : parameterAnnotations) {
                if (isQualified(annotation)) {
                    qualifiedAnnotations.add(annotation);
                }
            }
        }
        int size = qualifiedAnnotations.size();
        if (size == 1) {
            final Annotation annotation = Iterables.getOnlyElement(qualifiedAnnotations);
            return new Predicate<Binding>() {
                public boolean matches(Binding binding) {
                    Annotation actualAnnotation = binding.getKey().getAnnotation();
                    return (actualAnnotation != null) && actualAnnotation.equals(annotation);
                }

                @Override
                public String toString() {
                    return "@Autowired " + annotation;
                }
            };
        } else if (size > 0) {
            throw new ProvisionException("Too many qualified annotations " + qualifiedAnnotations
                    + " when trying to inject " + member);
        }
    }
    return new Predicate<Binding>() {
        public boolean matches(Binding binding) {
            return true;
        }

        @Override
        public String toString() {
            return "@Autowired";
        }
    };
}

From source file:fr.cls.atoll.motu.processor.wps.StringList.java

public static void testPackageAnnotation() {
    try {//from   ww  w.  j a  v a 2 s  . co m
        Annotation[] annos = DescriptionType.class.getAnnotations();

        System.out.println("All annotations for Meta2:");
        for (Annotation a : annos) {
            System.out.println(a);
        }

    } catch (Exception exc) {
    }

    AnnotatedElement pack = DescriptionType.class.getPackage();
    // getPackage isn't guaranteed to return a package
    if (pack == null) {
        return;
    }

    XmlSchema schema = pack.getAnnotation(XmlSchema.class);
    String namespace = null;
    if (schema != null) {
        namespace = schema.namespace();
    } else {
        namespace = "";
    }
    System.out.println(namespace);
}