List of usage examples for javax.lang.model.element TypeElement asType
@Override TypeMirror asType();
From source file:org.leandreck.endpoints.processor.model.EndpointNodeFactory.java
public EndpointNode createEndpointNode(final TypeElement typeElement) { final TypeScriptEndpoint annotation = typeElement.getAnnotation(TypeScriptEndpoint.class); final String name = defineName(typeElement, annotation); final String url = defineUrl(typeElement); final String template = defineTemplate(annotation); final List<MethodNode> methods = defineMethods(typeElement, (DeclaredType) typeElement.asType()); return new EndpointNode(name, url, template, methods, configuration.getGlobalPrintConfiguration()); }
From source file:org.lambdamatic.mongodb.apt.template.MetadataTemplateContext.java
/** * Full constructor/*from ww w. ja va2 s . com*/ * * @param domainElement the {@link TypeElement} to work on. * @param templateFieldBuildFunction the {@link Function} used to generate a single * {@link TemplateField} from a given relevant {@link VariableElement} in the given * {@link TypeElement}. * @param templateMethodsBuildFunction the {@link Function} used to generate zero or more * {@link TemplateMethods} from a given relevant {@link VariableElement} in the given * {@link TypeElement}. * */ private MetadataTemplateContext(final TypeElement domainElement, final BaseAnnotationProcessor annotationProcessor, final BiFunction<VariableElement, ProcessingEnvironment, TemplateField> templateFieldBuildFunction, final Function<DeclaredType, String> simpleClassNameBuilder, final String templateFileName) { super((DeclaredType) domainElement.asType(), annotationProcessor); this.domainTypeFields = domainElement.getEnclosedElements().stream() .filter(e -> e.getKind() == ElementKind.FIELD) .filter(e -> e.getAnnotation(TransientField.class) == null).map(e -> (VariableElement) e) .collect(Collectors.toList()); this.templateFields = this.domainTypeFields.stream().map(f -> { return templateFieldBuildFunction.apply(f, annotationProcessor.getProcessingEnvironment()); }).collect(Collectors.toList()); this.simpleClassName = simpleClassNameBuilder.apply(this.domainType); this.fullyQualifiedClassName = getPackageName() + '.' + this.simpleClassName; this.templateFileName = templateFileName; this.annotations = Stream.of(domainElement.getAnnotationsByType(EmbeddedDocument.class)) .map(a -> TemplateAnnotation.Builder.type(EmbeddedDocument.class).build()) .collect(Collectors.toList()); }
From source file:de.adorsys.beanval2json.converter.BeanvalConverter.java
/** * @return true if this converter can handle the given TypeElement *//*from w ww .j a v a 2s . c om*/ public boolean accepts(TypeElement typeElement) { if (typeElement == null || getAcceptedTypes() == null) { return false; } for (Class<? extends Annotation> annotation : getAcceptedTypes()) { TypeElement annotationType = ctx.getElementUtils().getTypeElement(annotation.getName()); if (ctx.getTypeUtils().isSameType(typeElement.asType(), annotationType.asType())) { return true; } } return false; }
From source file:org.debux.webmotion.netbeans.hints.ActionRule.java
@Override public void run(RuleContext context, final List<Hint> hints) { WebMotionParserResult parserResult = (WebMotionParserResult) context.parserResult; Source source = parserResult.getSnapshot().getSource(); final Document document = source.getDocument(false); final FileObject fileObject = source.getFileObject(); FileObject fo = Utils.getFO(document); ClassPath bootCp = ClassPath.getClassPath(fo, ClassPath.BOOT); ClassPath compileCp = ClassPath.getClassPath(fo, ClassPath.COMPILE); ClassPath sourcePath = ClassPath.getClassPath(fo, ClassPath.SOURCE); ClasspathInfo info = ClasspathInfo.create(bootCp, compileCp, sourcePath); final JavaSource src = JavaSource.create(info); try {// w w w . j a v a 2 s . co m src.runUserActionTask(new CancellableTask<CompilationController>() { @Override public void cancel() { } @Override public void run(CompilationController cu) throws Exception { String packageBase = Utils.getPackageValue("package.base", null); List<OffsetRange> tokens = LexerUtils.getTokens(document, "FILTER_ACTION"); String packageTarget = Utils.getPackageValue("package.filters", packageBase); String superClass = "org.debux.webmotion.server.WebMotionFilter"; runAction(cu, tokens, packageTarget, superClass); tokens = LexerUtils.getTokens(document, "ERROR_ACTION_JAVA"); packageTarget = Utils.getPackageValue("package.errors", packageBase); superClass = "org.debux.webmotion.server.WebMotionController"; runAction(cu, tokens, packageTarget, superClass); tokens = LexerUtils.getTokens(document, "ACTION_ACTION_IDENTIFIER", "ACTION_ACTION_JAVA_IDENTIFIER", "ACTION_ACTION_JAVA_QUALIFIED_IDENTIFIER", "ACTION_ACTION_JAVA_VARIABLE"); packageTarget = Utils.getPackageValue("package.actions", packageBase); superClass = "org.debux.webmotion.server.WebMotionController"; runAction(cu, tokens, packageTarget, superClass); } protected void runAction(CompilationController cu, List<OffsetRange> tokens, String packageTarget, String superClass) { Elements elements = cu.getElements(); Types types = cu.getTypes(); for (OffsetRange range : tokens) { try { String value = LexerUtils.getText(document, range); String className = StringUtils.substringBeforeLast(value, "."); String methodName = StringUtils.substringAfterLast(value, "."); if (Utils.isNotVariable(className)) { TypeElement classElement = elements.getTypeElement(packageTarget + className); if (classElement != null) { // Check class TypeElement controllerElement = elements.getTypeElement(superClass); if (controllerElement != null) { TypeMirror controllerType = controllerElement.asType(); Set<Modifier> modifiers = classElement.getModifiers(); ElementKind kind = classElement.getKind(); TypeMirror resolveType = classElement.asType(); if (kind == ElementKind.CLASS) { if (!modifiers.contains(Modifier.PUBLIC)) { hints.add(new Hint(ActionRule.this, "The class is not public", fileObject, range, WebMotionHintsProvider.asList( new PublicModifierClassFix(src, classElement)), 100)); } if (modifiers.contains(Modifier.ABSTRACT)) { hints.add(new Hint(ActionRule.this, "The class is abstract", fileObject, range, WebMotionHintsProvider.asList( new AbstractModifierClassFix(src, classElement)), 100)); } if (!types.isSubtype(resolveType, controllerType)) { hints.add(new Hint(ActionRule.this, "Requires super class " + superClass, fileObject, range, WebMotionHintsProvider.asList( new ExtendsClassFix(src, classElement, superClass)), 100)); } } } // Check method if (Utils.isNotVariable(methodName)) { List<? extends Element> members = elements.getAllMembers(classElement); Element method = null; for (Element member : members) { ElementKind kind = member.getKind(); String name = member.getSimpleName().toString(); if (kind == ElementKind.METHOD && name.equals(methodName)) { method = member; break; } } if (method != null) { Set<Modifier> modifiers = method.getModifiers(); String currentClass = method.getEnclosingElement().getSimpleName() .toString(); if ("Object".equals(currentClass) || "WebMotionController".equals(currentClass) || "WebMotionFilter".equals(currentClass)) { hints.add(new Hint(ActionRule.this, "Invalid method", fileObject, range, WebMotionHintsProvider.NO_FIXES, 100)); } if (!modifiers.contains(Modifier.PUBLIC)) { hints.add( new Hint(ActionRule.this, "The method is not public", fileObject, range, WebMotionHintsProvider .asList(new PublicModifierMethodFix(src, classElement, methodName)), 100)); } if (modifiers.contains(Modifier.STATIC)) { hints.add( new Hint(ActionRule.this, "The method is static", fileObject, range, WebMotionHintsProvider .asList(new StaticModifierMethodFix(src, classElement, methodName)), 100)); } } else { hints.add(new Hint(ActionRule.this, "Invalid method", fileObject, range, WebMotionHintsProvider.asList( new MethodClassFix(src, classElement, methodName)), 100)); } } } else { hints.add(new Hint(ActionRule.this, "Invalid class", fileObject, range, WebMotionHintsProvider.asList( new CreateClassFix(src, packageTarget, superClass, className)), 100)); } } } catch (BadLocationException ex) { Exceptions.printStackTrace(ex); } } } }, false); } catch (IOException ex) { Exceptions.printStackTrace(ex); } }
From source file:com.rgeldmacher.leash.LeashAnnotationProcessor.java
private String addGetRetainedFragmentSnippet(MethodSpec.Builder builder, TypeElement classWithAnnotations, ClassName retainedFragmentType, MethodSpec getRetainedFragmentMethodSpec) { String parameterName;//from www. j ava 2 s.c om if (typeIsFragment(classWithAnnotations)) { parameterName = "fragment"; builder.addParameter(TypeName.get(classWithAnnotations.asType()), parameterName); builder.addStatement("$T activity = null", getActivityClass(classWithAnnotations)) .beginControlFlow("if ($L != null)", parameterName) .addStatement("activity = $L.getActivity()", parameterName).endControlFlow() .addStatement("$T retainedFragment = $N(activity)", retainedFragmentType, getRetainedFragmentMethodSpec); } else { parameterName = "activity"; builder.addParameter(TypeName.get(classWithAnnotations.asType()), parameterName); builder.addStatement("$T retainedFragment = $N($L)", retainedFragmentType, getRetainedFragmentMethodSpec, parameterName); } return parameterName; }
From source file:fr.xebia.extras.selma.codegen.FactoryWrapper.java
private int collectFactoryMethods(TypeElement element, boolean ignoreAbstract) { int factoryMethodCount = 0; final List<ExecutableElement> methods = ElementFilter.methodsIn(element.getEnclosedElements()); for (ExecutableElement method : methods) { MethodWrapper methodWrapper = new MethodWrapper(method, (DeclaredType) element.asType(), context); // We should ignore abstract methods if parsing an abstract mapper class if (ignoreAbstract && methodWrapper.isAbstract()) { continue; }/*from ww w.ja va2s.c o m*/ if (isValidFactoryMethod(methodWrapper)) { pushFactoryMethod(element, methodWrapper, ignoreAbstract); factoryMethodCount++; } } return factoryMethodCount; }
From source file:de.adorsys.beanval2json.converter.BeanvalConverter.java
/** * Searches for all properties which are annotated with given TypeElement and * updates the constraintsMap with the according constraints *//* www.j a v a 2 s. c o m*/ public void addConstraints(TypeElement typeElement, RoundEnvironment roundEnv, Map<String, Constraints> constraintsMap) throws ProcessingException { for (Element element : roundEnv.getElementsAnnotatedWith(typeElement)) { String name = getFqn(element); if (ctx.ignoreProperty(name)) { continue; } for (AnnotationMirror annotationMirror : element.getAnnotationMirrors()) { if (!ctx.getTypeUtils().isSameType(typeElement.asType(), annotationMirror.getAnnotationType())) { continue; } Constraint constraint = convertConstraint(annotationMirror); Constraints constraints = getConstraints(constraintsMap, name); try { String methodName = String.format("%s%s", IDENTIFIER_SETTER, typeElement.getSimpleName()); constraints.getClass().getMethod(methodName, constraint.getClass()).invoke(constraints, constraint); } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException ex) { throw new ProcessingException(String.format("Could not add %s-Constraint from %s: %s", typeElement.getSimpleName(), element.getSimpleName(), ex.getMessage())); } } } }
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 w w w. j ava 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:info.archinnov.achilles.internals.codegen.meta.EntityMetaCodeGen.java
public EntityMetaSignature buildEntityMeta(EntityType entityType, TypeElement elm, GlobalParsingContext globalParsingContext, List<FieldMetaSignature> fieldMetaSignatures) { final TypeName rawClassTypeName = getRawType(TypeName.get(elm.asType())); final Optional<Consistency> consistency = aptUtils.getAnnotationOnClass(elm, Consistency.class); final Optional<TTL> ttl = aptUtils.getAnnotationOnClass(elm, TTL.class); final Optional<Strategy> strategy = aptUtils.getAnnotationOnClass(elm, Strategy.class); final Optional<Table> entityAnnot = aptUtils.getAnnotationOnClass(elm, Table.class); final Optional<TypeName> viewBaseClass = AnnotationTree.findOptionalViewBaseClass(aptUtils, elm); aptUtils.validateFalse(entityAnnot.isPresent() && viewBaseClass.isPresent(), "Cannot have both @Table and @MaterializedView on the class '%s'", rawClassTypeName); if (entityType == EntityType.VIEW) { aptUtils.validateTrue(viewBaseClass.isPresent(), "Missing @MaterializedView annotation on entity class '%s'", rawClassTypeName); }//from w ww. j a va 2s .co m validateIsAConcreteNonFinalClass(aptUtils, elm); validateHasPublicConstructor(aptUtils, rawClassTypeName, elm); validateNoDuplicateNames(aptUtils, rawClassTypeName, fieldMetaSignatures); validateHasPartitionKey(aptUtils, rawClassTypeName, fieldMetaSignatures); final boolean isCounter = BeanValidator.isCounterTable(aptUtils, rawClassTypeName, fieldMetaSignatures); if (entityType == EntityType.TABLE) { validateStaticColumns(aptUtils, rawClassTypeName, fieldMetaSignatures); } else if (entityType == EntityType.VIEW) { validateNoStaticColumnsForView(aptUtils, rawClassTypeName, fieldMetaSignatures); aptUtils.validateFalse(isCounter, "The class '%s' cannot have counter columns because it is a materialized view", rawClassTypeName); } validateComputed(aptUtils, rawClassTypeName, fieldMetaSignatures); validateCqlColumnNotReservedWords(aptUtils, rawClassTypeName, fieldMetaSignatures); validateCorrectKeysOrder(aptUtils, rawClassTypeName, fieldMetaSignatures.stream().filter(x -> x.context.columnType == ColumnType.PARTITION) .map(x -> Tuple2.of(x.context.fieldName, (KeyColumnInfo) x.context.columnInfo)) .collect(toList()), "@PartitionKey"); validateCorrectKeysOrder(aptUtils, rawClassTypeName, fieldMetaSignatures.stream().filter(x -> x.context.columnType == CLUSTERING) .map(x -> Tuple2.of(x.context.fieldName, (KeyColumnInfo) x.context.columnInfo)) .collect(toList()), "@ClusteringColumn"); final TypeName rawBeanType = TypeName.get(aptUtils.erasure(elm)); final String className = elm.getSimpleName() + META_SUFFIX; final TypeName typeName = ClassName.get(ENTITY_META_PACKAGE, className); final TypeSpec.Builder builder = TypeSpec.classBuilder(className) .addJavadoc("Meta class of all entities of type $T<br/>\n", rawBeanType) .addJavadoc("The meta class is responsible for<br/>\n").addJavadoc("<ul>\n") .addJavadoc(" <li>determining runtime consistency levels (read/write,serial)<li/>\n"); if (entityType == EntityType.TABLE) { builder.addJavadoc(" <li>determining runtime insert strategy<li/>\n"); } builder.addJavadoc(" <li>trigger event interceptors (if any)<li/>\n") .addJavadoc(" <li>map a $T back to an instance of $T<li/>\n", ClassName.get(Row.class), rawBeanType) .addJavadoc( " <li>determine runtime keyspace name using static annotations and runtime SchemaNameProvider (if any)<li/>\n") .addJavadoc( " <li>determine runtime table name using static annotations and runtime SchemaNameProvider (if any)<li/>\n") .addJavadoc(" <li>generate schema during bootstrap<li/>\n") .addJavadoc(" <li>validate schema during bootstrap<li/>\n") .addJavadoc( " <li>expose all property meta classes for encoding/decoding purpose on unitary columns<li/>\n") .addJavadoc("<ul/>\n"); builder.addAnnotation(ACHILLES_META_ANNOT).addModifiers(Modifier.PUBLIC, Modifier.FINAL) .addMethod(buildEntityClass(rawClassTypeName)) .addMethod(buildDerivedTableName(elm, globalParsingContext.namingStrategy)) .addMethod(buildFieldNameToCqlColumn(fieldMetaSignatures)) .addMethod(buildGetStaticReadConsistency(consistency)) .addMethod(buildGetStaticNamingStrategy(strategy)) .addMethod(buildPartitionKeys(fieldMetaSignatures, rawBeanType)) .addMethod(buildClusteringColumns(fieldMetaSignatures, rawBeanType)) .addMethod(buildNormalColumns(fieldMetaSignatures, rawBeanType)) .addMethod(buildComputedColumns(fieldMetaSignatures, rawBeanType)); if (entityType == EntityType.TABLE) { builder.superclass(genericType(ABSTRACT_ENTITY_PROPERTY, rawBeanType)) .addMethod(buildIsCounterTable(isCounter)) .addMethod( buildStaticKeyspace(aptUtils.getAnnotationOnClass(elm, Table.class).get().keyspace())) .addMethod(buildStaticTableOrViewName( aptUtils.getAnnotationOnClass(elm, Table.class).get().table())) .addMethod(buildGetStaticWriteConsistency(consistency)) .addMethod(buildGetStaticSerialConsistency(consistency)).addMethod(buildGetStaticTTL(ttl)) .addMethod(buildGetStaticInsertStrategy(strategy)) .addMethod(buildStaticColumns(fieldMetaSignatures, rawBeanType)) .addMethod(buildCounterColumns(fieldMetaSignatures, rawBeanType)); } else if (entityType == EntityType.VIEW) { builder.superclass(genericType(ABSTRACT_VIEW_PROPERTY, rawBeanType)) .addMethod(buildStaticKeyspace( aptUtils.getAnnotationOnClass(elm, MaterializedView.class).get().keyspace())) .addMethod(buildStaticTableOrViewName( aptUtils.getAnnotationOnClass(elm, MaterializedView.class).get().view())) .addMethod(buildGetBaseEntityClass(viewBaseClass.get())); } for (FieldMetaSignature x : fieldMetaSignatures) { builder.addField(x.buildPropertyAsField()); } // Build public static final xxx_AchillesMeta.ColumnsForFunctions COLUMNS = new xxx_AchillesMeta.ColumnsForFunctions(); builder.addType( EntityMetaColumnsForFunctionsCodeGen.createColumnsClassForFunctionParam(fieldMetaSignatures)) .addField(buildColumnsField(className)); return new EntityMetaSignature(entityType, builder.build(), elm.getSimpleName().toString(), typeName, rawBeanType, viewBaseClass, fieldMetaSignatures); }
From source file:com.dspot.declex.action.Actions.java
private void createInformationForMethods(Element typeElement, ActionInfo actionInfo, List<String> methodsHandled) { if (methodsHandled == null) { methodsHandled = new LinkedList<>(); }//from w w w.j a v a2 s . co m for (Element elem : typeElement.getEnclosedElements()) { if (elem.getKind() == ElementKind.METHOD) { if (methodsHandled.contains(elem.toString())) continue; final ExecutableElement element = (ExecutableElement) elem; List<ActionMethodParam> params = new LinkedList<>(); for (VariableElement param : element.getParameters()) { List<Annotation> annotations = new LinkedList<>(); for (Class<? extends Annotation> annotation : ACTION_ANNOTATION) { Annotation containedAnnotation = param.getAnnotation(annotation); if (containedAnnotation != null) { annotations.add(containedAnnotation); } } final AbstractJClass paramType = codeModelHelper.elementTypeToJClass(param); ActionMethodParam actionMethodParam = new ActionMethodParam(param.getSimpleName().toString(), paramType, annotations); params.add(actionMethodParam); } List<Annotation> annotations = new LinkedList<>(); for (Class<? extends Annotation> annotation : ACTION_ANNOTATION) { Annotation containedAnnotation = element.getAnnotation(annotation); if (containedAnnotation != null) { annotations.add(containedAnnotation); } } String javaDoc = env.getProcessingEnvironment().getElementUtils().getDocComment(element); final String clazz = element.getReturnType().toString(); actionInfo.addMethod(element.getSimpleName().toString(), clazz, javaDoc, params, annotations); methodsHandled.add(element.toString()); } } List<? extends TypeMirror> superTypes = env.getProcessingEnvironment().getTypeUtils() .directSupertypes(typeElement.asType()); for (TypeMirror type : superTypes) { TypeElement superElement = env.getProcessingEnvironment().getElementUtils() .getTypeElement(type.toString()); if (superElement == null) continue; if (superElement.getKind().equals(ElementKind.INTERFACE)) continue; if (superElement.asType().toString().equals(Object.class.getCanonicalName())) continue; createInformationForMethods(superElement, actionInfo, methodsHandled); } }