Java Code Examples for javax.lang.model.element.Element#getAnnotation()

The following examples show how to use javax.lang.model.element.Element#getAnnotation() . 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 File: ComponentProcessor.java    From appinventor-extensions with Apache License 2.0 6 votes vote down vote up
/**
 * Processes the conditional annotations for a component into a dictionary
 * mapping blocks to those annotations.
 *
 * @param componentInfo Component info in which to store the conditional information.
 * @param element The currently processed Java language element. This should be a method
 *                annotated with either @UsesPermission or @UsesBroadcastReceivers.
 * @param blockName The name of the block as it appears in the sources.
 */
private void processConditionalAnnotations(ComponentInfo componentInfo, Element element,
                                           String blockName) {
  // Conditional UsesPermissions
  UsesPermissions usesPermissions = element.getAnnotation(UsesPermissions.class);
  if (usesPermissions != null) {
    componentInfo.conditionalPermissions.put(blockName, usesPermissions.value());
  }

  UsesBroadcastReceivers broadcastReceiver = element.getAnnotation(UsesBroadcastReceivers.class);
  if (broadcastReceiver != null) {
    try {
      Set<String> receivers = new HashSet<>();
      for (ReceiverElement re : broadcastReceiver.receivers()) {
        updateWithNonEmptyValue(receivers, receiverElementToString(re));
      }
      componentInfo.conditionalBroadcastReceivers.put(blockName, receivers.toArray(new String[0]));
    } catch (Exception e) {
      messager.printMessage(Kind.ERROR, "Unable to process broadcast receiver", element);
    }
  }
}
 
Example 2
Source File: DatabaseConfigurationCollectionStep.java    From sqlitemagic with Apache License 2.0 6 votes vote down vote up
private boolean parseSubmodules(Set<? extends Element> submoduleDatabaseElements) {
  if (submoduleDatabaseElements.size() > 1) {
    environment.error(ERR_SINGLE_SUBMODULE_DB_ALLOWED);
    return false;
  }
  for (Element element : submoduleDatabaseElements) {
    if (environment.getSubmoduleName() == null) {
      final SubmoduleDatabase submoduleDatabase = element.getAnnotation(SubmoduleDatabase.class);
      final String moduleName = submoduleDatabase.value();
      if (Strings.isNullOrEmpty(moduleName)) {
        environment.error(element, "Submodule name cannot be empty or null");
      }
      environment.setSubmoduleName(firstCharToUpperCase(moduleName));
    } else {
      environment.error(element, ERR_SINGLE_SUBMODULE_DB_ALLOWED);
      return false;
    }
  }
  return true;
}
 
Example 3
Source File: AnnotationsProcessor.java    From android-transformer with Apache License 2.0 6 votes vote down vote up
private void processMappedAnnotationElements() {
    for (Element mappedElement : roundEnvironment.getElementsAnnotatedWith(Mapped.class)) {
        if (mappedElement.getKind() == ElementKind.FIELD) {
            Mapped mappedAnnotation = mappedElement.getAnnotation(Mapped.class);

            String fieldName = mappedElement.getSimpleName().toString();
            String fieldType = mappedElement.asType().toString();
            boolean isPublicField = mappedElement.getModifiers().contains(Modifier.PUBLIC);
            String toFieldName = mappedAnnotation.toField();

            MapperFieldInfo mappingFieldInfo = new MapperFieldInfo(fieldName, fieldType, toFieldName, isPublicField);

            ClassInfo classInfo = extractClassInformationFromField(mappedElement);
            getMapper(classInfo)
                        .getFields()
                            .add(mappingFieldInfo);
        }
    }
}
 
Example 4
Source File: APTProcessor.java    From Modularity with Apache License 2.0 6 votes vote down vote up
@Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
        try {
            JavaFileObject f = processingEnv.getFiler().createSourceFile(CLASSNAME);
            Writer w = f.openWriter();
            PrintWriter pw = new PrintWriter(w);
            for (TypeElement te : annotations) {
                pw.println("package " + PACKAGENAME + ";");
                pw.println("\npublic class " + CLASSNAME + " { ");
                for (Element element : roundEnv.getElementsAnnotatedWith(te)) {
                    RList annotation = element.getAnnotation(RList.class);
                    String name = annotation.name();
                    String value = element.toString();
//                    String packageName = element.getEnclosingElement().toString();

                    pw.println("    public static final String " + name + " = \"" + value + "\";");
                }
                pw.println("}");
                pw.flush();
            }
        } catch (IOException x) {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR,
                    x.toString());
        }
        return true;
    }
 
Example 5
Source File: InlineAnnotationReaderImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Gets all the annotations on the given declaration.
 */
private Annotation[] getAllAnnotations(Element decl, Locatable srcPos) {
    List<Annotation> r = new ArrayList<Annotation>();

    for( AnnotationMirror m : decl.getAnnotationMirrors() ) {
        try {
            String fullName = ((TypeElement) m.getAnnotationType().asElement()).getQualifiedName().toString();
            Class<? extends Annotation> type =
                SecureLoader.getClassClassLoader(getClass()).loadClass(fullName).asSubclass(Annotation.class);
            Annotation annotation = decl.getAnnotation(type);
            if(annotation!=null)
                r.add( LocatableAnnotation.create(annotation,srcPos) );
        } catch (ClassNotFoundException e) {
            // just continue
        }
    }

    return r.toArray(new Annotation[r.size()]);
}
 
Example 6
Source File: LVTHarness.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {
    if (roundEnv.processingOver())
        return true;

    TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");

    if (!annotations.contains(aliveRangeAnno)) {
        error("no @AliveRanges annotation found in test class");
    }

    for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
        Annotation annotation = elem.getAnnotation(AliveRanges.class);
        aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
    }
    return true;
}
 
Example 7
Source File: LVTHarness.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations,
    RoundEnvironment roundEnv) {
    if (roundEnv.processingOver())
        return true;

    TypeElement aliveRangeAnno = elements.getTypeElement("AliveRanges");

    if (!annotations.contains(aliveRangeAnno)) {
        error("no @AliveRanges annotation found in test class");
    }

    for (Element elem: roundEnv.getElementsAnnotatedWith(aliveRangeAnno)) {
        Annotation annotation = elem.getAnnotation(AliveRanges.class);
        aliveRangeMap.put(new ElementKey(elem), (AliveRanges)annotation);
    }
    return true;
}
 
Example 8
Source File: HTRouterDispatchProcess.java    From ht-universalrouter-android with MIT License 6 votes vote down vote up
/**
 * 主要的处理注解的类,会拿到所有的注解相关的类
 *
 * @param annotations
 * @param roundEnv
 * @return 处理成功返回true
 */
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    List<HTAnnotatedClass> annotatedClasses = new ArrayList<>();
    //获取所有通过HTRouter注解的项,遍历
    for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(HTRouter.class)) {
        TypeElement annotatedClass = (TypeElement) annotatedElement;
        //检测是否是支持的注解类型,如果不是里面会报错
        if (!isValidClass(annotatedClass)) {
            return true;
        }
        //获取到信息,把注解类的信息加入到列表中
        HTRouter htRouter = annotatedElement.getAnnotation(HTRouter.class);
        annotatedClasses.add(new HTAnnotatedClass(annotatedClass, htRouter.url(), htRouter.entryAnim(), htRouter.exitAnim()));
    }

    //生成各种类
    for (Integer type : CODE_TYPE_MAP.keySet()){
        try {
            generateCode(annotatedClasses, type);
        } catch (IOException e) {
            messager.printMessage(ERROR, CODE_TYPE_MAP.get(type));
        }
    }
    return true;
}
 
Example 9
Source File: EasyMVPProcessor.java    From EasyMVP with Apache License 2.0 6 votes vote down vote up
private void parseConductorController(Element element,
                                      Map<TypeElement, DelegateClassGenerator> delegateClassMap) {
    if (!SuperficialValidation.validateElement(element)) {
        error("Superficial validation error for %s", element.getSimpleName());
        return;
    }
    if (!Validator.isNotAbstractClass(element)) {
        error("%s is abstract", element.getSimpleName());
        return;
    }
    if (!Validator.isSubType(element, CONDUCTOR_CONTROLLER_CLASS_NAME, processingEnv)) {
        error("%s must extend View", element.getSimpleName());
        return;
    }
    //getEnclosing for class type will returns its package/
    TypeElement enclosingElement = (TypeElement) element;
    DelegateClassGenerator delegateClassGenerator =
            getDelegate(enclosingElement, delegateClassMap);
    delegateClassGenerator.setViewType(ViewType.CONDUCTOR_CONTROLLER);
    ConductorController annotation = element.getAnnotation(ConductorController.class);
    try {
        annotation.presenter();
    } catch (MirroredTypeException mte) {
        parsePresenter(delegateClassGenerator, mte);
    }
}
 
Example 10
Source File: EntityAnnotationProcessor.java    From droitatedDB with Apache License 2.0 5 votes vote down vote up
private Persistence checkPersistenceAnnotation(final RoundEnvironment roundEnv) {
	Set<? extends Element> persistenceAnnotated = roundEnv.getElementsAnnotatedWith(Persistence.class);

	if (persistenceAnnotated.size() == 0) {
		return null;
	}

	if (persistenceAnnotated.size() > 1) {
		messager.printMessage(Kind.ERROR, "Only one @Persistence activator is allowed within the project", persistenceAnnotated.iterator().next());
		return null;
	}
	Element persistenceClass = persistenceAnnotated.iterator().next();
	return persistenceClass.getAnnotation(Persistence.class);
}
 
Example 11
Source File: BaseModelAttributeInfo.java    From epoxy with Apache License 2.0 5 votes vote down vote up
BaseModelAttributeInfo(Element attribute, Types typeUtils, Elements elements,
    Logger logger, Memoizer memoizer) {
  this.typeUtils = typeUtils;
  this.setFieldName(attribute.getSimpleName().toString());
  setTypeMirror(attribute.asType(), memoizer);
  setJavaDocString(elements.getDocComment(attribute));

  classElement = (TypeElement) attribute.getEnclosingElement();
  setRootClass(classElement.getSimpleName().toString());
  setPackageName(elements.getPackageOf(classElement).getQualifiedName().toString());
  this.setHasSuperSetter(hasSuperMethod(classElement, attribute));
  this.setHasFinalModifier(attribute.getModifiers().contains(FINAL));
  this.setPackagePrivate(isFieldPackagePrivate(attribute));

  EpoxyAttribute annotation = attribute.getAnnotation(EpoxyAttribute.class);

  Set<Option> options = new HashSet<>(Arrays.asList(annotation.value()));
  validateAnnotationOptions(logger, annotation, options);

  //noinspection deprecation
  setUseInHash(annotation.hash() && !options.contains(Option.DoNotHash));
  setIgnoreRequireHashCode(options.contains(Option.IgnoreRequireHashCode));
  setDoNotUseInToString(options.contains(Option.DoNotUseInToString));

  //noinspection deprecation
  setGenerateSetter(annotation.setter() && !options.contains(Option.NoSetter));
  setGenerateGetter(!options.contains(Option.NoGetter));

  setPrivate(attribute.getModifiers().contains(PRIVATE));
  if (isPrivate()) {
    findGetterAndSetterForPrivateField(logger);
  }

  buildAnnotationLists(attribute.getAnnotationMirrors());
}
 
Example 12
Source File: DelegateMethodExtractor.java    From litho with Apache License 2.0 5 votes vote down vote up
private static List<Annotation> getMethodAnnotations(
    Element method, List<Class<? extends Annotation>> permittedMethodAnnotations) {
  List<Annotation> methodAnnotations = new ArrayList<>();
  for (Class<? extends Annotation> possibleDelegateMethodAnnotation :
      permittedMethodAnnotations) {
    final Annotation methodAnnotation = method.getAnnotation(possibleDelegateMethodAnnotation);
    if (methodAnnotation != null) {
      methodAnnotations.add(methodAnnotation);
    }
  }

  return methodAnnotations;
}
 
Example 13
Source File: JavaWritableClass.java    From HighLite with Apache License 2.0 5 votes vote down vote up
Element findForeignKeyReferencedField(final Element enclosed,
                                      final ForeignKey foreignKey) {
    Element fieldRefElement = null;
    Element tableElem = mTypeUtils.asElement(enclosed.asType());
    for (final Element enc : getFields(tableElem)) {
        if (!enc.getSimpleName().toString().equals(foreignKey.fieldReference())) {
            continue;
        }

        final SQLiteColumn field = enc.getAnnotation(SQLiteColumn.class);
        if (field == null || (!field.primaryKey().enabled() && !field.unique())) {
            throw new ProcessingException(enclosed,
                    String.format("Field %s in class %s needs to be declared as primary key or "
                            + "unique with @SQLiteColumn to be referenced in "
                            + "@ForeignKey", enc.toString(), tableElem.toString()));
        }

        fieldRefElement = enc;
        break;
    }

    if (fieldRefElement == null) {
        throw new ProcessingException(enclosed,
                String.format("Field %s in class %s does not exist",
                        foreignKey.fieldReference(), tableElem.toString()));
    }

    return fieldRefElement;
}
 
Example 14
Source File: RelationRule.java    From alchemy with Apache License 2.0 5 votes vote down vote up
private void processOneToOne(Element field, Element relation) {
    if (relation.getAnnotation(Entry.class) == null) {
        throw new ElementException("Related type must be annotated with @Entry", relation);
    }
    final Element enclosingElement = field.getEnclosingElement();
    final TableSpec lTable = mCompileGraph.findTableSpec(enclosingElement);
    final TableSpec rTable = mCompileGraph.findTableSpec(relation);
    final ClassName className = makeClassName(field);
    final RelationSpec relationSpec = new RelationSpec(
            field, className, lTable, rTable, false);
    mCompileGraph.putRelationSpec(enclosingElement, relationSpec);
}
 
Example 15
Source File: OpenUriHandlerProcessor.java    From netbeans with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean handleProcess(
        Set<? extends TypeElement> annotations,
        RoundEnvironment roundEnv) throws LayerGenerationException {

    for (Element e : roundEnv.getElementsAnnotatedWith(
            IntentHandlerRegistration.class)) {
        IntentHandlerRegistration r = e.getAnnotation(
                IntentHandlerRegistration.class);
        registerHandler(e, r);
    }
    return true;
}
 
Example 16
Source File: Barbershop.java    From barber with Apache License 2.0 5 votes vote down vote up
private int resolveDefault(Element element) {
    StyledAttr styledAttr = element.getAnnotation(StyledAttr.class);
    if (styledAttr != null) {
        return styledAttr.defaultValue();
    }

    return -1;
}
 
Example 17
Source File: ReaderTypeSpec.java    From zerocell with Apache License 2.0 5 votes vote down vote up
private Optional<String> checkRowNumberField() {
    for(Element element: typeElement.getEnclosedElements()) {
        if (! element.getKind().isField()) {
            continue;
        }
        RowNumber annotation = element.getAnnotation(RowNumber.class);
        if (! Objects.isNull(annotation)) {
            TypeMirror type;
            try {
                type = element.asType();
            } catch (MirroredTypeException mte) {
                type = mte.getTypeMirror();
            }
            final String fieldType = String.format("%s", type);
            final String fieldName = element.getSimpleName().toString();
            if (fieldType.equals(int.class.getTypeName())     ||
                fieldType.equals(long.class.getTypeName())    ||
                fieldType.equals(Integer.class.getTypeName()) ||
                fieldType.equals(Long.class.getTypeName())
            ) {
                return Optional.of(beanSetterPropertyName(fieldName));
            } else {
                // Must be one of the integer classes or bust!
                throw new IllegalArgumentException(
                        String.format("Invalid type (%s) for @RowNumber field (%s). Only java.lang.Integer and java.lang.Long are allowed", fieldType, fieldName));
            }
        }
    }
    return Optional.empty();
}
 
Example 18
Source File: HTMLViewProcessor.java    From netbeans with Apache License 2.0 4 votes vote down vote up
@Override
    protected boolean handleProcess(Set<? extends TypeElement> set, RoundEnvironment re) throws LayerGenerationException {
        for (Element e : re.getElementsAnnotatedWith(OpenHTMLRegistration.class)) {
            OpenHTMLRegistration reg = e.getAnnotation(OpenHTMLRegistration.class);
            if (reg == null || e.getKind() != ElementKind.METHOD) {
                continue;
            }
            if (!e.getModifiers().contains(Modifier.STATIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be static", e);
            }
            if (!e.getModifiers().contains(Modifier.PUBLIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be public", e);
            }
            if (!((ExecutableElement)e).getParameters().isEmpty()) {
                error("Method annotated by @OpenHTMLRegistration should have no arguments", e);
            }
            if (!e.getEnclosingElement().getModifiers().contains(Modifier.PUBLIC)) {
                error("Method annotated by @OpenHTMLRegistration needs to be public in a public class", e);
            }
            
            ActionID aid = e.getAnnotation(ActionID.class);
            if (aid != null) {
                final LayerBuilder builder = layer(e);
                LayerBuilder.File actionFile = builder.
                        file("Actions/" + aid.category() + "/" + aid.id().replace('.', '-') + ".instance").
                        methodvalue("instanceCreate", "org.netbeans.modules.htmlui.Pages", "openAction");
                String abs = LayerBuilder.absolutizeResource(e, reg.url());
                try {
                    builder.validateResource(abs, e, reg, null, true);
                } catch (LayerGenerationException ex) {
                    if (System.getProperty("netbeans.home") != null) {
                        processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "Cannot find resource " + abs, e);
                    } else {
                        throw ex;
                    }
                }
                actionFile.stringvalue("url", abs);
                if (!reg.iconBase().isEmpty()) {
                    actionFile.stringvalue("iconBase", reg.iconBase());
                }
                actionFile.stringvalue("method", e.getSimpleName().toString());
                actionFile.stringvalue("class", e.getEnclosingElement().asType().toString());
                String[] techIds = reg.techIds();
                for (int i = 0; i < techIds.length; i++) {
                    actionFile.stringvalue("techId." + i, techIds[i]);
                }
//                actionFile.instanceAttribute("component", TopComponent.class, reg, null);
//                if (reg.preferredID().length() > 0) {
//                    actionFile.stringvalue("preferredID", reg.preferredID());
//                }
                actionFile.bundlevalue("displayName", reg.displayName(), reg, "displayName");
                actionFile.write();
            } else {
                error("@OpenHTMLRegistration needs to be accompanied with @ActionID annotation", e);
            }
            
        }
        return true;
    }
 
Example 19
Source File: ParceledElementExtractor.java    From postman with MIT License 4 votes vote down vote up
private boolean hasParceledAnnotation(Element element) {
    return element.getAnnotation(Parceled.class) != null;
}
 
Example 20
Source File: SQLiteOpenHelperClass.java    From HighLite with Apache License 2.0 4 votes vote down vote up
private MethodSpec buildOnUpgradeMethod() {
    final CodeBlock.Builder onUpgradeStatements = CodeBlock.builder(),
            code = CodeBlock.builder();

    int onUpgradeCounter = 0;
    for (final Element enclosed : mElement.getEnclosedElements()) {
        if (enclosed.getAnnotation(OnUpgrade.class) == null) continue;

        if (++onUpgradeCounter > 1) {
            throw new ProcessingException(enclosed,
                    String.format("Only one method per class may be annotated with %s",
                            OnUpgrade.class.getCanonicalName()));
        }

        if (!enclosed.getModifiers().contains(Modifier.STATIC)) {
            throw new ProcessingException(enclosed,
                    String.format("%s annotated methods need to be static",
                            OnUpgrade.class.getCanonicalName()));
        }

        final ExecutableElement executableElement = (ExecutableElement) enclosed;
        if (executableElement.getParameters().size() != 3
                || !SQLITE_DATABASE.equals(
                ClassName.get(executableElement.getParameters().get(0).asType()))
                || !TypeName.INT.equals(
                ClassName.get(executableElement.getParameters().get(1).asType()))
                || !TypeName.INT.equals(
                ClassName.get(executableElement.getParameters().get(2).asType()))) {
            throw new ProcessingException(enclosed,
                    String.format("%s annotated methods needs to have exactly "
                                    + "three parameters, being of type %s, %s and %s "
                                    + "respectively",
                            OnUpgrade.class.getCanonicalName(),
                            SQLITE_DATABASE.toString(),
                            TypeName.INT.toString(),
                            TypeName.INT.toString()));
        }

        onUpgradeStatements.addStatement("$T.$L(database, oldVersion, newVersion)",
                ClassName.get(mElement.asType()), enclosed.getSimpleName());
    }

    for (final Map.Entry<Element, SQLiteTable> tableElementEntry
            : mTableElementMap.entrySet()) {

        code.addStatement("onUpgrade$L(database)", tableElementEntry.getKey().getSimpleName());
    }

    code.add(onUpgradeStatements.build());

    return MethodSpec.methodBuilder("onUpgrade")
            .addModifiers(Modifier.PUBLIC)
            .addAnnotation(AnnotationSpec.builder(Override.class).build())
            .addParameter(SQLITE_DATABASE, "database", Modifier.FINAL)
            .addParameter(TypeName.INT, "oldVersion", Modifier.FINAL)
            .addParameter(TypeName.INT, "newVersion", Modifier.FINAL)
            .addCode(code.build())
            .build();
}