private void createHeader( Set<? extends Element> annotatedElements, String packageName, JavaWriter writer) throws IOException { writer.emitPackage(packageName); Map<String, Element> nonRepeatedImports = new HashMap<>(); for (Element element : annotatedElements) { TypeMirror elementType = element.asType(); if (isSubtypeOfType(elementType, "android.view.View")) { nonRepeatedImports.put(element.asType().toString(), element); } else { processingEnv .getMessager() .printMessage( Diagnostic.Kind.ERROR, String.format( "Variable: %s, is not of a type that subclasses android.view.View. @%s can only be used with Views", element.getSimpleName().toString(), InjectView.class.getSimpleName())); } } for (String importString : nonRepeatedImports.keySet()) { writer.emitImports(importString); } }
private KeySpec getKey(Element element) { if (isDefaultAnnotationElement(element, BindExtra.class.getName(), "value")) { return new KeySpec( null, generateKey(IntentFieldBinding.KEY_PREFIX, element.getSimpleName().toString())); } return new KeySpec(null, element.getAnnotation(BindExtra.class).value()); }
private <A extends Annotation> ActionModel processAction( int genericPosition, Element element, Element outputElement, Class<A> annotationClass) { A annotation = element.getAnnotation(annotationClass); if (annotation != null) { System.out.println("Element: " + element.getSimpleName()); if (elementTools.isMethod(element)) { TypeMirror outputGeneric = ((DeclaredType) outputElement.asType()).getTypeArguments().get(genericPosition); List<? extends VariableElement> parameters = ((ExecutableElement) element).getParameters(); if (parameters.size() == 1 && processingEnv.getTypeUtils().isSameType(parameters.get(0).asType(), outputGeneric)) { ActionModel actionModel = new ActionModel(); actionModel.setMethodName(elementTools.getFieldName(element)); actionModel.setType(element.asType()); if (element.getKind() == ElementKind.METHOD) { actionModel.setType(((ExecutableElement) element).getParameters().get(0).asType()); } System.out.println("It maches!!!" + actionModel); return actionModel; } else { System.out.println("Does not match"); } } } return null; }
private void parseOnChanged( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames, Class annotationClass) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); TypeMirror mirror = element.asType(); if (!(mirror.getKind() == TypeKind.EXECUTABLE)) return; String method = element.toString().trim(); String methodName = method.substring(0, method.indexOf("(")); Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(method); if (m.find()) { String[] methodTypes = m.group(1).split(","); String key = null; if (annotationClass.equals(OnKStringChanged.class)) { KStringBinding binding = new KStringBinding(methodName, methodTypes); key = element.getAnnotation(OnKStringChanged.class).value(); bindingClass.putGeneric(key, binding); } else if (annotationClass.equals(OnKBooleanChanged.class)) { KBooleanBinding binding = new KBooleanBinding(methodName, methodTypes); key = element.getAnnotation(OnKBooleanChanged.class).value(); bindingClass.putGeneric(key, binding); } else { error(element, "unknow annotation class type @%s", annotationClass.getSimpleName()); } } erasedTargetNames.add(enclosingElement.toString()); }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // System.out.println("supported options: "+ // Arrays.toString(getSupportedOptions().toArray())); if (!roundEnv.processingOver()) { for (TypeElement currAnno : annotations) { // System.out.println("Found " + currAnno.getQualifiedName()); if (currAnno.getQualifiedName().contentEquals(GENERATE_POJO_BUILDER_CLASS.getName())) { Set<? extends Element> annotatedElements = roundEnv.getElementsAnnotatedWith(currAnno); // System.out.println("[GenerateBuilder] annotatedElements="+ // Arrays.toString(annotatedElements.toArray())); for (Element elem : annotatedElements) { if (elem.getKind() == ElementKind.CLASS) { TypeElement typeElem = (TypeElement) elem; GeneratePojoBuilder annotation = typeElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS); generatePojoBuilderProcessor.process(typeElem, annotation); } else if (elem.getKind() == ElementKind.METHOD) { ExecutableElement execElem = (ExecutableElement) elem; GeneratePojoBuilder annotation = execElem.getAnnotation(GENERATE_POJO_BUILDER_CLASS); generatePojoBuilderProcessor.process(execElem, annotation); } } } } } return false; }
private static List<? extends TypeMirror> computeReturn( Set<ElementKind> types, CompilationInfo info, TreePath parent, Tree error, int offset) { ReturnTree rt = (ReturnTree) parent.getLeaf(); if (rt.getExpression() == error) { TreePath method = findMethod(parent); if (method == null) { return null; } Element el = info.getTrees().getElement(method); if (el == null || el.getKind() != ElementKind.METHOD) { return null; } types.add(ElementKind.PARAMETER); types.add(ElementKind.LOCAL_VARIABLE); types.add(ElementKind.FIELD); return Collections.singletonList(((ExecutableElement) el).getReturnType()); } return null; }
private void parseMethod(Api api, ExecutableElement executableElement) throws IOException { Element actionElement = generator .getProcessingEnvironment() .getElementUtils() .getTypeElement(ApiMethodDoc.class.getName()); TypeMirror apiMethodDocType = actionElement.asType(); for (AnnotationMirror am : executableElement.getAnnotationMirrors()) { if (am.getAnnotationType().equals(apiMethodDocType)) { api.apiMethodDoc = Maps.newHashMap(); for (Map.Entry<? extends ExecutableElement, ? extends AnnotationValue> ee : am.getElementValues().entrySet()) { api.apiMethodDoc.put(ee.getKey().getSimpleName().toString(), ee.getValue()); } break; } } // generator.log("apiMethodDoc: " + api.apiMethodDoc); if (null == api.apiMethodDoc) { generator.log("Method miss @ApiMethodDoc. " + executableElement); return; } api.methodName = executableElement.getSimpleName().toString(); api.methodMapping = executableElement.getAnnotation(RequestMapping.class); api.parameters = Lists.newArrayList(); for (VariableElement var : executableElement.getParameters()) { api.parameters.add(var); } }
public static List<TypeMirror> asTypes(final Collection<? extends Element> elements) { final List<TypeMirror> types = Lists.newArrayList(); for (final Element element : elements) { types.add(element.asType()); } return types; }
/** super(args) -> SuperType.call(this, args) */ private JS callToSuperConstructor( WriterVisitor<JS> visitor, MethodInvocationTree tree, GenerationContext<JS> context) { Element methodElement = TreeUtils.elementFromUse(tree); TypeElement typeElement = (TypeElement) methodElement.getEnclosingElement(); String methodName = MethodInvocationWriter.buildMethodName(tree); // avoid useless call to super() when the super class is Object if (GeneratorConstants.SUPER.equals(methodName) && JavaNodes.sameRawType(typeElement.asType(), Object.class)) { return null; } // avoid call to super for synthetic types if (GeneratorConstants.SUPER.equals(methodName) && context.getCurrentWrapper().getEnclosingType().isSyntheticType()) { return null; } // transform it into superType.[prototype.method].call(this, args..); String typeName = context.getNames().getTypeName(context, typeElement, DependencyType.STATIC); JS superType = context .js() .name( GeneratorConstants.SUPER.equals(methodName) ? typeName : typeName + ".prototype." + methodName); List<JS> arguments = MethodInvocationWriter.buildArguments(visitor, tree, context); arguments.add(0, context.js().keyword(Keyword.THIS)); return context.js().functionCall(context.js().property(superType, "call"), arguments); }
private void createConstructorAndBuilder() { List<ExecutableElement> constructors = new ArrayList<ExecutableElement>(); for (Element e : annotatedElement.getEnclosedElements()) { if (e.getKind() == CONSTRUCTOR) { constructors.add((ExecutableElement) e); } } for (ExecutableElement userConstructor : constructors) { JMethod copyConstructor = generatedClass.constructor(PUBLIC); JMethod staticHelper = generatedClass.method(PUBLIC | STATIC, generatedClass._extends(), "build"); codeModelHelper.generifyStaticHelper(this, staticHelper, getAnnotatedElement()); JBlock body = copyConstructor.body(); JInvocation superCall = body.invoke("super"); JInvocation newInvocation = JExpr._new(generatedClass); for (VariableElement param : userConstructor.getParameters()) { String paramName = param.getSimpleName().toString(); JClass paramType = codeModelHelper.typeMirrorToJClass(param.asType(), this); copyConstructor.param(paramType, paramName); staticHelper.param(paramType, paramName); superCall.arg(JExpr.ref(paramName)); newInvocation.arg(JExpr.ref(paramName)); } JVar newCall = staticHelper.body().decl(generatedClass, "instance", newInvocation); staticHelper.body().invoke(newCall, getOnFinishInflate()); staticHelper.body()._return(newCall); body.invoke(getInit()); } }
private void handleEmbeddedType(Element element, Set<TypeElement> elements) { TypeMirror type = element.asType(); if (element.getKind() == ElementKind.METHOD) { type = ((ExecutableElement) element).getReturnType(); } String typeName = type.toString(); if (typeName.startsWith(Collection.class.getName()) || typeName.startsWith(List.class.getName()) || typeName.startsWith(Set.class.getName())) { type = ((DeclaredType) type).getTypeArguments().get(0); } else if (typeName.startsWith(Map.class.getName())) { type = ((DeclaredType) type).getTypeArguments().get(1); } TypeElement typeElement = typeExtractor.visit(type); if (typeElement != null && !TypeUtils.hasAnnotationOfType(typeElement, conf.getEntityAnnotations())) { if (!typeElement.getQualifiedName().toString().startsWith("java.")) { elements.add(typeElement); } } }
SQLiteColumnSpec(String name, Element element, int conflictClause) { this.field = element != null ? element.getSimpleName().toString() : null; this.name = StringUtils.nonEmpty(name, field); this.type = element == null ? TypeName.LONG : TypeName.get(element.asType()); this.pk = ROWID.equals(this.name); this.conflictClause = conflictClause; }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { // check if process was done on previous round if (OcelotProcessor.isDone() || roundEnv.processingOver()) { // Returns true if types generated by this round will not be // subject to a subsequent round of annotation processing; returns // false otherwise. return true; // if is it : stop } // Create provider of ocelot-services.js String js = createJSServicesProvider(); // Create file ocelot-services.js try { FileObject resource = filer.createResource(StandardLocation.CLASS_OUTPUT, "", js); try (Writer writer = resource.openWriter()) { ElementVisitor visitor = new DataServiceVisitor(processingEnv); for (Element element : roundEnv.getElementsAnnotatedWith(DataService.class)) { messager.printMessage( Diagnostic.Kind.MANDATORY_WARNING, " javascript generation class : " + element); element.accept(visitor, writer); } } } catch (IOException e) { messager.printMessage(Diagnostic.Kind.ERROR, e.getMessage()); } OcelotProcessor.setDone(true); return true; }
/** * Returns true if and only if a component can instantiate new instances (typically of a module) * rather than requiring that they be passed. */ static boolean componentCanMakeNewInstances(TypeElement typeElement) { switch (typeElement.getKind()) { case CLASS: break; case ENUM: case ANNOTATION_TYPE: case INTERFACE: return false; default: throw new AssertionError("TypeElement cannot have kind: " + typeElement.getKind()); } if (typeElement.getModifiers().contains(ABSTRACT)) { return false; } if (requiresEnclosingInstance(typeElement)) { return false; } for (Element enclosed : typeElement.getEnclosedElements()) { if (enclosed.getKind().equals(CONSTRUCTOR) && ((ExecutableElement) enclosed).getParameters().isEmpty() && !enclosed.getModifiers().contains(PRIVATE)) { return true; } } // TODO(gak): still need checks for visibility return false; }
private void parseBindExtra( Element element, Map<TypeElement, IntentBindingAdapterGenerator> targetClassMap, Set<String> erasedTargetNames) throws InvalidTypeException { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); // Verify that the target has all the appropriate information for type TypeMirror type = element.asType(); if (type instanceof TypeVariable) { TypeVariable typeVariable = (TypeVariable) type; type = typeVariable.getUpperBound(); } validateNotRequiredArguments(element); validateForCodeGeneration(BindExtra.class, element); validateBindingPackage(BindExtra.class, element); // Assemble information on the bind point String name = element.getSimpleName().toString(); String intentType = typeUtil.getIntentType(type); KeySpec key = getKey(element); boolean required = element.getAnnotation(NotRequired.class) == null; boolean hasDefault = typeUtil.isPrimitive(type); boolean needsToBeCast = typeUtil.needToCastIntentType(type); IntentBindingAdapterGenerator intentBindingAdapterGenerator = getOrCreateTargetClass(targetClassMap, enclosingElement); IntentFieldBinding binding = new IntentFieldBinding(name, type, intentType, key, needsToBeCast, hasDefault, required); intentBindingAdapterGenerator.addField(binding); // Add the type-erased version to the valid targets set. erasedTargetNames.add(enclosingElement.toString()); }
private void parseBind( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { // Verify common generated code restrictions. if (isInaccessibleViaGeneratedCode(Bind.class, "fields", element) || isBindingInWrongPackage(Bind.class, element)) { return; } TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.ARRAY) { parseBindMany(element, targetClassMap, erasedTargetNames); } else if (LIST_TYPE.equals(doubleErasure(elementType))) { parseBindMany(element, targetClassMap, erasedTargetNames); } else if (isSubtypeOfType(elementType, ITERABLE_TYPE)) { error( element, "@%s must be a List or array. (%s.%s)", Bind.class.getSimpleName(), ((TypeElement) element.getEnclosingElement()).getQualifiedName(), element.getSimpleName()); } else { parseBindOne(element, targetClassMap, erasedTargetNames); } }
private ExecutableElement[] findGetterAndSetter(TypeElement cls, VariableElement variable) { ExecutableElement[] gs = new ExecutableElement[] {null, null}; List<? extends Element> enclosedElements = cls.getEnclosedElements(); String capitalizedVarName = StringUtils.startUpperCase(variable.getSimpleName().toString()); String getterName = String.format("get%s", capitalizedVarName); String setterName = String.format("set%s", capitalizedVarName); for (int i = 0, c = enclosedElements.size(); i < c; i++) { Element e = enclosedElements.get(i); if (e.getKind() == ElementKind.METHOD) { if (getterName.equals(e.getSimpleName().toString())) { gs[0] = (ExecutableElement) e; } else if (setterName.equals(e.getSimpleName().toString())) { gs[1] = (ExecutableElement) e; } else { continue; } if (gs[0] != null && gs[1] != null) { break; } } } return gs; }
public SqlCreateStatement( Map<String, Element> elementMap, Element parent, SqlUpgradeScripts upgradeScripts) { this.tableName = parent.getSimpleName().toString(); columnDefinitions = new ArrayList<>(); columnDefinitions.add(ColumnDefinition.createPrimaryIdDefinition()); for (String key : elementMap.keySet()) { Element element = elementMap.get(key); ColumnDefinition columnDefinition = new ColumnDefinition(element); Column column = element.getAnnotation(Column.class); ForeignObject foreignObject = element.getAnnotation(ForeignObject.class); if (column != null && upgradeScripts != null) { int version = column.version(); if (version > 1) { upgradeScripts.addAlterAddColumn(columnDefinition, tableName, version); } } else if (foreignObject != null && upgradeScripts != null) { int version = foreignObject.version(); if (version > 1) { upgradeScripts.addAlterAddColumn(columnDefinition, tableName, version); } } columnDefinitions.add(columnDefinition); } }
@Override public Void visitAnnotation(AnnotationTree node, Void p) { Element anno = TreeInfo.symbol((JCTree) node.getAnnotationType()); if (anno.toString().equals(DefaultType.class.getName())) { checker.report(Result.failure("annotation.not.allowed.in.src", anno.toString()), node); } return super.visitAnnotation(node, p); }
// Assumes targetKinds and E are sensible. private static <E extends Element> List<E> listFilter( Iterable<? extends Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) { List<E> list = new ArrayList<E>(); for (Element e : elements) { if (targetKinds.contains(e.getKind())) list.add(clazz.cast(e)); } return list; }
private void addResponseHeaders(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(ResponseHeader.class)) { ResponseHeader annotation = element.getAnnotation(ResponseHeader.class); String fieldAddress = getFieldAddress(actionClass, element); builder.addStatement( fieldAddress + " = $L.get($S)", element.toString(), BASE_HEADERS_MAP, annotation.value()); } }
private void parseConstructorParameterAnnotations(PropertyBuilder property, Element element) { if (element.getAnnotation(Nullable.class) != null) { property.setNullable(true); } if (element.getAnnotation(Volatile.class) != null) { property.setVolatile(true); } }
// Assumes targetKinds and E are sensible. private static <E extends Element> Set<E> setFilter( Set<? extends Element> elements, Set<ElementKind> targetKinds, Class<E> clazz) { // Return set preserving iteration order of input set. Set<E> set = new LinkedHashSet<E>(); for (Element e : elements) { if (targetKinds.contains(e.getKind())) set.add(clazz.cast(e)); } return set; }
private static String getFieldAddress(RestActionClass actionClass, Element element) { String address; if (actionClass.getTypeElement().equals(element.getEnclosingElement())) { address = "action.$L"; } else { address = String.format("((%s)action).$L", element.getEnclosingElement()); } return address; }
private void addRequestHeaders(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(RequestHeader.class)) { RequestHeader annotation = element.getAnnotation(RequestHeader.class); builder.beginControlFlow("if (action.$L != null)", element); builder.addStatement( "requestBuilder.addHeader($S, action.$L.toString())", annotation.value(), element); builder.endControlFlow(); } }
private boolean hasMethod(String methodName) { for (Element element : typeElement.getEnclosedElements()) { if (element.getKind() == ElementKind.METHOD && methodName.equalsIgnoreCase(element.getSimpleName().toString())) { return true; } } return false; }
public static Visibility of(Element element) { if (element.getModifiers().contains(Modifier.PUBLIC)) { return PUBLIC; } if (element.getModifiers().contains(Modifier.PRIVATE)) { return PRIVATE; } return PACKAGE; }
private void createBeanInfo(TypeElement classElement) throws Exception { if (verbose) { processingEnv .getMessager() .printMessage( Diagnostic.Kind.NOTE, "Generating BeanInfo for " + classElement.getSimpleName()); } String className = classElement.getSimpleName().toString(); String qualifiedName = classElement.getQualifiedName().toString(); PackageElement packageElement = (PackageElement) classElement.getEnclosingElement(); String packageName = packageElement.getQualifiedName().toString(); Map<String, VariableElement> fields = new HashMap<String, VariableElement>(); Writer writer = null; try { // Build Bean Info TypeElement curClassElement = classElement; do { for (Element e : curClassElement.getEnclosedElements()) { if (e.getKind().equals(ElementKind.FIELD) && !e.getModifiers().contains(Modifier.TRANSIENT) && !e.getModifiers().contains(Modifier.STATIC)) { fields.put(e.getSimpleName().toString(), (VariableElement) e); } } TypeMirror t = curClassElement.getSuperclass(); if (t instanceof DeclaredType) { curClassElement = (TypeElement) ((DeclaredType) t).asElement(); } else { curClassElement = null; } } while (curClassElement != null); VelocityContext vc = new VelocityContext(); vc.put("className", className); vc.put("packageName", packageName); vc.put("fields", fields); // Create source file JavaFileObject jfo = processingEnv.getFiler().createSourceFile(qualifiedName + "BeanInfo"); if (verbose) { processingEnv .getMessager() .printMessage(Diagnostic.Kind.NOTE, "creating source file: " + jfo.toUri()); } writer = jfo.openWriter(); template.merge(vc, writer); } finally { closeQuietly(writer); } }
@Override protected boolean handleProcess( Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element el : roundEnv.getElementsAnnotatedWith(EventDoc.class)) { EventDoc event = el.getAnnotation(EventDoc.class); debug("Found event: " + event.module() + " " + event.code() + " " + event.desc()); addLine(getLine(event), getFilePath(event)); } return true; }
default Result checkSignature(Element elem) { if (elem.getKind() != ElementKind.INTERFACE) { String err = "A signature template must be an interface, but an element annotated with " + "`@Signature` has TypeKind {0}."; err = format(err, elem.getKind()); return error(err, AllSignatureChecks.class, elem); } return checkSignature((TypeElement) elem); }