javax.annotation.processing.RoundEnvironment Java Examples

The following examples show how to use javax.annotation.processing.RoundEnvironment. 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: ApiManager   Author: MoerFinance   File: ApiImplProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    if (CollectionUtils.isEmpty(set)) {
        return false;
    }
    for (TypeElement typeElement : set) {
        Set<? extends Element> annotated = roundEnvironment.getElementsAnnotatedWith(typeElement);
        for (Element apiImplElement : annotated) {
            ApiImpl annotation = apiImplElement.getAnnotation(ApiImpl.class);
            if (annotation == null || !(apiImplElement instanceof TypeElement)) {
                continue;
            }
            ApiContract<ClassName> apiNameContract = getApiClassNameContract((TypeElement) apiImplElement);
            try {
                JavaFile.builder(ApiConstants.PACKAGE_NAME_CONTRACT, buildClass(apiNameContract))
                        .build()
                        .writeTo(filer);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}
 
Example #2
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: Processor.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (round++ == 0) {
        try (Writer out = processingEnv.getFiler()
                                             .createSourceFile("Anno.java")
                                             .openWriter()) {
            String target = processingEnv.getOptions().get("target");
            String code = "import java.lang.annotation.ElementType;\n" +
                          "import java.lang.annotation.Target;\n" +
                          "@Target(ElementType." + target + ")\n" +
                          "@interface Anno { public String value(); }\n";
            out.write(code);
        } catch (IOException exc) {
            throw new IllegalStateException(exc);
        }
    }
    return true;
}
 
Example #3
Source Project: vertx-codetrans   Author: vert-x3   File: ConvertingProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (Element annotatedElt : roundEnv.getElementsAnnotatedWith(CodeTranslate.class)) {
    ExecutableElement methodElt = (ExecutableElement) annotatedElt;
    TypeElement typeElt = (TypeElement) methodElt.getEnclosingElement();
    if (typeElt.getQualifiedName().toString().equals(fqn) && methodElt.getSimpleName().toString().equals(method)) {
      for (Lang lang : langs) {
        Result result;
        try {
          String translation = translator.translate(methodElt, false, lang, RenderMode.SNIPPET);
          result = new Result.Source(translation);
        } catch (Exception e) {
          result = new Result.Failure(e);
        }
        results.put(lang, result);
      }
    }
  }
  return false;
}
 
Example #4
Source Project: karaf-boot   Author: jbonofre   File: ShellProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Set<String> packages = new TreeSet<>();
    for (Element elem : roundEnv.getElementsAnnotatedWith(Service.class)) {
        packages.add(elem.getEnclosingElement().toString());
    }

    if (!packages.isEmpty()) {
        if (!hasRun) {
            hasRun = true;
            // Add the Karaf embedded package
            try (PrintWriter w = appendResource("META-INF/org.apache.karaf.boot.bnd")) {
                w.println("Karaf-Commands: " + String.join(",", packages));
            } catch (Exception e) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "Error writing to META-INF/org.apache.karaf.boot.bnd: " + e.getMessage());
            }
        }
    }

    return true;
}
 
Example #5
Source Project: DDComponentForAndroid   Author: luojilab   File: AutowiredProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    if (CollectionUtils.isNotEmpty(set)) {
        try {
            logger.info(">>> Found autowired field, start... <<<");
            categories(roundEnvironment.getElementsAnnotatedWith(Autowired.class));
            generateHelper();

        } catch (Exception e) {
            logger.error(e);
        }
        return true;
    }

    return false;
}
 
Example #6
Source Project: toothpick   Author: stephanenicolas   File: FactoryProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void createFactoriesForClassesAnnotatedWithInjectConstructor(RoundEnvironment roundEnv) {
  for (Element annotatedElement :
      ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(InjectConstructor.class))) {
    TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
    List<ExecutableElement> constructorElements =
        ElementFilter.constructorsIn(annotatedTypeElement.getEnclosedElements());
    if (constructorElements.size() != 1
        || constructorElements.get(0).getAnnotation(Inject.class) != null) {
      error(
          constructorElements.get(0),
          "Class %s is annotated with @InjectInjectConstructor. Therefore, It must have one unique constructor and it should not be annotated with @Inject.",
          annotatedTypeElement.getQualifiedName());
    }
    processInjectAnnotatedConstructor(
        constructorElements.get(0), mapTypeElementToConstructorInjectionTarget);
  }
}
 
Example #7
Source Project: openjdk-8   Author: bpupadhyaya   File: T6413690.java    License: GNU General Public License v2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnvironment) {
    TypeElement testMe = elements.getTypeElement(TestMe.class.getName());
    Set<? extends Element> supers = roundEnvironment.getElementsAnnotatedWith(testMe);
    try {
        for (Element sup : supers) {
            Writer sub = filer.createSourceFile(sup.getSimpleName() + "_GENERATED").openWriter();
            sub.write(String.format("class %s_GENERATED extends %s {}",
                                    sup.getSimpleName(),
                                    ((TypeElement)sup).getQualifiedName()));
            sub.close();
        }
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    return true;
}
 
Example #8
Source Project: memento   Author: mttkay   File: MementoProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnvironment) {
    Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(Retain.class);
    if (elements.isEmpty()) {
        return true;
    }

    //TODO: verify activity implements onFirstCreate
    verifyFieldsAccessible(elements);

    log("processing " + elements.size() + " fields");

    Element hostActivity = elements.iterator().next().getEnclosingElement();
    TypeElement activityType = findAndroidActivitySuperType((TypeElement) hostActivity);
    if (activityType == null) {
        throw new IllegalStateException("Annotated type does not seem to be an Activity");
    }

    try {
        generateMemento(elements, hostActivity, activityType);
    } catch (IOException e) {
        throw new RuntimeException("Failed writing class file", e);
    }

    return true;
}
 
Example #9
Source Project: nalu   Author: NaluKit   File: ControllerAnnotationScanner.java    License: Apache License 2.0 6 votes vote down vote up
private void handleAcceptParameters(RoundEnvironment roundEnvironment,
                                    Element element,
                                    ControllerModel controllerModel)
    throws ProcessorException {
  TypeElement typeElement = (TypeElement) element;
  List<Element> annotatedElements = this.processorUtils.getMethodFromTypeElementAnnotatedWith(this.processingEnvironment,
                                                                                              typeElement,
                                                                                              AcceptParameter.class);
  // validate
  AcceptParameterAnnotationValidator.builder()
                                    .roundEnvironment(roundEnvironment)
                                    .processingEnvironment(processingEnvironment)
                                    .controllerModel(controllerModel)
                                    .listOfAnnotatedElements(annotatedElements)
                                    .build()
                                    .validate();
  // add to ControllerModel ...
  for (Element annotatedElement : annotatedElements) {
    ExecutableElement executableElement = (ExecutableElement) annotatedElement;
    AcceptParameter annotation = executableElement.getAnnotation(AcceptParameter.class);
    controllerModel.getParameterAcceptors()
                   .add(new ParameterAcceptor(annotation.value(),
                                              executableElement.getSimpleName()
                                                               .toString()));
  }
}
 
Example #10
Source Project: openjdk-jdk9   Author: AdoptOpenJDK   File: LVTHarness.java    License: 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 #11
Source Project: armeria   Author: line   File: DocumentationProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void processAnnotation(TypeElement annotationElement, RoundEnvironment roundEnv) {
    roundEnv.getElementsAnnotatedWith(annotationElement)
            .stream()
            .filter(element -> element.getKind() == ElementKind.METHOD)
            // Element is always ExecutableElement because it is a method.
            .forEachOrdered(element -> {
                try {
                    processMethod((ExecutableElement) element);
                } catch (IOException e) {
                    final StringWriter writer = new StringWriter();
                    e.printStackTrace(new PrintWriter(writer));
                    processingEnv.getMessager().printMessage(
                            Kind.ERROR,
                            "Could not process all elements" + System.lineSeparator() + writer,
                            element);
                }
            });
}
 
Example #12
Source Project: qpid-broker-j   Author: apache   File: ManagedAttributeValueTypeValidator.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment roundEnv)
{
    Elements elementUtils = processingEnv.getElementUtils();
    TypeElement annotationElement = elementUtils.getTypeElement(MANAGED_ATTRIBUTE_VALUE_TYPE_CLASS_NAME);

    for (Element e : roundEnv.getElementsAnnotatedWith(annotationElement))
    {
        boolean isAbstract = isAbstract(annotationElement, e);
        if(!isAbstract)
        {
            checkAnnotationIsOnInterface(annotationElement, e);
        }
        if(!isContent(e))
        {
            checkAllMethodsAreAccessors(e, isAbstract);
        }
    }
    return false;
}
 
Example #13
Source Project: openjdk-8   Author: bpupadhyaya   File: T7018098.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    Context context = ((JavacProcessingEnvironment) processingEnv).getContext();
    FSInfo fsInfo = context.get(FSInfo.class);

    round++;
    if (round == 1) {
        boolean expect = Boolean.valueOf(options.get("expect"));
        checkEqual("cache result", fsInfo.isDirectory(testDir), expect);
        initialFSInfo = fsInfo;
    } else {
        checkEqual("fsInfo", fsInfo, initialFSInfo);
    }

    return true;
}
 
Example #14
Source Project: transport   Author: linkedin   File: TransportProcessor.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  try {
    processImpl(roundEnv);
  } catch (Exception e) {
    // We don't allow exceptions of any kind to propagate to the compiler
    try (StringWriter stringWriter = new StringWriter(); PrintWriter printWriter = new PrintWriter(stringWriter)) {
      e.printStackTrace(printWriter);
      fatalError(stringWriter.toString());
    } catch (IOException ioe) {
      fatalError("Could not close resources " + ioe);
    }
  }
  // Universal processors should return false since other processor can be potentially acting on the same element
  return false;
}
 
Example #15
Source Project: turbine   Author: google   File: ProcessingIntegrationTest.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (first) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.WARNING, "proc warning");
    try {
      JavaFileObject file = processingEnv.getFiler().createSourceFile("Gen.java");
      try (Writer writer = file.openWriter()) {
        writer.write("class Gen {}");
      }
    } catch (IOException e) {
      throw new UncheckedIOException(e);
    }
    first = false;
  }
  if (roundEnv.processingOver()) {
    processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "proc error");
  }
  return false;
}
 
Example #16
Source Project: dekorate   Author: dekorateio   File: JibProcessor.java    License: Apache License 2.0 6 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (roundEnv.processingOver()) {
    getSession().close();
    return true;
  }

  for (TypeElement typeElement : annotations) {
    for (Element mainClass : roundEnv.getElementsAnnotatedWith(typeElement)) {
      JibBuild jib = mainClass.getAnnotation(JibBuild.class);
      if (jib == null) {
        continue;
      }
      process("jib", mainClass, JibBuild.class);
    }
  }
  return false;
}
 
Example #17
Source Project: picocli   Author: remkop   File: AbstractCommandSpecProcessor.java    License: Apache License 2.0 6 votes vote down vote up
private void buildMixin(Element element, RoundEnvironment roundEnv, Context context) {
    debugElement(element, "@Mixin");
    if (element.asType().getKind() != TypeKind.DECLARED) {
        error(element, "@Mixin must have a declared type, not %s", element.asType());
        return;
    }
    TypeElement type = (TypeElement) ((DeclaredType) element.asType()).asElement();
    CommandSpec mixin = buildCommand(type, context, roundEnv);

    logger.fine("Built mixin: " + mixin + " from " + element);
    if (EnumSet.of(ElementKind.FIELD, ElementKind.PARAMETER).contains(element.getKind())) {
        VariableElement variableElement = (VariableElement) element;
        MixinInfo mixinInfo = new MixinInfo(variableElement, mixin);

        CommandSpec mixee = buildCommand(mixinInfo.enclosingElement(), context, roundEnv);
        Set<MixinInfo> mixinInfos = context.mixinInfoMap.get(mixee);
        if (mixinInfos == null) {
            mixinInfos = new HashSet<MixinInfo>(2);
            context.mixinInfoMap.put(mixee, mixinInfos);
        }
        mixinInfos.add(mixinInfo);
        logger.fine("Mixin name=" + mixinInfo.mixinName() + ", target command=" + mixee.userObject());
    }
}
 
Example #18
Source Project: buck   Author: facebook   File: BuckModuleAnnotationProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (roundEnv.processingOver()) {
    return false;
  }

  List<BuckModuleDescriptor> buckModuleDescriptors =
      collectBuckModuleDescriptors(annotations, roundEnv);

  if (buckModuleDescriptors.isEmpty()) {
    return false;
  }

  assertOneBuckModuleDescriptor(buckModuleDescriptors);

  return generateBuckModuleAdapterPlugin(buckModuleDescriptors.get(0));
}
 
Example #19
Source Project: openjdk-8-source   Author: keerath   File: T6468404.java    License: GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (!ran) {
        ran = true;
        ExecutableElement m = getFirstMethodIn("C");
        System.err.println("method: " + m);

        TypeMirror type = (DeclaredType)m.getParameters().get(0).asType();
        System.err.println("parameters[0]: " + type);
        if (!isParameterized(type))
            throw new AssertionError(type);

        type = ((ExecutableType)m.asType()).getParameterTypes().get(0);
        System.err.println("parameterTypes[0]: " + type);
        if (!isParameterized(type))
            throw new AssertionError(type);
        System.err.println();
    }
    return true;
}
 
Example #20
Source Project: openjdk-jdk8u   Author: AdoptOpenJDK   File: BasicAnnoTests.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    TestElementScanner s = new TestElementScanner();
    for (Element e: roundEnv.getRootElements()) {
        s.scan(e);
    }
    return true;
}
 
Example #21
Source Project: DataLoader   Author: JeremyLiao   File: DataLoaderProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    if (!roundEnvironment.processingOver()) {
        processAnnotations(roundEnvironment);
    }
    return true;
}
 
Example #22
Source Project: picocli   Author: remkop   File: AbstractCommandSpecProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void buildOptions(RoundEnvironment roundEnv, Context context) {
    logger.fine("Building options...");
    Set<? extends Element> explicitOptions = roundEnv.getElementsAnnotatedWith(Option.class);
    for (Element element : explicitOptions) {
        buildOption(element, context);
    }
}
 
Example #23
Source Project: XModulable   Author: xpleemoon   File: InjectProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
    if (set != null && !set.isEmpty()) {
        Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(InjectXModule.class);
        if (elements == null || elements.size() <= 0) {
            return true;
        }

        mLogger.info(String.format("解析注解:%s", InjectXModule.class.getSimpleName()));
        try {
            // key:依赖注入变量的目标类全限定名;value:目标类中携带@InjectXModule的Element的map集合
            Map<String, List<Element>> targetInjectElements = new LinkedHashMap<>();
            // 扫描注解InjectXModule
            for (Element injectElement : elements) {
                verify(injectElement);

                String fullClzName = injectElement.getEnclosingElement().toString();
                List<Element> injectElements = targetInjectElements.get(fullClzName);
                if (injectElements == null) {
                    injectElements = new ArrayList<>();
                    targetInjectElements.put(fullClzName, injectElements);
                }
                injectElements.add(injectElement);
            }

            // 生成代码
            generateCode(targetInjectElements);
        } catch (ProcessException e) {
            mLogger.error(e.fillInStackTrace());
        }
        return true;
    }
    return false;
}
 
Example #24
Source Project: kripton   Author: xcesco   File: BindSharedPreferencesSubProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
	model = new PrefsModel();

	parseBindType(roundEnv);

	// Put all @BindSharedPreferences elements in beanElements
	for (Element item : roundEnv.getElementsAnnotatedWith(BindSharedPreferences.class)) {
		AssertKripton.assertTrueOrInvalidKindForAnnotationException(item.getKind() == ElementKind.CLASS, item, BindSharedPreferences.class);

		analyzeSharedPreferences((TypeElement) item);
	}

	return true;
}
 
Example #25
Source Project: picocli   Author: remkop   File: AbstractCommandSpecProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void buildParameters(RoundEnvironment roundEnv, Context context) {
    logger.fine("Building parameters...");
    Set<? extends Element> explicitParameters = roundEnv.getElementsAnnotatedWith(Parameters.class);
    for (Element element : explicitParameters) {
        buildParameter(element, context);
    }
}
 
Example #26
Source Project: RetroFacebook   Author: yongjhih   File: RetroFacebookBuilderProcessor.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  Set<? extends Element> builderTypes =
      roundEnv.getElementsAnnotatedWith(RetroFacebook.Builder.class);
  if (!SuperficialValidation.validateElements(builderTypes)) {
    return false;
  }
  for (Element annotatedType : builderTypes) {
    // Double-check that the annotation is there. Sometimes the compiler gets confused in case of
    // erroneous source code. SuperficialValidation should protect us against this but it doesn't
    // cost anything to check again.
    if (isAnnotationPresent(annotatedType, RetroFacebook.Builder.class)) {
      validate(
          annotatedType,
          "@RetroFacebook.Builder can only be applied to a class or interface inside an"
              + " @RetroFacebook class");
    }
  }

  Set<? extends Element> validateMethods =
      roundEnv.getElementsAnnotatedWith(RetroFacebook.Validate.class);
  if (!SuperficialValidation.validateElements(validateMethods)) {
    return false;
  }
  for (Element annotatedMethod : validateMethods) {
    if (isAnnotationPresent(annotatedMethod, RetroFacebook.Validate.class)) {
      validate(
          annotatedMethod,
          "@RetroFacebook.Validate can only be applied to a method inside an @RetroFacebook class");
    }
  }
  return false;
}
 
Example #27
Source Project: openjdk-jdk8u-backup   Author: AdoptOpenJDK   File: T6350057.java    License: GNU General Public License v2.0 5 votes vote down vote up
public boolean process(Set<? extends TypeElement> annotations,
                       RoundEnvironment roundEnvironment) {
    if (!roundEnvironment.processingOver())
        for(Element element : roundEnvironment.getRootElements())
            element.accept(new LocalVarAllergy(), null);
    return true;
}
 
Example #28
Source Project: immutables   Author: immutables   File: StaticEnvironment.java    License: Apache License 2.0 5 votes vote down vote up
void init(Set<? extends TypeElement> annotations, RoundEnvironment round, ProcessingEnvironment processing) {
  this.components = MutableClassToInstanceMap.create();
  this.processing = processing;
  this.round = round;
  this.annotations = ImmutableSet.copyOf(annotations);
  this.initialized = true;
}
 
Example #29
Source Project: SimpleWeibo   Author: 8tory   File: TypeSimplifierTest.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public final boolean process(
    Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  if (!testsRan) {
    testsRan = true;
    typeUtil = processingEnv.getTypeUtils();
    runTests();
  }
  return false;
}
 
Example #30
Source Project: toothpick   Author: stephanenicolas   File: FactoryProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private void createFactoriesForClassesAnnotatedWith(
    RoundEnvironment roundEnv, TypeElement annotationType) {
  for (Element annotatedElement :
      ElementFilter.typesIn(roundEnv.getElementsAnnotatedWith(annotationType))) {
    TypeElement annotatedTypeElement = (TypeElement) annotatedElement;
    processClassContainingInjectAnnotatedMember(
        annotatedTypeElement, mapTypeElementToConstructorInjectionTarget);
  }
}