Java Code Examples for javax.annotation.processing.RoundEnvironment.getElementsAnnotatedWith()

The following are Jave code examples for showing how to use getElementsAnnotatedWith() of the javax.annotation.processing.RoundEnvironment class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: EM   File: FragmentAnnotationProcessor.java   View Source Code Vote up 6 votes
private void processRound(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
	loop: for (TypeElement annotation : annotations) {
		for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
			switch (element.getAnnotation(RuntimeExtension.class).value()) {
			case FRAMEWORK:
				entry = "Fragment-Host: system.bundle; extension:=framework";
				break loop;
			case BOOTCLASSPATH:
				entry = "Fragment-Host: system.bundle; extension:=bootclasspath";
				break loop;
			}
		}
	}
	try {
		generateFile();
	} catch (IOException e) {
		messager.printMessage(Kind.ERROR, "IOException while generating file with contracts! " + e.getMessage());
		e.printStackTrace();
	}
}
 
Example 2
Project: Assembler   File: InterceptorCompiler.java   View Source Code Vote up 6 votes
@Override
public boolean process(Set<? extends TypeElement> set,
                       RoundEnvironment roundEnvironment) {

    Set<? extends Element> elements = roundEnvironment.getElementsAnnotatedWith(Interceptor.class);
    if (elements == null || elements.isEmpty()) {
        return false;
    }

    if (moduleName == null || moduleName.length() == 0) {
        logger.error("<-- option_module_name is not set for modules  -->");
        return false;
    }

    Set<Element> verifyElements = new HashSet<>();

    verifyElements(verifyElements, elements);


    generateInterceptorTables(moduleName, verifyElements);

    return true;
}
 
Example 3
Project: cuckoo   File: DelegationProcessor.java   View Source Code Vote up 6 votes
private Map<ExecutableElement, String> getMethodToFieldNameMap(RoundEnvironment roundEnvironment) {
    final Map<ExecutableElement, String> methodToFieldNameMap = new HashMap<>();

    for (Element byElement : roundEnvironment.getElementsAnnotatedWith(By.class)) {
        if (byElement.getKind() != ElementKind.FIELD) {
            continue;
        }
        VariableElement byField = (VariableElement) byElement;
        for (Element element : typeUtils.asElement(byField.asType()).getEnclosedElements()) {
            if (element.getKind() != ElementKind.METHOD) {
                continue;
            }
            ExecutableElement method = (ExecutableElement) element;
            methodToFieldNameMap.put(method, byField.getSimpleName().toString());
        }
    }

    return methodToFieldNameMap;
}
 
Example 4
Project: incap   File: M1_NRelatedToOneAP.java   View Source Code Vote up 6 votes
@Override
public boolean incrementalProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
  for (TypeElement annotation : annotations) {
    System.out.println("Processing annotation:" + annotation);
  }

  if (isProcessingDone) {
    return false;
  }

  // generates a class with a constant that contains the name of all classes containing an annotation.
  Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(Annotation1.class);
  Map<String, Set<? extends Element>> mapGeneratedFileNameToOriginatingElements = processElements(annotatedElements);
  generateFiles(incrementalProcessingEnvironment.getFiler(), mapGeneratedFileNameToOriginatingElements);
  isProcessingDone = true;
  return false;
}
 
Example 5
Project: sql-first-mapper   File: SqlFirstAnnotationProcessor.java   View Source Code Vote up 6 votes
/**
 * Prepare global config
 *
 * @param roundEnv annotation processor environment
 */
private Element prepareGlobalConfig(RoundEnvironment roundEnv) {
    Element sqlFirstApcConfigElement = null;

    //TODO read with filer for the case of partial compilation
    Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(SqlFirstApcConfig.class);
    for (Element element : annotatedElements) {
        if (sqlFirstApcConfigElement == null) {
            sqlFirstApcConfigElement = element;
        } else {
            processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, "SqlFirstApcConfig annotation must be declared only once ", element);
        }
    }
    return sqlFirstApcConfigElement;
    
}
 
Example 6
Project: Assembler   File: RouterCompiler.java   View Source Code Vote up 6 votes
/***
 *
 * Annotation Processing
 *
 *
 * Step1: Find All Annotation Class
 * Step2: Check if the Annotation class meets the conditions
 * Step3: Generate Java Code
 *
 * @param set
 * @param roundEnvironment
 * @return
 */
@Override
public boolean process(Set<? extends TypeElement> set,
                       RoundEnvironment roundEnvironment) {
    if (set == null || set.isEmpty()) {
        return false;
    }


    if (moduleName == null || moduleName.length() == 0) {
        logger.error("OPTION ModuleName is not set!!!");
        return false;
    } else {
        //Find All Annotation Class
        Set<? extends Element> rootElements = roundEnvironment.getElementsAnnotatedWith(Route.class);
        if (rootElements == null || rootElements.isEmpty()) {
            logger.error("No Route Annotation class  exist!!!");
            return false;
        }
        String validModuleName = moduleName.replace(".", "_")
                .replace("-", "_");
        return findAnnotationClassWithModuleName(validModuleName, rootElements);
    }
}
 
Example 7
Project: Spyglass   File: MainProcessor.java   View Source Code Vote up 6 votes
private Set<ExecutableElement> findMethodsWithSpyglassAnnotations(final RoundEnvironment roundEnvironment) {
	final Set<ExecutableElement> methods = new HashSet<>();

	for (final Class<? extends Annotation> annoType : SUPPORTED_ANNOTATIONS) {
		for (final Element foundElement : roundEnvironment.getElementsAnnotatedWith(annoType)) {
			if (foundElement.getKind() == ElementKind.METHOD) {
				methods.add((ExecutableElement) foundElement);
			} else if (foundElement.getKind() == ElementKind.PARAMETER) {
				methods.add((ExecutableElement) foundElement.getEnclosingElement());
			} else {
				throw new RuntimeException("A Spyglass annotation was somehow applied to an illegal element type.");
			}
		}
	}

	return methods;
}
 
Example 8
Project: RxAndroidOrm   File: Processor.java   View Source Code Vote up 6 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    writeStaticJavaFiles();

    getMigrators(roundEnv);
    getDatabaseName(roundEnv);

    for (Element element : roundEnv.getElementsAnnotatedWith(Model.class)) {
        models.add(element);
        generateColumnEnums(element);
        generateEntityProxies(element);
        generateCursorHelperFiles(element);
        generateModelDaoFiles(element);
    }
    resolveDependencies();
    writeJavaFiles();
    return true;
}
 
Example 9
Project: limitjson   File: JSONProcessor.java   View Source Code Vote up 6 votes
private void processLimitJSON(RoundEnvironment roundEnv) {
        for (Element element : roundEnv.getElementsAnnotatedWith(LIMITJSON.class)) {
            LJSONTypeElement ljsonElement = LJSONTypeElement.create(elements, element);
            processorHelper.setLimitJSONTypeElements(ljsonElement);
            processorHelper.i("---------------------" + ljsonElement.toString());
//
            TypeElement typeElement = (TypeElement) element;
            Element a = typeElement.getEnclosingElement();
            processorHelper.i("LJSON ++" + a + " " + element.getKind().name());
            List<? extends Element> param = typeElement.getEnclosedElements();
            for (Element p : param) {
                if (p instanceof VariableElement) {
                    processorHelper.i("LJSON ........" + p.getSimpleName() + " " + p.asType().toString());
                }
            }

        }
    }
 
Example 10
Project: incubator-netbeans   File: ServiceTabProcessor.java   View Source Code Vote up 6 votes
@Override
protected boolean handleProcess(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) throws LayerGenerationException {
    if (roundEnv.processingOver()) {
        return false;
    }
    for (Element e : roundEnv.getElementsAnnotatedWith(ServicesTabNodeRegistration.class)) {
        ServicesTabNodeRegistration reg = e.getAnnotation(ServicesTabNodeRegistration.class);
        File f = layer(e).
            instanceFile("UI/Runtime", null, Node.class).
            stringvalue("iconResource", reg.iconResource()).
            stringvalue("name", reg.name()).
            methodvalue("instanceCreate", "org.openide.nodes.NodeOp", "factory").
            bundlevalue("displayName", reg.displayName()).
            instanceAttribute("original", Node.class);
        if (!"".equals(reg.shortDescription())) {
            f.bundlevalue("shortDescription", reg.shortDescription());
        }
        f.position(reg.position());
        f.write();
    }
    return true;
}
 
Example 11
Project: Barricade   File: BarricadeProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
  try {
    HashMap<String, BarricadeResponseSet> configs = new HashMap<>();
    // Iterate over all @Barricade annotated elements
    for (Element annotatedElement : roundEnvironment.getElementsAnnotatedWith(Barricade.class)) {
      Barricade barricade = annotatedElement.getAnnotation(Barricade.class);
      messager.printMessage(NOTE, "[Barricade] Processing endpoint: " + barricade.endpoint());

      List<BarricadeResponse> responses = new ArrayList<>(barricade.responses().length);
      int defaultIndex = 0;

      for (int i = 0; i < barricade.responses().length; i++) {
        Response option = barricade.responses()[i];
        responses.add(new BarricadeResponse(option));
        if (option.isDefault()) {
          defaultIndex = i;
        }
      }
      configs.put(barricade.endpoint(), new BarricadeResponseSet(responses, defaultIndex));
    }

    // This method is called multiple times, but we want to generate code only once
    if (!configs.isEmpty()) {
      generateCode(configs);
    }
  } catch (Exception e) {
    messager.printMessage(ERROR, "Couldn't process class:" + e.getMessage());
  }

  return true;
}
 
Example 12
Project: allure-java   File: DescriptionsProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(final Set<? extends TypeElement> annotations, final RoundEnvironment env) {
    final Set<? extends Element> elements = env.getElementsAnnotatedWith(Description.class);
    elements.forEach(el -> {
        if (!el.getAnnotation(Description.class).useJavaDoc()) {
            return;
        }
        final String docs = elementUtils.getDocComment(el);
        final List<String> typeParams = ((ExecutableElement) el).getParameters().stream()
                .map(param -> param.asType().toString()).collect(Collectors.toList());
        final String name = el.getSimpleName().toString();

        final String hash = generateMethodSignatureHash(name, typeParams);
        try {
            final FileObject file = filer.createResource(StandardLocation.CLASS_OUTPUT,
                    "allureDescriptions", hash);
            try (Writer writer = file.openWriter()) {
                writer.write(docs);
            }
        } catch (IOException e) {
            messager.printMessage(Diagnostic.Kind.WARNING,
                    "Unable to create resource from docs comment of method " + name + typeParams);
        }
    });

    return true;
}
 
Example 13
Project: dataenum   File: DataEnumProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
  Filer filer = processingEnv.getFiler();
  Messager messager = processingEnv.getMessager();

  for (Element element : roundEnvironment.getElementsAnnotatedWith(DataEnum.class)) {
    try {

      Spec spec = SpecParser.parse(element, processingEnv);
      if (spec == null) {
        continue;
      }

      OutputSpec outputSpec = OutputSpecFactory.create(spec);
      TypeSpec outputTypeSpec = SpecTypeFactory.create(outputSpec);

      JavaFile.Builder javaFileBuilder =
          JavaFile.builder(outputSpec.outputClass().packageName(), outputTypeSpec);
      if (needsCheckNotNull(spec)) {
        javaFileBuilder.addStaticImport(DataenumUtils.class, "checkNotNull");
      }
      if (needsNullSafeEquals(spec)) {
        javaFileBuilder.addStaticImport(DataenumUtils.class, "equal");
      }

      JavaFile javaFile = javaFileBuilder.build();
      javaFile.writeTo(filer);

    } catch (IOException | ParserException e) {
      messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage());
    }
  }

  return false;
}
 
Example 14
Project: drift   File: JavadocProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment round)
{
    for (TypeElement annotation : annotations) {
        for (Element element : round.getElementsAnnotatedWith(annotation)) {
            if (element instanceof TypeElement) {
                log(NOTE, "Extracting Javadoc metadata for " + element);
                extract((TypeElement) element);
            }
        }
    }
    return false;
}
 
Example 15
Project: GitHub   File: MvpCompiler.java   View Source Code Vote up 5 votes
private void checkInjectors(final RoundEnvironment roundEnv, Class<? extends Annotation> clazz, AnnotationRule annotationRule) {
	for (Element annotatedElement : roundEnv.getElementsAnnotatedWith(clazz)) {
		annotationRule.checkAnnotation(annotatedElement);
	}

	String errorStack = annotationRule.getErrorStack();
	if (errorStack != null && errorStack.length() > 0) {
		getMessager().printMessage(Diagnostic.Kind.ERROR, errorStack);
	}
}
 
Example 16
Project: GitHub   File: MvpCompiler.java   View Source Code Vote up 5 votes
private void processInjectors(final RoundEnvironment roundEnv, Class<? extends Annotation> clazz, ElementKind kind, ClassGenerator classGenerator) {
	for (Element annotatedElements : roundEnv.getElementsAnnotatedWith(clazz)) {
		if (annotatedElements.getKind() != kind) {
			getMessager().printMessage(Diagnostic.Kind.ERROR, annotatedElements + " must be " + kind.name() + ", or not mark it as @" + clazz.getSimpleName());
		}

		generateCode(kind, classGenerator, annotatedElements);
	}
}
 
Example 17
Project: incubator-netbeans   File: RandomlyFailsProcessor.java   View Source Code Vote up 5 votes
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
    if (!roundEnv.processingOver()) {
        for (Element e : roundEnv.getElementsAnnotatedWith(RandomlyFails.class)) {
            Element typeEl = e.getKind() == ElementKind.METHOD ? e.getEnclosingElement() : e;
            TypeMirror nbTestCaseType = processingEnv.getElementUtils().
                    getTypeElement(NbTestCase.class.getName()).asType();
            if (!processingEnv.getTypeUtils().isAssignable(typeEl.asType(), nbTestCaseType)) {
                processingEnv.getMessager().printMessage(Kind.ERROR, "@RandomlyFails must be used on NbTestCase subclasses", e);
            }
        }
        return true;
    }
    return false;
}
 
Example 18
Project: RxAndroidOrm   File: Processor.java   View Source Code Vote up 5 votes
private void getMigrators(RoundEnvironment roundEnv) {
    int max = 1;
    for (Element element : roundEnv.getElementsAnnotatedWith(Migration.class)) {
        int v = element.getAnnotation(Migration.class).value();
        if (max < v) {
            max = v;
        }
        migrators.put(v, element);
    }
    version = max;
}
 
Example 19
Project: Dinamo   File: ProcessoreAnnotazioni.java   View Source Code Vote up 5 votes
/**
 * 
 * @param annotations
 * @param roundEnv
 * @return 
 */
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv)
{
    try
    {
        if(roundEnv.getElementsAnnotatedWith(DinamoBootstrap.class).size() <= 1)
        {
            for (Element elem : roundEnv.getElementsAnnotatedWith(DinamoBootstrap.class)) 
            {
                DinamoBootstrap dinamoBootstrap = elem.getAnnotation(DinamoBootstrap.class);
                ConfigHelper.basePath = dinamoBootstrap.basePath();
            }
            Connection connection = establishingConnection();
            GeneraModel(connection);
        }
        else
        {
            throw new Exception("Multiple DinamoBoostrap annotation found.");
        }
    } 
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
    return true;
}
 
Example 20
Project: DUnit   File: DUnitProcessor.java   View Source Code Vote up 4 votes
/**
 * 处理DUnitGroup注解
 */
public MethodSpec processUnitGroupElements(Set<? extends TypeElement> set, RoundEnvironment roundEnvironment) {
	//获取所有被DUnitGroup注解的Element
	Collection<? extends Element> annotatedUnitGroupElements = roundEnvironment.getElementsAnnotatedWith(DUnitGroup.class);

	//查找所有element中类型为Type的Element
	List<TypeElement> originalElementList = ElementFilter.typesIn(annotatedUnitGroupElements);
	//将普通集合变为不可变集合
	List<TypeElement> types = new ImmutableList.Builder<TypeElement>()
			.addAll(originalElementList)
			.build();

	if (types.size() > 0) {
		mErrorReporter.print("process DUnitGroup start...");
		//用于存放所有DunitGroupModel
		ArrayList<DUnitGroupModel> unitGroupModels = new ArrayList<>();

		for (TypeElement type : types) {
			if (type.getKind() != ElementKind.CLASS) {
				mErrorReporter.abortWithError("@" + DUnit.class.getName() + " only applies to classes", type);
			}

			DUnitGroup dUnitGroup = type.getAnnotation(DUnitGroup.class);

			DUnitGroupModel unitGroupModel = mUnitModelUtil.createUnitGroupModel(type, dUnitGroup);
			unitGroupModels.add(unitGroupModel);
		}

		//将模型转换为字符串
		Gson gson = new Gson();
		//unitGroupModels
		String unitGroupModelsString = gson.toJson(unitGroupModels);

		//创建initUnitGroupModels
		MethodSpec initMethod_initUnitGroupModels = InitMethodUtil.createMethodSpec_initUnitGroupModels(unitGroupModelsString);

		mErrorReporter.print("process DUnitGroup end.");
		return initMethod_initUnitGroupModels;
	} else {
		mErrorReporter.print("Waring! no DUnitGroup found.");
	}

	return null;
}