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 <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; }
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; }
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; }
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); } }
private void addResponseStatements( RestActionClass actionClass, MethodSpec.Builder builder, Element element) { String fieldAddress = getFieldAddress(actionClass, element); if (equalTypes(element, HttpBody.class)) { builder.addStatement(fieldAddress + " = response.getBody()", element); } else if (equalTypes(element, String.class)) { builder.addStatement(fieldAddress + " = response.getBody().toString()", element); } else { builder.addStatement( fieldAddress + " = ($T) converter.fromBody(response.getBody(), new $T<$T>(){}.getType())", element, element.asType(), TypeToken.class, element.asType()); } }
private void visitField(final Element field) { final MemberMirrorGeneratorVisitor visitor = new MemberMirrorGeneratorVisitor(); final MemberMirror member = field.asType().accept(visitor, field); if (member != null) { members.add(member); } }
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 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); } } }
/** * ソース生成. * * @throws IOException * @author vvakame */ public void write() throws IOException { Filer filer = processingEnv.getFiler(); String generateClassName = classElement.asType().toString() + postfix; JavaFileObject fileObject = filer.createSourceFile(generateClassName, classElement); Template.write(fileObject, g); }
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()); }
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); } }
public static String getterName(final Element e) { final char[] field = getName(e).toCharArray(); field[0] = Character.toUpperCase(field[0]); final TypeMirror typeMirror = e.asType(); final TypeKind kind = typeMirror.getKind(); final String prefix = kind == TypeKind.BOOLEAN ? "is" : "get"; return prefix + new String(field); }
private boolean doesClassContainNoArgsConstructor(Element el) { for (Element subelement : el.getEnclosedElements()) { if (subelement.getKind() == ElementKind.CONSTRUCTOR && subelement.getModifiers().contains(Modifier.PUBLIC)) { TypeMirror mirror = subelement.asType(); if (mirror.accept(noArgsVisitor, null)) return true; } } return false; }
private CodeBlock getInstanceCodeBlockWithPotentialCast( Element injectionSiteElement, Element bindingElement) { if (injectionSiteElement.equals(bindingElement)) { return CodeBlocks.format("instance"); } TypeName injectionSiteName = TypeName.get(injectionSiteElement.asType()); if (injectionSiteName instanceof ParameterizedTypeName) { injectionSiteName = ((ParameterizedTypeName) injectionSiteName).rawType; } return CodeBlocks.format("(($T) instance)", injectionSiteName); }
@Override public String format(BindingDeclaration bindingDeclaration) { if (bindingDeclaration instanceof SubcomponentDeclaration) { return formatSubcomponentDeclaration((SubcomponentDeclaration) bindingDeclaration); } if (bindingDeclaration instanceof ContributionBinding) { ContributionBinding binding = (ContributionBinding) bindingDeclaration; switch (binding.bindingKind()) { case SYNTHETIC_RELEASABLE_REFERENCE_MANAGER: return String.format( "binding for %s from the scope declaration", stripCommonTypePrefixes(keyFormatter.format(binding.key()))); case SYNTHETIC_RELEASABLE_REFERENCE_MANAGERS: return String.format( "Dagger-generated binding for %s", stripCommonTypePrefixes(keyFormatter.format(binding.key()))); default: break; } } checkArgument( bindingDeclaration.bindingElement().isPresent(), "Cannot format bindings without source elements: %s", bindingDeclaration); Element bindingElement = bindingDeclaration.bindingElement().get(); switch (bindingElement.asType().getKind()) { case EXECUTABLE: return methodSignatureFormatter.format( MoreElements.asExecutable(bindingElement), bindingDeclaration .contributingModule() .map(module -> MoreTypes.asDeclared(module.asType()))); case DECLARED: return stripCommonTypePrefixes(bindingElement.asType().toString()); default: throw new IllegalArgumentException("Formatting unsupported for element: " + bindingElement); } }
private void processAnnotation( final Element element, final HashMap<String, String> values, final Messager msg) { // Get the Option annotation on the member final Option option = element.getAnnotation(Option.class); // Get the class name of the option bean className = element.getEnclosingElement().toString(); // Check if the type in the member is a String. If not we ignore it // We are currently only supporting String type if (!element.asType().toString().equals(String.class.getName())) { msg.printMessage( Diagnostic.Kind.WARNING, element.asType() + " not supported. " + option.name() + " not processed"); return; } // Save the option switch and the member's name in a hash set // e.g. -filename (option switch) mapped to fileName (member) values.put(option.name(), element.getSimpleName().toString()); }
private Set<TypeElement> processDelegateMethods() { Set<Element> delegateMethods = (Set) getElements(QueryDelegate.class); Set<TypeElement> typeElements = new HashSet<TypeElement>(); for (Element delegateMethod : delegateMethods) { ExecutableElement method = (ExecutableElement) delegateMethod; Element element = delegateMethod.getEnclosingElement(); String name = method.getSimpleName().toString(); Type delegateType = typeFactory.getType(element.asType(), true); Type returnType = typeFactory.getType(method.getReturnType(), true); List<Parameter> parameters = elementHandler.transformParams(method.getParameters()); // remove first element parameters = parameters.subList(1, parameters.size()); EntityType entityType = null; for (AnnotationMirror annotation : delegateMethod.getAnnotationMirrors()) { if (TypeUtils.isAnnotationMirrorOfType(annotation, QueryDelegate.class)) { TypeMirror type = TypeUtils.getAnnotationValueAsTypeMirror(annotation, "value"); if (type != null) { entityType = typeFactory.getEntityType(type, true); } } } if (entityType != null) { registerTypeElement(entityType.getFullName(), (TypeElement) element); entityType.addDelegate( new Delegate(entityType, delegateType, name, parameters, returnType)); TypeElement typeElement = processingEnv.getElementUtils().getTypeElement(entityType.getFullName()); boolean isAnnotated = false; for (Class<? extends Annotation> ann : conf.getEntityAnnotations()) { if (typeElement.getAnnotation(ann) != null) { isAnnotated = true; } } if (isAnnotated) { // handle also properties of entity type typeElements.add( processingEnv.getElementUtils().getTypeElement(entityType.getFullName())); } else { // skip handling properties context.extensionTypes.put(entityType.getFullName(), entityType); context.allTypes.put(entityType.getFullName(), entityType); } } } return typeElements; }
/** * Check shareable components for serializability. * * @param round The round environment. */ private void checkShareableComponents(RoundEnvironment round) { Set<? extends Element> elts = round.getElementsAnnotatedWith(Shareable.class); note("processing %d shareable elements", elts.size()); TypeMirror serializable = elementUtils.getTypeElement("java.io.Serializable").asType(); for (Element elt : elts) { note("examining %s", elt); TypeMirror type = elt.asType(); if (typeUtils.isAssignable(type, serializable)) { note("shareable type %s is serializable", type); } else { warning(elt, "shareable type %s is not serializable", type); } } }
private void addStatusField(RestActionClass actionClass, MethodSpec.Builder builder) { for (Element element : actionClass.getAnnotatedElements(Status.class)) { String fieldAddress = getFieldAddress(actionClass, element); if (TypeUtils.containsType(element, Boolean.class, boolean.class)) { builder.addStatement(fieldAddress + " = response.isSuccessful()", element); } else if (TypeUtils.containsType(element, Integer.class, int.class, long.class)) { builder.addStatement( fieldAddress + " = ($T) response.getStatus()", element, element.asType()); } else if (equalTypes(element, String.class)) { builder.addStatement(fieldAddress + " = Integer.toString(response.getStatus())", element); } else if (TypeUtils.containsType(element, Long.class)) { builder.addStatement(fieldAddress + " = (long) response.getStatus()", element); } } }
private boolean haveADefaultContructor(Element element) { int constructorsCount = 0; for (Element subelement : element.getEnclosedElements()) { if (subelement.getKind() == ElementKind.CONSTRUCTOR) { // System.out.println("Constructor found: " + subelement); constructorsCount++; TypeMirror mirror = subelement.asType(); if (mirror.accept(noArgsVisitor, null)) return true; } } // System.out.println("constructors found for " + element.getSimpleName() + " [" + // constructorsCount + "]"); return constructorsCount == 0; }
/** * Given an array of <code>Parameter</code>s, return a name/rank number map. If the array is null, * then null is returned. * * @param params The array of parameters (from type or executable member) to check. * @return a name-rank number map. */ private static Map<String, String> getRankMap(Utils utils, List<? extends Element> params) { if (params == null) { return null; } HashMap<String, String> result = new HashMap<>(); int rank = 0; for (Element e : params) { String name = utils.isTypeParameterElement(e) ? utils.getTypeName(e.asType(), false) : utils.getSimpleName(e); result.put(name, String.valueOf(rank)); rank++; } return result; }
private boolean hasLocalSignatureField(Element field) { assert field.getKind() == ElementKind.FIELD; if (isAnnotatedBy(procEnv, field, "org.paninij.lang.Local")) { TypeMirror type = getScalarType(field.asType()); if (type.getKind() == TypeKind.DECLARED) { TypeElement typeElem = (TypeElement) procEnv.getTypeUtils().asElement(type); if (typeElem == null) { throw new IllegalArgumentException("Failed to lookup type element: " + type); } if (isAnnotatedBy(procEnv, typeElem, "org.paninij.lang.SignatureInterface")) { return true; } } } return false; }
private void parseBindText( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { TypeElement enclosingElement = (TypeElement) element.getEnclosingElement(); TypeMirror elementType = element.asType(); if (elementType.getKind() == TypeKind.TYPEVAR) { TypeVariable typeVariable = (TypeVariable) elementType; elementType = typeVariable.getUpperBound(); } // Assemble information on the field. int[] ids = element.getAnnotation(BindText.class).value(); BindingClass bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); for (int id : ids) { if (bindingClass != null) { KBindings bindings = bindingClass.getKBindings(String.valueOf(id)); if (bindings != null) { Iterator<FieldViewBinding> iterator = bindings.getFieldBindings().iterator(); if (iterator.hasNext()) { FieldViewBinding existingBinding = iterator.next(); error( element, "Attempt to use @%s for an already bound ID %s on '%s'. (%s.%s)", BindText.class.getSimpleName(), id, existingBinding.getName(), enclosingElement.getQualifiedName(), element.getSimpleName()); return; } } } else { bindingClass = getOrCreateTargetClass(targetClassMap, enclosingElement, false, false); } String name = element.getSimpleName().toString(); TypeName type = TypeName.get(elementType); boolean required = isRequiredBinding(element); FieldViewBinding binding = new FieldViewBinding(name, type, required); bindingClass.addField(String.valueOf(id), binding); } // Add the type-erased version to the valid binding targets set. erasedTargetNames.add(enclosingElement.toString()); }
@Override public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) { for (Element elem : roundEnv.getElementsAnnotatedWith(FixedRecord.class)) { String classPackage = processingEnv.getElementUtils().getPackageOf(elem).getQualifiedName().toString(); ClassWrapper classWrapper = new ClassWrapper(classPackage, elem.getSimpleName().toString()); List<Element> listGetter = getFixedFieldAnnotateMethod(elem); for (Element elemMethod : listGetter) { TypeWrapper typeWrapper; MethodWrapper methodWrapper = new MethodWrapper(); FixedField fixedField = elemMethod.getAnnotation(FixedField.class); String decoratorClass = getDecoratorClass(fixedField); methodWrapper.setName(elemMethod.getSimpleName().toString()); methodWrapper.setFixedField(fixedField); methodWrapper.setDecoratorClass(decoratorClass); String fullName = ((ExecutableType) elemMethod.asType()).getReturnType().toString(); if (fullName.contains("<") && fixedField.collectionSize() > 0) { fullName = fullName.substring(fullName.indexOf("<") + 1, fullName.indexOf(">")); } String packageName = fullName.substring(0, fullName.lastIndexOf(".")); String typeName = fullName.substring(packageName.length() + 1); if (fixedField.length() == 0 && fixedField.collectionSize() == 0) { methodWrapper.setBean(true); } else if (fixedField.collectionSize() > 0) { methodWrapper.setList(true); } typeWrapper = new TypeWrapper(packageName, typeName); methodWrapper.setType(typeWrapper); classWrapper.addMethod(methodWrapper); } parser.createParserClass(classWrapper); // TODO processingEnv.getMessager().printMessage(Diagnostic.Kind.NOTE, ""); } if (roundEnv.processingOver()) { parser.getJavaFileBuilder().writeJavaFile(processingEnv); return false; } return true; // no further processing of this annotation type }
private void emitStatements( Set<? extends Element> annotatedElements, String hostActivityname, JavaWriter writer) throws IOException { for (Element element : annotatedElements) { writer.emitStatement( "((" + hostActivityname + ")target)." + element.getSimpleName().toString() + " = " + "(" + element.asType().toString() + ")target.findViewById(" + element.getAnnotation(InjectView.class).value() + ")"); } }
private void generateStructBinding( Element element, Struct struct, String root, String pakage, File header) throws IOException { String declaredType = element.asType().toString(); String structName = struct.name().equals(DEFAULT) ? declaredType : struct.name(); if (generatedStructs.contains(structName)) { messager.printMessage( Kind.WARNING, "struct " + structName + " already defined elsewhere.", element); return; } System.out.println("generating struct accessor for struct: " + structName); generatedStructs.add(structName); String output = root + separator + outputDir; String config = output + separator + header.getName() + ".cfg"; File configFile = new File(config); FileWriter writer = null; try { writer = new FileWriter(configFile); writer.write("Package " + pakage + "\n"); writer.write("EmitStruct " + structName + "\n"); if (!struct.name().equals(DEFAULT)) { writer.write("RenameJavaType " + struct.name() + " " + declaredType + "\n"); } } finally { if (writer != null) { writer.close(); } } // TODO this isn't very clean since we won't get any exceptions this way GlueGen.main( // "-I"+path+"/build/", "-O" + output, "-E" + AnnotationProcessorJavaStructEmitter.class.getName(), "-C" + config, header.getPath()); configFile.delete(); }
@Override public JsonElement visitEnum(DeclaredType t, Element el) { Types typeUtils = processingEnv.getTypeUtils(); if (AptUtil.isInternalType(typeUtils, el.asType())) { // InternalなEnum TypeElement typeElement = AptUtil.getTypeElement(typeUtils, el); if (AptUtil.isPublic(typeElement)) { return genJsonElement(t, el, Kind.ENUM); } else { Log.e("Internal EnumType must use public & static.", el); encountError = true; return defaultAction(t, el); } } else { // InternalじゃないEnum return genJsonElement(t, el, Kind.ENUM); } }
@Override public void process(Element element, JCodeModel codeModel, EBeanHolder holder) { Classes classes = holder.classes(); String fieldName = element.getSimpleName().toString(); Res resInnerClass = androidValue.getRInnerClass(); JFieldRef idRef = annotationHelper.extractOneAnnotationFieldRef(holder, element, resInnerClass, true); JBlock methodBody = holder.init.body(); TypeMirror fieldTypeMirror = element.asType(); String fieldType = fieldTypeMirror.toString(); // Special case for loading animations if (CanonicalNameConstants.ANIMATION.equals(fieldType)) { methodBody.assign( ref(fieldName), classes.ANIMATION_UTILS.staticInvoke("loadAnimation").arg(holder.contextRef).arg(idRef)); } else { if (holder.resources == null) { holder.resources = methodBody.decl( classes.RESOURCES, "resources_", holder.contextRef.invoke("getResources")); } String resourceMethodName = androidValue.getResourceMethodName(); // Special case for @HtmlRes if (element.getAnnotation(HtmlRes.class) != null) { methodBody.assign( ref(fieldName), classes .HTML .staticInvoke("fromHtml") .arg(invoke(holder.resources, resourceMethodName).arg(idRef))); } else { methodBody.assign(ref(fieldName), invoke(holder.resources, resourceMethodName).arg(idRef)); } } }
private void parseOnKStringUpdate( Element element, Map<TypeElement, BindingClass> targetClassMap, Set<String> erasedTargetNames) { 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(","); UpdateKStringBinding binding = new UpdateKStringBinding(methodName, methodTypes); String kstring = element.getAnnotation(OnKStringChanged.class).value(); bindingClass.addKStringUpdateBinding(kstring, binding); } erasedTargetNames.add(enclosingElement.toString()); }