javax.lang.model.element.AnnotationMirror Java Examples

The following examples show how to use javax.lang.model.element.AnnotationMirror. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: netbeans   Author: apache   File: ElementJavadoc.java    License: Apache License 2.0 6 votes vote down vote up
private void appendAnnotation(StringBuilder sb, AnnotationMirror annotationDesc, boolean topLevel) {
    DeclaredType annotationType = annotationDesc.getAnnotationType();
    if (annotationType != null && (!topLevel || isDocumented(annotationType))) {
        appendType(sb, annotationType, false, false, true);
        Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationDesc.getElementValues();
        if (!values.isEmpty()) {
            sb.append('('); //NOI18N
            for (Iterator<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> it = values.entrySet().iterator(); it.hasNext();) {
                Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> value = it.next();
                createLink(sb, value.getKey(), value.getKey().getSimpleName());
                sb.append('='); //NOI18N
                appendAnnotationValue(sb, value.getValue());
                if (it.hasNext())
                    sb.append(","); //NOI18N
            }
            sb.append(')'); //NOI18N
        }
        if (topLevel)
            sb.append("<br>"); //NOI18N
    }
}
 
Example #2
Source Project: netbeans   Author: apache   File: NamedStereotype.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean refresh( TypeElement type ) {
    List<? extends AnnotationMirror> allAnnotationMirrors = 
        getHelper().getCompilationController().getElements().
            getAllAnnotationMirrors(type);
    Map<String, ? extends AnnotationMirror> annotationsByType = 
            getHelper().getAnnotationsByType( allAnnotationMirrors );
    boolean isStereotype = annotationsByType.get( 
            StereotypeChecker.STEREOTYPE) != null ;
    if ( !isStereotype ){
        return false;
    }
    boolean hasNamed = NamedStereotypeObjectProvider.hasNamed(type, 
            getHelper());
    return hasNamed;
}
 
Example #3
Source Project: netbeans   Author: apache   File: BindingsPanel.java    License: Apache License 2.0 6 votes vote down vote up
protected void setStereotypes( WebBeansModel model, Element element )
        throws CdiException
{
    if (getResult() != null) {
        List<AnnotationMirror> stereotypes = getResult().getAllStereotypes(
                element);
        if (stereotypes.isEmpty()) {
            getStereotypesComponent().setText("");
            return;
        }
        StringBuilder text = new StringBuilder();
        boolean isFqn = showFqns();
        for (AnnotationMirror stereotype : stereotypes) {
            appendAnnotationMirror(stereotype, text, isFqn);
        }
        getStereotypesComponent().setText(text.substring(0, text.length() - 2));
    }
}
 
Example #4
Source Project: netbeans   Author: apache   File: AbstractTestGenerator.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean isClassEjb31Bean(WorkingCopy wc, TypeElement srcClass) {
    ClassPath cp = wc.getClasspathInfo().getClassPath(ClasspathInfo.PathKind.COMPILE);
    if (cp == null || cp.findResource("javax/ejb/embeddable/EJBContainer.class") == null) {
        // if EJBContainer class is not available on classpath then it is not EJB 3.1
        return false;
    }
    List<? extends AnnotationMirror> annotations = wc.getElements().getAllAnnotationMirrors(srcClass);
    for (AnnotationMirror am : annotations) {
        String annotation = ((TypeElement)am.getAnnotationType().asElement()).getQualifiedName().toString();
        if (annotation.equals("javax.ejb.Singleton") || // NOI18N
            annotation.equals("javax.ejb.Stateless") || // NOI18N
            annotation.equals("javax.ejb.Stateful")) { // NOI18N
            // class is an EJB
            return true;
        }
    }
    return false;
}
 
Example #5
Source Project: annotation-processing-example   Author: MindorksOpenSource   File: ProcessingUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static Set<TypeElement> getTypeElementsToProcess(Set<? extends Element> elements,
                                                        Set<? extends Element> supportedAnnotations) {
    Set<TypeElement> typeElements = new HashSet<>();
    for (Element element : elements) {
        if (element instanceof TypeElement) {
            boolean found = false;
            for (Element subElement : element.getEnclosedElements()) {
                for (AnnotationMirror mirror : subElement.getAnnotationMirrors()) {
                    for (Element annotation : supportedAnnotations) {
                        if (mirror.getAnnotationType().asElement().equals(annotation)) {
                            typeElements.add((TypeElement) element);
                            found = true;
                            break;
                        }
                    }
                    if (found) break;
                }
                if (found) break;
            }
        }
    }
    return typeElements;
}
 
Example #6
Source Project: qpid-broker-j   Author: apache   File: ManagedAttributeValueTypeValidator.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isAbstract(final TypeElement annotationElement, final Element typeElement)
{
    for (AnnotationMirror annotation : typeElement.getAnnotationMirrors())
    {
        if (annotation.getAnnotationType().asElement().equals(annotationElement))
        {

            Map<? extends ExecutableElement, ? extends AnnotationValue> annotationValues =
                    processingEnv.getElementUtils().getElementValuesWithDefaults(annotation);
            for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> element : annotationValues.entrySet())
            {
                if ("isAbstract".contentEquals(element.getKey().getSimpleName()))
                {
                    return element.getValue().getValue().equals(Boolean.TRUE);
                }
            }
            break;
        }
    }
    return false;
}
 
Example #7
Source Project: netbeans   Author: apache   File: AnnotationUtil.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * return AnnotationMirror for first found annotation from annotationFqns
 * @param element
 * @param info
 * @param annotationFqns
 * @return 
 */
public static AnnotationMirror getAnnotationMirror(Element element, 
        CompilationInfo info , String... annotationFqns)
{
    Set<TypeElement> set = new HashSet<TypeElement>();
    Elements els = info.getElements();
    for( String annotation : annotationFqns){
        TypeElement annotationElement = els.getTypeElement(
                annotation);
        if ( annotationElement != null ){
            set.add( annotationElement );
        }
    }
    
    List<? extends AnnotationMirror> annotations = 
        els.getAllAnnotationMirrors( element );
    for (AnnotationMirror annotationMirror : annotations) {
        Element declaredAnnotation = info.getTypes().asElement( 
                annotationMirror.getAnnotationType());
        if ( set.contains( declaredAnnotation ) ){
            return annotationMirror;
        }
    }
    return null;
}
 
Example #8
Source Project: netbeans   Author: apache   File: JSFConfigUtilities.java    License: Apache License 2.0 6 votes vote down vote up
private static boolean containsAnnotatedJsfResource(CompilationController parameter) {
    if (jsfResourcesElementHandles == null) {
        loadJsfResourcesElementsHandles(parameter);
    }

    ClassIndex classIndex = parameter.getClasspathInfo().getClassIndex();
    for (ElementHandle jsfResourceElementHandle : jsfResourcesElementHandles) {
        Set<ElementHandle<TypeElement>> elements = classIndex.getElements(
                jsfResourceElementHandle,
                EnumSet.of(ClassIndex.SearchKind.TYPE_REFERENCES),
                EnumSet.of(ClassIndex.SearchScope.SOURCE));
        for (ElementHandle<TypeElement> handle : elements) {
            TypeElement element = handle.resolve(parameter);
            if (element != null) {
                List<? extends AnnotationMirror> annotationMirrors = element.getAnnotationMirrors();
                for (AnnotationMirror annotationMirror : annotationMirrors) {
                    if (ElementHandle.create(annotationMirror.getAnnotationType().asElement())
                            .equals(jsfResourceElementHandle)) {
                        return true;
                    }
                }
            }
        }
    }
    return false;
}
 
Example #9
Source Project: netbeans   Author: apache   File: AnnotationScannerTest.java    License: Apache License 2.0 6 votes vote down vote up
public void testScanAnnotationsOnFields() throws Exception {
    final AnnotationModelHelper helper = AnnotationModelHelper.create(createClasspathInfoForScanningAnnotations());
    final Set<String> elements = new HashSet<String>();
    
    helper.runJavaSourceTask(new Callable<Void>() {
        public Void call() throws InterruptedException {
            helper.getAnnotationScanner().findAnnotations(
                    "javax.annotation.Resource",
                    EnumSet.of(ElementKind.FIELD),
                    new AnnotationHandler() {
                        public void handleAnnotation(TypeElement typeElement, Element element, AnnotationMirror annotationMirror) {
                            assertEquals("foo.MyClass", typeElement.getQualifiedName().toString());
                            elements.add(element.getSimpleName().toString());
                        }
                    });
            return null;
        }
    });
    assertEquals(1, elements.size());
    assertTrue(elements.contains("myDS"));
}
 
Example #10
Source Project: FastAdapter   Author: aizuzi   File: GeneratedFieldAndMethod.java    License: MIT License 6 votes vote down vote up
public FieldSpec buildField() {

    FieldSpec.Builder fieldSpec =
        FieldSpec.builder(TypeName.get(mAnnotatedField.type), mAnnotatedField.name);

    if (mAnnotatedField.annotationMirrors != null) {
      for (AnnotationMirror annotationMirror :
          mAnnotatedField.annotationMirrors) {
        TypeElement annotationElement =
            (TypeElement) annotationMirror.getAnnotationType().asElement();
        if (annotationElement.getQualifiedName().contentEquals(Override.class.getName())) {
          // Don't copy @Override if present, since we will be adding our own @Override in the
          // implementation.
          continue;
        }

        fieldSpec.addAnnotation(AnnotationSpec.get(annotationMirror));
      }
    }

    return fieldSpec.build();
  }
 
Example #11
Source Project: netbeans   Author: apache   File: DecoratorInterceptorLogic.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public InterceptorsResultImpl getInterceptors( Element element ) {
    Collection<InterceptorObject> interceptors = getModel().
        getInterceptorsManager().getObjects();
    Set<TypeElement> result = new HashSet<TypeElement>();
    
    Collection<AnnotationMirror> elementBindings = getInterceptorBindings(element);
    Set<String> elementBindingsFqns = getAnnotationFqns(elementBindings);
    
    for (InterceptorObject interceptor : interceptors) {
        TypeElement typeElement = interceptor.getTypeElement();
        if ( hasInterceptorBindings( typeElement , elementBindingsFqns )){
            result.add(typeElement);
        }
    }
    filterBindingsByMembers(elementBindings, result, TypeElement.class);
    return getInterceptorsResult( element , result );
}
 
Example #12
Source Project: netbeans   Author: apache   File: UseDatabaseGeneratorTest.java    License: Apache License 2.0 6 votes vote down vote up
private static void checkDatasourceField(TypeElement typeElement, String name) {
    List<VariableElement> elements = ElementFilter.fieldsIn(typeElement.getEnclosedElements());
    VariableElement variableElement = elements.get(0);
    assertTrue(variableElement.getSimpleName().contentEquals(name)); // field name
    DeclaredType declaredType = (DeclaredType) variableElement.asType();
    TypeElement returnTypeElement = (TypeElement) declaredType.asElement();
    assertTrue(returnTypeElement.getQualifiedName().contentEquals("javax.sql.DataSource")); // field type
    AnnotationMirror annotationMirror = variableElement.getAnnotationMirrors().get(0);
    DeclaredType annotationDeclaredType = annotationMirror.getAnnotationType();
    TypeElement annotationTypeElement = (TypeElement) annotationDeclaredType.asElement();
    assertTrue(annotationTypeElement.getQualifiedName().contentEquals("javax.annotation.Resource")); // annotation type
    Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry = annotationMirror.getElementValues().entrySet().iterator().next();
    String attributeName = entry.getKey().getSimpleName().toString();
    String attributeValue = (String) entry.getValue().getValue();
    assertEquals("name", attributeName); // attributes
    assertEquals(name, attributeValue);
}
 
Example #13
Source Project: netbeans   Author: apache   File: Utils.java    License: Apache License 2.0 6 votes vote down vote up
private static void populateParam(CompilationController controller, VariableElement paramEl, ParamModel paramModel) {
    paramModel.setParamType(paramEl.asType().toString());
    TypeElement paramAnotationEl = controller.getElements().getTypeElement("javax.jws.WebParam"); //NOI18N
    List<? extends AnnotationMirror> paramAnnotations = paramEl.getAnnotationMirrors();
    for (AnnotationMirror anMirror : paramAnnotations) {
        if (controller.getTypes().isSameType(paramAnotationEl.asType(), anMirror.getAnnotationType())) {
            Map<? extends ExecutableElement, ? extends AnnotationValue> expressions = anMirror.getElementValues();
            for(Entry<? extends ExecutableElement, ? extends AnnotationValue> entry:
                expressions.entrySet()) 
            {
                ExecutableElement ex = entry.getKey();
                AnnotationValue value = entry.getValue();
                if (ex.getSimpleName().contentEquals("name")) { //NOI18N
                    paramModel.name = (String)value.getValue();
                } else if (ex.getSimpleName().contentEquals("partName")) { //NOI18N
                    paramModel.setPartName((String)value.getValue());
                } else if (ex.getSimpleName().contentEquals("targetNamespace")) { //NOI18N
                    paramModel.setTargetNamespace((String)value.getValue());
                } else if (ex.getSimpleName().contentEquals("mode")) { //NOI18N
                    paramModel.setMode(Mode.valueOf(value.getValue().toString()));
                }
            }
        }
    }
}
 
Example #14
Source Project: android-state   Author: evernote   File: StateProcessor.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private boolean useReflection(Element field) {
    for (AnnotationMirror annotationMirror : field.getAnnotationMirrors()) {
        if (STATE_REFLECTION_CLASS_NAME.equals(annotationMirror.getAnnotationType().toString())) {
            return true;
        }
    }
    return false;
}
 
Example #15
Source Project: netbeans   Author: apache   File: WebBeansModelProviderImpl.java    License: Apache License 2.0 5 votes vote down vote up
private boolean isObservesParameter( VariableElement element,
        ExecutableElement method , List<? extends AnnotationMirror> annotations ) 
    throws org.netbeans.modules.web.beans.api.model.InjectionPointDefinitionError
{
    List<? extends VariableElement> parameters = method.getParameters();
    boolean observesFound = false;
    for (VariableElement variableElement : parameters) {
        if (  AnnotationObjectProvider.hasAnnotation(variableElement, 
                OBSERVES_ANNOTATION, getModel().getHelper()))
        {
            if ( observesFound ){
                throw new org.netbeans.modules.web.beans.api.model.
                    InjectionPointDefinitionError(method, 
                        NbBundle.getMessage(WebBeansModelImplementation.class, 
                                "ERR_MultipleObserves" , method.getSimpleName()));
            }
            observesFound = true;
        }
    }
    if ( !observesFound ){
        return false;
    }
    
    String badAnnotation = checkInjectProducers(annotations);
    if ( badAnnotation != null ){
        throw new org.netbeans.modules.web.beans.api.model.
            InjectionPointDefinitionError( method, 
                NbBundle.getMessage(WebBeansModelImplementation.class, 
                        "ERR_ObserverHasInjectOrProduces" , method.getSimpleName(),
                        badAnnotation ));
    }
    return observesFound;
}
 
Example #16
Source Project: spring-init   Author: spring-projects-experimental   File: ElementUtils.java    License: Apache License 2.0 5 votes vote down vote up
public boolean findTypeInAnnotation(AnnotationMirror imported, String string,
		String className) {
	Map<? extends ExecutableElement, ? extends AnnotationValue> values = imported
			.getElementValues();
	for (ExecutableElement element : values.keySet()) {
		if (values.get(element).accept(typeFinder, null)) {
			return true;
		}
	}
	return false;
}
 
Example #17
Source Project: spring-analysis-note   Author: Vip-Augus   File: IndexedStereotypesProvider.java    License: MIT License 5 votes vote down vote up
private Element getCandidateAnnotationElement(Set<Element> seen, AnnotationMirror annotation) {
	Element element = annotation.getAnnotationType().asElement();
	if (seen.contains(element)) {
		return null;
	}
	// We need to visit all indexed annotations.
	if (!isIndexedAnnotation(annotation)) {
		seen.add(element);
	}
	return (!element.toString().startsWith("java.lang") ? element : null);
}
 
Example #18
Source Project: netbeans   Author: apache   File: JaxWsUtils.java    License: Apache License 2.0 5 votes vote down vote up
public  static boolean hasFqn( AnnotationMirror mirror , String fqn){
    Element anElement = mirror.getAnnotationType().asElement();
    if ( anElement instanceof TypeElement ){
        return fqn.contentEquals( ((TypeElement)anElement).getQualifiedName());
    }
    return false;
}
 
Example #19
Source Project: netbeans   Author: apache   File: PersistentObjectManagerTest.java    License: Apache License 2.0 5 votes vote down vote up
private boolean refresh(TypeElement typeElement) {
    AnnotationParser parser = AnnotationParser.create(getHelper());
    parser.expectString("name", AnnotationParser.defaultValue(typeElement.getSimpleName()));
    List<? extends AnnotationMirror> annotations = typeElement.getAnnotationMirrors();
    if (annotations.size() == 0) {
        return false;
    }
    name = parser.parse(annotations.get(0)).get("name", String.class);
    return true;
}
 
Example #20
Source Project: netbeans   Author: apache   File: AnnotationHelpers.java    License: Apache License 2.0 5 votes vote down vote up
public List<T> createInitialObjects() throws InterruptedException {
    final List<T> result = new ArrayList<T>();
    helper.getAnnotationScanner().findAnnotations(annotationName, AnnotationScanner.TYPE_KINDS, new AnnotationHandler() {
        public void handleAnnotation(TypeElement type, Element element, AnnotationMirror annotation) {
            result.add(newItem(helper, type));
        }
    });
    return result;
}
 
Example #21
Source Project: netbeans   Author: apache   File: OptionAnnotationProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Iterable<? extends Completion> getCompletions(Element element, AnnotationMirror annotation, ExecutableElement member, String userText) {
    if (delegate() != null) {
        return delegate().getCompletions(element, annotation, member, userText);
    } else {
        return Collections.emptySet();
    }
}
 
Example #22
Source Project: netbeans   Author: apache   File: MemberBindingFilter.java    License: Apache License 2.0 5 votes vote down vote up
void filter( Set<T> set ) {
    super.filter(set);
    if ( set.size() == 0 ){
        return;
    }
    /*
     * Binding annotation could have members. See example :
     * @BindingType
     * @Retention(RUNTIME)
     * @Target({METHOD, FIELD, PARAMETER, TYPE})
     * public @interface PayBy {
     * PaymentMethod value();
     * @NonBinding String comment();
     * }    
     * One need to check presence of member in binding annotation at 
     * injected point and compare this member with member in annotation
     * for discovered type.
     * Members with  @Nonbinding annotation should be ignored. 
     */
     for (AnnotationMirror annotation : getBindingAnnotations()) {
        Map<? extends ExecutableElement, ? extends AnnotationValue> 
            elementValues = annotation.getElementValues();
        Set<ExecutableElement> bindingMembers = collectBindingMembers(
                annotation , getImplementation() );
        checkMembers(elementValues, bindingMembers, set );
    }
}
 
Example #23
Source Project: spring-init   Author: spring-projects-experimental   File: ElementUtils.java    License: Apache License 2.0 5 votes vote down vote up
public List<TypeElement> getTypesFromAnnotation(AnnotationMirror annotationMirror,
		String fieldname) {
	List<TypeElement> collected = new ArrayList<>();
	if (annotationMirror != null) {
		Map<? extends ExecutableElement, ? extends AnnotationValue> values = annotationMirror
				.getElementValues();
		for (ExecutableElement element : values.keySet()) {
			if (element.getSimpleName().toString().equals(fieldname)) {
				values.get(element).accept(typeCollector, collected);
			}
		}
	}
	return collected;
}
 
Example #24
Source Project: netbeans   Author: apache   File: LayerGenerationException.java    License: Apache License 2.0 5 votes vote down vote up
private static AnnotationMirror findAnnotationMirror(Element element, ProcessingEnvironment processingEnv, Class<? extends Annotation> annotation) {
    for (AnnotationMirror ann : element.getAnnotationMirrors()) {
        if (processingEnv.getElementUtils().getBinaryName((TypeElement) ann.getAnnotationType().asElement()).
                contentEquals(annotation.getName())) {
            return ann;
        }
    }
    return null;
}
 
Example #25
Source Project: java-n-IDE-for-Android   Author: shenghuntianlang   File: JavacProcessingEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Set<TypeElement> scan(Element e, Set<TypeElement> p) {
    for (AnnotationMirror annotationMirror :
             elements.getAllAnnotationMirrors(e) ) {
        Element e2 = annotationMirror.getAnnotationType().asElement();
        p.add((TypeElement) e2);
    }
    return super.scan(e, p);
}
 
Example #26
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: WorkArounds.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean isDeprecated0(Element e) {
    if (!utils.getDeprecatedTrees(e).isEmpty()) {
        return true;
    }
    JavacTypes jctypes = ((DocEnvImpl)configuration.docEnv).toolEnv.typeutils;
    TypeMirror deprecatedType = utils.getDeprecatedType();
    for (AnnotationMirror anno : e.getAnnotationMirrors()) {
        if (jctypes.isSameType(anno.getAnnotationType().asElement().asType(), deprecatedType))
            return true;
    }
    return false;
}
 
Example #27
Source Project: netbeans   Author: apache   File: BasicImpl.java    License: Apache License 2.0 5 votes vote down vote up
public BasicImpl(AnnotationModelHelper helper, AnnotationMirror annotation, String name, Column column, String temporal) {
    this.name = name;
    this.column = column;
    this.temporal = temporal;
    AnnotationParser parser = AnnotationParser.create(helper);
    parser.expectPrimitive("optional", Boolean.class, parser.defaultValue(true));
    parseResult = parser.parse(annotation);
}
 
Example #28
Source Project: j2cl   Author: google   File: JsInteropAnnotationUtils.java    License: Apache License 2.0 5 votes vote down vote up
public static boolean isUnusableByJsSuppressed(AnnotatedConstruct binding) {
  AnnotationMirror suppressWarningsBinding =
      AnnotationUtils.findAnnotationBindingByName(
          binding.getAnnotationMirrors(), SUPPRESS_WARNINGS_ANNOTATION_NAME);
  if (suppressWarningsBinding == null) {
    return false;
  }
  List<?> suppressions =
      AnnotationUtils.getAnnotationParameterArray(suppressWarningsBinding, "value");
  return suppressions.stream().map(Object::toString).anyMatch("\"unusable-by-js\""::equals);
}
 
Example #29
Source Project: spring-init   Author: spring-projects-experimental   File: InitializerSpec.java    License: Apache License 2.0 5 votes vote down vote up
private void addRegistrarInvokers(MethodSpec.Builder builder) {
	addImportInvokers(builder, configurationType);
	List<? extends AnnotationMirror> annotationMirrors = configurationType.getAnnotationMirrors();
	for (AnnotationMirror am : annotationMirrors) {
		// Looking up something like @EnableBar
		TypeElement element = (TypeElement) am.getAnnotationType().asElement();
		addImportInvokers(builder, element);
	}
}
 
Example #30
Source Project: netbeans   Author: apache   File: AbstractServiceProviderProcessor.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param annotation an annotation instance (null permitted)
 * @param name the name of an attribute of that annotation
 * @return the corresponding value if found
 */
private AnnotationValue findAnnotationValue(AnnotationMirror annotation, String name) {
    if (annotation != null) {
        for (Map.Entry<? extends ExecutableElement,? extends AnnotationValue> entry : annotation.getElementValues().entrySet()) {
            if (entry.getKey().getSimpleName().contentEquals(name)) {
                return entry.getValue();
            }
        }
    }
    return null;
}