List of usage examples for javax.lang.model.element TypeElement getAnnotation
@Override
<A extends Annotation> A getAnnotation(Class<A> annotationType);
From source file:org.lambdamatic.mongodb.apt.template.MongoCollectionTemplateContext.java
/** * Full constructor//from www.j a v a2 s . c om * * @param domainType the {@link TypeElement} to work on. * @param annotationProcessor the annotation processor used to generate the * {@link LambdamaticMongoCollection} implementation */ public MongoCollectionTemplateContext(final TypeElement domainType, final BaseAnnotationProcessor annotationProcessor) { super((DeclaredType) domainType.asType(), annotationProcessor); this.collectionName = ElementUtils.getAnnotationValue(domainType.getAnnotation(Document.class), docAnnotation -> docAnnotation.collection(), ""); }
From source file:net.pkhsolutions.ceres.common.builder.processor.BuildableAP.java
private void processType(TypeElement type) { final DataPopulationStrategy strategy = type.getAnnotation(Buildable.class).populationStrategy(); if (strategy.equals(DataPopulationStrategy.USE_CONSTRUCTOR_PARAMETERS)) { createConstructorBuilder(type);/* w w w . ja va2 s . c o m*/ } else { createFieldBuilder(type); } }
From source file:org.mule.module.extension.internal.capability.xml.schema.SchemaDocumenter.java
private ConfigurationDeclaration findMatchingConfiguration(Declaration declaration, final TypeElement configurationElement) { return (ConfigurationDeclaration) CollectionUtils.find(declaration.getConfigurations(), new Predicate() { @Override//from w ww . j a va2s. c o m public boolean evaluate(Object object) { Configuration configuration = configurationElement.getAnnotation(Configuration.class); ConfigurationDeclaration configurationDeclaration = (ConfigurationDeclaration) object; return configurationDeclaration.getName().equals(configuration.name()); } }); }
From source file:net.minecrell.quartz.mappings.processor.MappingsGeneratorProcessor.java
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { if (roundEnv.processingOver()) { return false; }//from w w w .ja v a 2 s . c om List<TypeElement> mappingClasses = new ArrayList<>(); for (Element element : roundEnv.getElementsAnnotatedWith(Mapping.class)) { if (element instanceof TypeElement) { mappingClasses.add((TypeElement) element); } } if (mappingClasses.isEmpty()) { return true; } try { FileObject file = this.processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", "mappings.json"); Map<String, MappedClass> mappings; try (Reader reader = file.openReader(false)) { mappings = Mappings.read(reader); } catch (IOException ignored) { mappings = new HashMap<>(); } ClassMapper classMappings = createMapper(mappingClasses); // We need to remap the descriptors of the fields and methods, use ASM for convenience Remapper unmapper = classMappings.createUnmapper(); for (TypeElement mappingClass : mappingClasses) { String internalName = getInternalName(mappingClass); Mapping annotation = mappingClass.getAnnotation(Mapping.class); String mappedName = annotation.value(); if (mappedName.isEmpty()) { mappedName = internalName; } MappedClass mapping = new MappedClass(mappedName); Accessible accessible = mappingClass.getAnnotation(Accessible.class); if (accessible != null) { mapping.getAccess().put("", parseAccessible(accessible)); } for (Element element : mappingClass.getEnclosedElements()) { accessible = element.getAnnotation(Accessible.class); Constructor constructor = element.getAnnotation(Constructor.class); if (constructor != null) { if (accessible != null) { String constructorDesc = getDescriptor((ExecutableElement) element); mapping.getAccess().put("<init>" + constructorDesc, parseAccessible(accessible)); } continue; } annotation = element.getAnnotation(Mapping.class); if (annotation == null) { continue; } mappedName = annotation.value(); checkArgument(!mappedName.isEmpty(), "Mapping detection is not supported yet"); switch (element.getKind()) { case METHOD: ExecutableElement method = (ExecutableElement) element; String methodName = method.getSimpleName().toString(); String methodDesc = getDescriptor(method); mapping.getMethods().put(mappedName + unmapper.mapMethodDesc(methodDesc), methodName); if (accessible != null) { mapping.getAccess().put(methodName + methodDesc, parseAccessible(accessible)); } break; case FIELD: case ENUM_CONSTANT: VariableElement field = (VariableElement) element; String fieldName = field.getSimpleName().toString(); mapping.getFields().put(mappedName + ':' + unmapper.mapDesc(getDescriptor(field)), fieldName); if (accessible != null) { mapping.getAccess().put(fieldName, parseAccessible(accessible)); } break; default: } } mappings.put(internalName, mapping); } // Generate JSON output file = this.processingEnv.getFiler().createResource(StandardLocation.CLASS_OUTPUT, "", "mappings.json"); try (Writer writer = file.openWriter()) { Mappings.write(writer, mappings); } return true; } catch (IOException e) { this.processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, ExceptionUtils.getStackTrace(e)); throw new RuntimeException("Failed to create mappings.json", e); } }
From source file:com.contentful.vault.compiler.Processor.java
private void parseContentType(TypeElement element, Map<TypeElement, ModelInjection> models) { String id = element.getAnnotation(ContentType.class).value(); if (id.isEmpty()) { error(element, "@%s id may not be empty. (%s)", ContentType.class.getSimpleName(), element.getQualifiedName()); return;/*from ww w . j a va 2 s . c o m*/ } if (!isSubtypeOfType(element.asType(), Resource.class.getName())) { error(element, "Classes annotated with @%s must extend \"" + Resource.class.getName() + "\". (%s)", ContentType.class.getSimpleName(), element.getQualifiedName()); return; } Set<FieldMeta> fields = new LinkedHashSet<>(); Set<String> memberIds = new LinkedHashSet<>(); for (Element enclosedElement : element.getEnclosedElements()) { Field field = enclosedElement.getAnnotation(Field.class); if (field == null) { continue; } String fieldId = field.value(); if (fieldId.isEmpty()) { fieldId = enclosedElement.getSimpleName().toString(); } Set<Modifier> modifiers = enclosedElement.getModifiers(); if (modifiers.contains(Modifier.STATIC)) { error(element, "@%s elements must not be static. (%s.%s)", Field.class.getSimpleName(), element.getQualifiedName(), enclosedElement.getSimpleName()); return; } if (modifiers.contains(Modifier.PRIVATE)) { error(element, "@%s elements must not be private. (%s.%s)", Field.class.getSimpleName(), element.getQualifiedName(), enclosedElement.getSimpleName()); return; } if (!memberIds.add(fieldId)) { error(element, "@%s for the same id (\"%s\") was used multiple times in the same class. (%s)", Field.class.getSimpleName(), fieldId, element.getQualifiedName()); return; } FieldMeta.Builder fieldBuilder = FieldMeta.builder(); if (isList(enclosedElement)) { DeclaredType declaredType = (DeclaredType) enclosedElement.asType(); List<? extends TypeMirror> typeArguments = declaredType.getTypeArguments(); if (typeArguments.size() == 0) { error(element, "Array fields must have a type parameter specified. (%s.%s)", element.getQualifiedName(), enclosedElement.getSimpleName()); return; } TypeMirror arrayType = typeArguments.get(0); if (!isValidListType(arrayType)) { error(element, "Invalid list type \"%s\" specified. (%s.%s)", arrayType.toString(), element.getQualifiedName(), enclosedElement.getSimpleName()); return; } String sqliteType = null; if (String.class.getName().equals(arrayType.toString())) { sqliteType = SqliteUtils.typeForClass(List.class.getName()); } fieldBuilder.setSqliteType(sqliteType).setArrayType(arrayType.toString()); } else { TypeMirror enclosedType = enclosedElement.asType(); String linkType = getLinkType(enclosedType); String sqliteType = null; if (linkType == null) { sqliteType = SqliteUtils.typeForClass(enclosedType.toString()); if (sqliteType == null) { error(element, "@%s specified for unsupported type (\"%s\"). (%s.%s)", Field.class.getSimpleName(), enclosedType.toString(), element.getQualifiedName(), enclosedElement.getSimpleName()); return; } } fieldBuilder.setSqliteType(sqliteType).setLinkType(linkType); } fields.add(fieldBuilder.setId(fieldId).setName(enclosedElement.getSimpleName().toString()) .setType(enclosedElement.asType()).build()); } if (fields.size() == 0) { error(element, "Model must contain at least one @%s element. (%s)", Field.class.getSimpleName(), element.getQualifiedName()); return; } ClassName injectionClassName = getInjectionClassName(element, SUFFIX_MODEL); String tableName = "entry_" + SqliteUtils.hashForId(id); models.put(element, new ModelInjection(id, injectionClassName, element, tableName, fields)); }
From source file:com.contentful.vault.compiler.Processor.java
private void parseSpace(TypeElement element, Map<TypeElement, SpaceInjection> spaces, Map<TypeElement, ModelInjection> models) { Space annotation = element.getAnnotation(Space.class); String id = annotation.value(); if (id.isEmpty()) { error(element, "@%s id may not be empty. (%s)", Space.class.getSimpleName(), element.getQualifiedName()); return;/*from w ww . j av a2 s. c o m*/ } TypeMirror spaceMirror = elementUtils.getTypeElement(Space.class.getName()).asType(); List<ModelInjection> includedModels = new ArrayList<>(); for (AnnotationMirror mirror : element.getAnnotationMirrors()) { if (typeUtils.isSameType(mirror.getAnnotationType(), spaceMirror)) { Set<? extends Map.Entry<? extends ExecutableElement, ? extends AnnotationValue>> items = mirror .getElementValues().entrySet(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> entry : items) { if ("models".equals(entry.getKey().getSimpleName().toString())) { List l = (List) entry.getValue().getValue(); if (l.size() == 0) { error(element, "@%s models must not be empty. (%s)", Space.class.getSimpleName(), element.getQualifiedName()); return; } Set<String> modelIds = new LinkedHashSet<>(); for (Object model : l) { TypeElement e = (TypeElement) ((Type) ((Attribute) model).getValue()).asElement(); ModelInjection modelInjection = models.get(e); if (modelInjection == null) { return; } else { String rid = modelInjection.remoteId; if (!modelIds.add(rid)) { error(element, "@%s includes multiple models with the same id \"%s\". (%s)", Space.class.getSimpleName(), rid, element.getQualifiedName()); return; } includedModels.add(modelInjection); } } } } } } List<String> locales = Arrays.asList(annotation.locales()); Set<String> checked = new HashSet<>(); for (int i = locales.size() - 1; i >= 0; i--) { String code = locales.get(i); if (!checked.add(code)) { error(element, "@%s contains duplicate locale code '%s'. (%s)", Space.class.getSimpleName(), code, element.getQualifiedName()); return; } else if (code.contains(" ") || code.isEmpty()) { error(element, "Invalid locale code '%s', must not be empty and may not contain spaces. (%s)", code, element.getQualifiedName()); return; } } if (checked.size() == 0) { error(element, "@%s at least one locale must be configured. (%s)", Space.class.getSimpleName(), element.getQualifiedName()); return; } ClassName injectionClassName = getInjectionClassName(element, SUFFIX_SPACE); String dbName = "space_" + SqliteUtils.hashForId(id); String copyPath = StringUtils.defaultIfBlank(annotation.copyPath(), null); spaces.put(element, new SpaceInjection(id, injectionClassName, element, includedModels, dbName, annotation.dbVersion(), copyPath, locales)); }
From source file:net.pkhsolutions.ceres.common.builder.processor.BuildableAP.java
private VelocityContext createAndInitializeVelocityContext(TypeElement type) { final VelocityContext vc = new VelocityContext(); vc.put("className", type.getSimpleName().toString()); vc.put("generationDate", new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").format(new Date())); vc.put("packageName", getPackage(type).getQualifiedName().toString()); vc.put("bindable", type.getAnnotation(Buildable.class).bindable()); vc.put("generateGetters", type.getAnnotation(Buildable.class).generateGetters()); return vc;//from ww w . j av a 2s . com }
From source file:com.dspot.declex.action.Actions.java
public boolean isAction(String name) { String actionToCheck = name.substring(0, name.lastIndexOf('.')); if (actionToCheck.isEmpty() || !actionToCheck.endsWith(".Action")) return false; if (actionToCheck.equals(DeclexConstant.ACTION)) return true; TypeElement element = env.getProcessingEnvironment().getElementUtils().getTypeElement(actionToCheck); if (element == null) return false; boolean isAction = element.getAnnotation(com.dspot.declex.annotation.action.Actions.class) != null; if (isAction) { //If it is an Actions container object, add it as an export Action addActions(actionToCheck);/*from w ww . ja v a2 s . c o m*/ } return isAction; }
From source file:org.kie.workbench.common.forms.adf.processors.FormDefinitionGenerator.java
protected void processFormDefinition(TypeElement formElement) throws Exception { final Messager messager = context.getMessager(); messager.printMessage(Diagnostic.Kind.NOTE, "Discovered FormDefintion class [" + formElement.getSimpleName() + "]"); boolean checkInheritance = false; FormDefinition definition = formElement.getAnnotation(FormDefinition.class); String modelClassName = formElement.getQualifiedName().toString(); String builderClassName = FormGenerationUtils.fixClassName(formElement.getQualifiedName().toString()) + FORM_BUILDER_SUFFIX;/*from ww w . j a v a2 s .com*/ FormDefinitionData form = new FormDefinitionData(modelClassName, builderClassName); form.setStartElement(definition.startElement()); form.setI18nBundle(StringUtils.isEmpty(definition.i18n().bundle()) ? formElement.asType().toString() : definition.i18n().bundle()); Column[] columns = definition.layout().value(); List<String> layoutColumns = new ArrayList<>(); if (columns.length == 0) { layoutColumns.add(ColSpan.SPAN_12.getName()); } else { for (Column column : columns) { layoutColumns.add(column.value().getName()); } } form.setLayoutColumns(layoutColumns); checkInheritance = definition.allowInheritance(); Map<String, String> defaultFieldSettings = new HashMap<>(); for (FieldParam param : definition.defaultFieldSettings()) { defaultFieldSettings.put(param.name(), param.value()); } List<FormDefinitionFieldData> formElements = new ArrayList<>(); if (checkInheritance) { TypeElement parent = getParent(formElement); formElements.addAll( extractParentFormFields(parent, definition.policy(), definition.i18n(), defaultFieldSettings)); } formElements.addAll( extracFormFields(formElement, definition.policy(), definition.i18n(), defaultFieldSettings)); FormGenerationUtils.sort(definition.startElement(), formElements); messager.printMessage(Diagnostic.Kind.NOTE, "Discovered " + formElements.size() + " elements for form [" + formElement.getQualifiedName().toString() + "]"); form.getElements().addAll(formElements); context.getForms().add(form); }
From source file:com.predic8.membrane.annot.SpringConfigurationXSDGeneratingAnnotationProcessor.java
@SuppressWarnings("unchecked") private void read() { if (cache != null) return;//from w w w . j a va 2 s .com cache = new HashMap<Class<? extends Annotation>, HashSet<Element>>(); try { FileObject o = processingEnv.getFiler().getResource(StandardLocation.CLASS_OUTPUT, "", "META-INF/membrane.cache"); BufferedReader r = new BufferedReader(o.openReader(false)); try { if (!CACHE_FILE_FORMAT_VERSION.equals(r.readLine())) return; HashSet<Element> currentSet = null; Class<? extends Annotation> annotationClass = null; while (true) { String line = r.readLine(); if (line == null) break; if (line.startsWith(" ")) { line = line.substring(1); TypeElement element = null; try { element = processingEnv.getElementUtils().getTypeElement(line); } catch (RuntimeException e) { // do nothing (Eclipse) } if (element != null) { if (element.getAnnotation(annotationClass) != null) currentSet.add(element); } } else { try { annotationClass = (Class<? extends Annotation>) getClass().getClassLoader() .loadClass(line); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } currentSet = new HashSet<Element>(); cache.put(annotationClass, currentSet); } } } finally { r.close(); } } catch (FileNotFoundException e) { // do nothing (Maven) } catch (IOException e) { // do nothing (Eclipse) } for (Set<Element> e : cache.values()) { String status = "read " + e.size(); log(status); } }