@Override
  @SuppressWarnings("ConstantConditions")
  protected void doVisitField(
      @Nullable VariableElement oldField, @Nullable VariableElement newField) {
    if (!shouldCheck(oldField, newField)) {
      return;
    }

    Predicate<VariableElement> isNotEnumConstant = v -> v.getKind() != ElementKind.ENUM_CONSTANT;

    List<? extends VariableElement> fields =
        ElementFilter.fieldsIn(oldField.getEnclosingElement().getEnclosedElements());
    fields.removeIf(isNotEnumConstant);

    int oldIdx = fields.indexOf(oldField);

    fields = ElementFilter.fieldsIn(newField.getEnclosingElement().getEnclosedElements());
    fields.removeIf(isNotEnumConstant);

    int newIdx = fields.indexOf(newField);

    if (newIdx != oldIdx) {
      pushActive(oldField, newField, oldIdx, newIdx);
    }
  }
 @Override
 protected boolean shouldCheck(VariableElement oldField, VariableElement newField) {
   return isEnumClass
       && super.shouldCheck(oldField, newField)
       && oldField.getKind() == ElementKind.ENUM_CONSTANT
       && newField.getKind() == ElementKind.ENUM_CONSTANT;
 }
  private void addActionToIntentBuilder(
      EIntentServiceHolder holder,
      ExecutableElement executableElement,
      String methodName,
      JFieldVar actionKeyField) {
    JMethod method =
        holder.getIntentBuilderClass().method(PUBLIC, holder.getIntentBuilderClass(), methodName);
    JBlock body = method.body();

    // setAction
    body.invoke("action").arg(actionKeyField);

    // For each method params, we get put value into extras
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() > 0) {

      // Extras params
      for (VariableElement param : methodParameters) {
        String paramName = param.getSimpleName().toString();
        JClass parameterClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder);

        JFieldVar paramVar = getStaticExtraField(holder, paramName);
        JVar methodParam = method.param(parameterClass, paramName);

        JMethod putExtraMethod =
            holder.getIntentBuilder().getPutExtraMethod(param.asType(), paramName, paramVar);
        body.invoke(putExtraMethod).arg(methodParam);
      }
    }
    body._return(JExpr._this());
  }
 public void generateFieldDeclaration(VariableElement fieldElement) {
   println(
       "  {0}{1} {2};",
       generateModifierList(fieldElement.getModifiers().toArray(new Modifier[] {})),
       fieldElement.asType().toString(),
       fieldElement.getSimpleName());
 }
Exemple #5
0
 public MapKeyNamingType getMapKeyNamingValue() {
   VariableElement enumConstant = AnnotationValueUtil.toEnumConstant(mapKeyNaming);
   if (enumConstant == null) {
     throw new AptIllegalStateException("mapKeyNaming");
   }
   return MapKeyNamingType.valueOf(enumConstant.getSimpleName().toString());
 }
 public void generateFieldDeclaration(VariableElement fieldElement, Modifier... modifiers) {
   println(
       "  {0}{1} {2};",
       generateModifierList(modifiers),
       fieldElement.asType().toString(),
       fieldElement.getSimpleName());
 }
 @Override
 public Void visitEnumConstant(VariableElement c, JAnnotationArrayMember p) {
   JClass annotationClass = helper.typeMirrorToJClass(c.asType(), holder);
   JExpression expression = JExpr.direct(annotationClass.fullName() + "." + c.getSimpleName());
   p.param(expression);
   return null;
 }
  @Override
  public void writeFieldReadStatement(
      VariableElement field,
      Collection<ExecutableElement> postCreateChildMethods,
      JavaWriter writer)
      throws IOException {
    DeclaredType type = (DeclaredType) field.asType();
    TypeMirror itemType = type.getTypeArguments().get(0);
    TypeMirror itemTypeErasure = processingEnv.getTypeUtils().erasure(itemType);

    String collectionInitializer;
    try {
      collectionInitializer = initializers.findCollectionInitializer(type);
    } catch (InvalidTypeException e) {
      processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, e.getMessage(), field);
      collectionInitializer = "null";
    }
    writer.beginControlFlow("if (bundle.containsKey(\"%s\"))", field.getSimpleName());
    writer.emitStatement("object.%s = %s", field.getSimpleName(), collectionInitializer);
    writer.emitStatement(
        "%1$s.readCollectionFromBundle(object.%2$s, bundle, %3$s.class, \"%2$s\")",
        CollectionBundler.class.getCanonicalName(), field.getSimpleName(), itemTypeErasure);

    writePostCreateChildMethodCalls(field, itemType, postCreateChildMethods, writer);
    writer.endControlFlow();
  }
  private void processFromProperties(TypeElement type, Set<TypeElement> types) {
    List<? extends Element> children = type.getEnclosedElements();
    VisitorConfig config = conf.getConfig(type, children);

    // fields
    if (config.visitFieldProperties()) {
      for (VariableElement field : ElementFilter.fieldsIn(children)) {
        TypeElement typeElement = typeExtractor.visit(field.asType());
        if (typeElement != null) {
          types.add(typeElement);
        }
      }
    }

    // getters
    if (config.visitMethodProperties()) {
      for (ExecutableElement method : ElementFilter.methodsIn(children)) {
        String name = method.getSimpleName().toString();
        if ((name.startsWith("get") || name.startsWith("is")) && method.getParameters().isEmpty()) {
          TypeElement typeElement = typeExtractor.visit(method.getReturnType());
          if (typeElement != null) {
            types.add(typeElement);
          }
        }
      }
    }
  }
  public int compareTo(final MethodHandler that) {
    if (this == that) {
      return 0;
    }

    int res = methName.compareTo(that.methName);
    if (res != 0) {
      return res;
    }

    if (pars.size() < that.pars.size()) {
      return -1;
    }

    if (pars.size() > that.pars.size()) {
      return 1;
    }

    Iterator<VariableElement> it = that.pars.iterator();
    for (VariableElement pd : pars) {
      VariableElement thatPd = it.next();

      if (!pd.equals(thatPd)) {
        return 1;
      }
    }

    return 0;
  }
 private void haveAfterTextChangedMethodParameters(
     ExecutableElement executableElement, IsValid valid) {
   List<? extends VariableElement> parameters = executableElement.getParameters();
   boolean editableParameterFound = false;
   boolean textViewParameterFound = false;
   for (VariableElement parameter : parameters) {
     String parameterType = parameter.asType().toString();
     if (parameterType.equals("android.text.Editable")) {
       if (editableParameterFound) {
         annotationHelper.printAnnotationError(
             executableElement,
             "Unrecognized parameter declaration. you can declare only one parameter of type android.text.Editable");
         valid.invalidate();
       }
       editableParameterFound = true;
       continue;
     }
     if (parameterType.equals("android.widget.TextView")) {
       if (textViewParameterFound) {
         annotationHelper.printAnnotationError(
             executableElement,
             "Unrecognized parameter declaration. you can declare only one parameter of type android.widget.TextView");
         valid.invalidate();
       }
       textViewParameterFound = true;
       continue;
     }
     valid.invalidate();
     annotationHelper.printAnnotationError(
         executableElement,
         "Unrecognized parameter type. %s can only have a android.widget.TextView parameter and/or an android.text.Editable parameter. See android.text.TextWatcher.afterTextChanged() for more informations.");
   }
 }
  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());
    }
  }
 @Override
 public boolean processVariableElement(VariableElement field, DeclaredTypeName fieldType) {
   boolean isViewProperty = TypeConstants.isBasicPropertyType(fieldType);
   ViewQuery isViewQuery = field.getAnnotation(ViewQuery.class);
   Set<Modifier> modifiers = field.getModifiers();
   if (modifiers.containsAll(TypeConstants.PUBLIC_STATIC_FINAL)) {
     if (isViewQuery != null) {
       if (!TypeConstants.QUERY.equals(fieldType)) {
         utils
             .getMessager()
             .printMessage(
                 Diagnostic.Kind.ERROR,
                 "ViewQuery must be an instance of " + TypeConstants.QUERY.toString());
       } else if (modelSpec.hasMetadata(ViewModelSpecWrapper.METADATA_KEY_QUERY_ELEMENT)) {
         utils
             .getMessager()
             .printMessage(Diagnostic.Kind.ERROR, "Only one ViewQuery can be declared per spec");
       } else {
         modelSpec.putMetadata(ViewModelSpecWrapper.METADATA_KEY_VIEW_QUERY, isViewQuery);
         modelSpec.putMetadata(ViewModelSpecWrapper.METADATA_KEY_QUERY_ELEMENT, field);
       }
       return true;
     } else {
       return super.processVariableElement(field, fieldType);
     }
   } else if (isViewProperty) {
     utils
         .getMessager()
         .printMessage(
             Diagnostic.Kind.ERROR, "View properties must be public static final", field);
   }
   return false;
 }
Exemple #14
0
  @Override
  public void process(Element element, EBeanHolder holder) {
    final ExecutableElement afterPutMethod = (ExecutableElement) element;
    final UseModelHolder useModelHolder = holder.getPluginHolder(new UseModelHolder(holder));
    useModelHolder.setAfterPutMethod(afterPutMethod);

    List<Class<? extends Annotation>> annotations =
        Arrays.asList(UseModel.class, LocalDBModel.class, ServerModel.class);
    for (Class<? extends Annotation> annotation : annotations) {
      if (element.getAnnotation(annotation) != null) return;
    }

    List<? extends VariableElement> parameters = afterPutMethod.getParameters();

    JInvocation invocation =
        useModelHolder
            .getPutModelInitBlock()
            ._if(ref("result").ne(_null()))
            ._then()
            .invoke(afterPutMethod.getSimpleName().toString());

    for (VariableElement param : parameters) {
      final String paramName = param.getSimpleName().toString();
      ParamUtils.injectParam(paramName, invocation);
    }
  }
Exemple #15
0
 @Override
 public void printErrorCheckMethod(
     final PrintWriter writer, final ExecutableElement method, final String tabs) {
   final Check check = method.getAnnotation(Check.class);
   if (check != null) // Get the error code from an IntBuffer output parameter
   writer.println(
         tabs + "Util.checkCLError(" + check.value() + ".get(" + check.value() + ".position()));");
   else {
     final Class return_type = Utils.getJavaType(method.getReturnType());
     if (return_type == int.class) writer.println(tabs + "Util.checkCLError(__result);");
     else {
       boolean hasErrCodeParam = false;
       for (final VariableElement param : method.getParameters()) {
         if ("errcode_ret".equals(param.getSimpleName().toString())
             && Utils.getJavaType(param.asType()) == IntBuffer.class) {
           hasErrCodeParam = true;
           break;
         }
       }
       if (hasErrCodeParam)
         throw new RuntimeException(
             "A method is missing the @Check annotation: " + method.toString());
     }
   }
 }
Exemple #16
0
        @Override
        public String apply(VariableElement input) {
          if (isVarArg(input.asType())) {
            return ((ArrayType) input.asType()).getComponentType() + "...";
          }

          return input.asType().toString();
        }
Exemple #17
0
 public boolean containsField(String name) {
   for (VariableElement field : getFields()) {
     if (field.getSimpleName().toString().equals(name)) {
       return true;
     }
   }
   return false;
 }
 @Override
 public Void visitVariable(VariableElement e, Void p) {
   if (e.getAnnotation(Signaller.class) != null) {
     TypeElement typeElement = elementUtils.getTypeElement(e.asType().toString());
     if (typeElement != null) {
       handleTypeElement(typeElement);
     }
   }
   return super.visitVariable(e, p);
 }
 private void scanForMultipart(
     ExecutableElement executableElement, RestDocumentation.Resource.Method doc) {
   for (VariableElement var : executableElement.getParameters()) {
     TypeMirror varType = var.asType();
     if (varType.toString().startsWith(MultipartHttpServletRequest.class.getName())) {
       doc.setMultipartRequest(true);
       return;
     }
   }
 }
 private void processNestedLombokTypes(
     String prefix, TypeElement element, ExecutableElement source, TypeElementMembers members) {
   for (Map.Entry<String, VariableElement> entry : members.getFields().entrySet()) {
     String name = entry.getKey();
     VariableElement field = entry.getValue();
     if (isLombokField(field, element)) {
       processNestedType(prefix, element, source, name, null, field, field.asType());
     }
   }
 }
 // 4942232:
 // check that classes exist for all the parameters of native methods
 private void checkMethodParameters(Set<TypeElement> classes) {
   Types types = processingEnv.getTypeUtils();
   for (TypeElement te : classes) {
     for (ExecutableElement ee : ElementFilter.methodsIn(te.getEnclosedElements())) {
       for (VariableElement ve : ee.getParameters()) {
         TypeMirror tm = ve.asType();
         checkMethodParametersVisitor.visit(tm, types);
       }
     }
   }
 }
  private void buildPathVariables(
      ExecutableElement executableElement, RestDocumentation.Resource.Method doc) {
    RestDocumentation.Resource.Method.UrlFields subs = doc.getUrlSubstitutions();

    for (VariableElement var : executableElement.getParameters()) {
      PathVariable pathVar = var.getAnnotation(PathVariable.class);
      if (pathVar != null) {
        addUrlField(subs, var, pathVar.value());
      }
    }
  }
  private void buildUrlParameters(
      ExecutableElement executableElement, RestDocumentation.Resource.Method doc) {
    RestDocumentation.Resource.Method.UrlFields subs = doc.getUrlParameters();

    for (VariableElement var : executableElement.getParameters()) {
      RequestParam reqParam = var.getAnnotation(RequestParam.class);
      if (reqParam != null) {
        addUrlField(subs, var, reqParam.value());
      }
    }
  }
Exemple #24
0
  private void printMethod(ExecutableElement executableElement) {
    StringBuilder s = new StringBuilder(256);
    s.append("method: " + executableElement).append("\n\t");
    s.append("annotations: " + executableElement.getAnnotationMirrors()).append("\n\t");
    s.append("return: " + executableElement.getReturnType()).append("\n\t");
    for (VariableElement var : executableElement.getParameters()) {
      s.append("parameter: " + var + ", " + var.getAnnotation(ApiParameterDoc.class))
          .append("\n\t");
    }

    generator.log(s.toString());
  }
Exemple #25
0
 static Parameter forVariableElement(VariableElement variable) {
   ImmutableSet.Builder<String> qualifiers = ImmutableSet.builder();
   for (AnnotationMirror annotationMirror : variable.getAnnotationMirrors()) {
     DeclaredType annotationType = annotationMirror.getAnnotationType();
     if (annotationType.asElement().getAnnotation(Qualifier.class) != null) {
       qualifiers.add(Mirrors.getQualifiedName(annotationType).toString());
     }
   }
   return new Parameter(
       FluentIterable.from(qualifiers.build()).first(),
       variable.asType().toString(),
       variable.getSimpleName().toString());
 }
 private boolean validateParametersTypes(ExecutableElement constructor) {
   boolean res = true;
   List<? extends VariableElement> parameters = constructor.getParameters();
   Iterator<TypeElement> sources = context.sources().iterator();
   for (VariableElement parameter : parameters) {
     TypeElement sourceType = sources.next();
     if (!parameter.asType().equals(sourceType.asType())) {
       res = false;
       break;
     }
   }
   return res;
 }
 private static void printBufferObjectChecks(
     PrintWriter writer, ExecutableElement method, Mode mode, boolean context_specific) {
   EnumSet<BufferKind> check_set = EnumSet.noneOf(BufferKind.class);
   for (VariableElement param : method.getParameters()) {
     BufferObject bo_annotation = param.getAnnotation(BufferObject.class);
     if (bo_annotation != null) {
       check_set.add(bo_annotation.value());
     }
   }
   for (BufferKind kind : check_set) {
     printBufferObjectCheck(writer, kind, mode, context_specific);
   }
 }
  @Override
  public void writeFieldWriteStatement(VariableElement field, JavaWriter writer)
      throws IOException {
    DeclaredType type = (DeclaredType) field.asType();
    TypeMirror itemType = type.getTypeArguments().get(0);
    TypeMirror itemTypeErasure = processingEnv.getTypeUtils().erasure(itemType);

    writer.beginControlFlow("if (object.%s != null)", field.getSimpleName());
    writer.emitStatement(
        "%1$s.writeCollectionToBundle(object.%2$s, bundle, %3$s.class, \"%2$s\")",
        CollectionBundler.class.getCanonicalName(), field.getSimpleName(), itemTypeErasure);
    writer.endControlFlow();
  }
 protected String manufactureAccessorName(VariableElement fieldElement) {
   String name;
   if (fieldElement
       .asType()
       .toString()
       .equals(java.lang.Boolean.class.getSimpleName().toLowerCase())) {
     name = "is";
   } else {
     name = "get";
   }
   name += firstCharToUpperCase(fieldElement.getSimpleName().toString());
   return name;
 }
  private void addActionInOnHandleIntent(
      EIntentServiceHolder holder,
      ExecutableElement executableElement,
      String methodName,
      JFieldVar actionKeyField) {
    // If action match, call the method
    JInvocation actionCondition =
        actionKeyField.invoke("equals").arg(holder.getOnHandleIntentIntentAction());
    JBlock callActionBlock = holder.getOnHandleIntentBody()._if(actionCondition)._then();
    JInvocation callActionInvocation = JExpr._super().invoke(methodName);

    // For each method params, we get back value from extras and put it
    // in super calls
    List<? extends VariableElement> methodParameters = executableElement.getParameters();
    if (methodParameters.size() > 0) {
      // Extras
      JVar extras = callActionBlock.decl(classes().BUNDLE, "extras");
      extras.init(holder.getOnHandleIntentIntent().invoke("getExtras"));
      JBlock extrasNotNullBlock = callActionBlock._if(extras.ne(_null()))._then();

      // Extras params
      for (VariableElement param : methodParameters) {
        String paramName = param.getSimpleName().toString();
        String extraParamName = paramName + "Extra";
        JFieldVar paramVar = getStaticExtraField(holder, paramName);
        JClass extraParamClass = codeModelHelper.typeMirrorToJClass(param.asType(), holder);
        BundleHelper bundleHelper = new BundleHelper(annotationHelper, param);

        JExpression getExtraExpression =
            JExpr.invoke(extras, bundleHelper.getMethodNameToRestore()).arg(paramVar);
        if (bundleHelper.restoreCallNeedCastStatement()) {
          getExtraExpression = JExpr.cast(extraParamClass, getExtraExpression);

          if (bundleHelper.restoreCallNeedsSuppressWarning()) {
            JMethod onHandleIntentMethod = holder.getOnHandleIntentMethod();
            if (onHandleIntentMethod.annotations().size() == 0) {
              onHandleIntentMethod.annotate(SuppressWarnings.class).param("value", "unchecked");
            }
          }
        }

        JVar extraField =
            extrasNotNullBlock.decl(extraParamClass, extraParamName, getExtraExpression);
        callActionInvocation.arg(extraField);
      }
      extrasNotNullBlock.add(callActionInvocation);
    } else {
      callActionBlock.add(callActionInvocation);
    }
    callActionBlock._return();
  }