Exemplo n.º 1
0
 /**
  * @param executable the executable to check
  * @return {@code true}, iff the executable does not represent {@link
  *     java.lang.Object#equals(Object)} or an overridden version of it
  */
 private static boolean isNotObjectEquals(ExecutableElement executable) {
   if (executable.getSimpleName().contentEquals("equals")
       && executable.getParameters().size() == 1
       && asTypeElement(executable.getParameters().get(0).asType())
           .getQualifiedName()
           .contentEquals("java.lang.Object")) {
     return false;
   }
   return true;
 }
 /**
  * Tests whether a method invocation is an invocation of {@link Comparable#compareTo}.
  *
  * <p>
  *
  * @param node a method invocation node
  * @return true iff {@code node} is a invocation of {@code compareTo()}
  */
 private boolean isInvocationOfCompareTo(MethodInvocationTree node) {
   ExecutableElement method = TreeUtils.elementFromUse(node);
   return (method.getParameters().size() == 1
       && method.getReturnType().getKind() == TypeKind.INT
       // method symbols only have simple names
       && method.getSimpleName().contentEquals("compareTo"));
 }
Exemplo n.º 3
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());
     }
   }
 }
 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.");
   }
 }
Exemplo n.º 5
0
  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);
    }
  }
Exemplo n.º 6
0
  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());
    }
  }
Exemplo n.º 7
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);
    }
  }
  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);
          }
        }
      }
    }
  }
Exemplo n.º 9
0
 private static void printParameterCaching(
     PrintWriter writer,
     TypeElement interface_decl,
     ExecutableElement method,
     Mode mode,
     boolean context_specific) {
   for (VariableElement param : method.getParameters()) {
     Class java_type = Utils.getJavaType(param.asType());
     CachedReference cachedReference = param.getAnnotation(CachedReference.class);
     if (Buffer.class.isAssignableFrom(java_type)
         && cachedReference != null
         && (mode != Mode.BUFFEROBJECT || param.getAnnotation(BufferObject.class) == null)
         && param.getAnnotation(Result.class) == null) {
       writer.print("\t\tif ( LWJGLUtil.CHECKS ) StateTracker.");
       if (context_specific) {
         writer.print("getReferences(caps).");
       } else {
         writer.print("getTracker().");
       }
       if (cachedReference.name().length() > 0) {
         writer.print(cachedReference.name());
       } else {
         writer.print(Utils.getReferenceName(interface_decl, method, param));
       }
       if (cachedReference.index().length() > 0) {
         writer.print("[" + cachedReference.index() + "]");
       }
       writer.println(" = " + param.getSimpleName() + ";");
     }
   }
 }
  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());
  }
Exemplo n.º 11
0
 private void hasConstructor(TypeElement type) {
   for (ExecutableElement cons : ElementFilter.constructorsIn(type.getEnclosedElements())) {
     if (cons.getParameters().isEmpty()) {
       return;
     }
   }
   error("missing default (no-args) constructor", type);
 }
Exemplo n.º 12
0
 private boolean checkForDependencies(List<ExecutableElement> providerMethods) {
   for (ExecutableElement element : providerMethods) {
     if (!element.getParameters().isEmpty()) {
       return true;
     }
   }
   return false;
 }
Exemplo n.º 13
0
  private void parseGuard(ExecutableElement methodElement) {
    assert methodElement.getParameters().size() == 1;

    final String type = methodElement.getParameters().get(0).asType().toString();

    if (type.equals(DynamicObject.class.getName())) {
      assert !hasDynamicObjectGuard;
      hasDynamicObjectGuard = true;
    } else if (type.equals(ObjectType.class.getName())) {
      assert !hasObjectTypeGuard;
      hasObjectTypeGuard = true;
    } else if (type.equals(Object.class.getName())) {
      assert !hasObjectGuard;
      hasObjectGuard = true;
    } else {
      assert false : "Unknown type for the first guard parameter: " + type;
    }
  }
 private String[] getParamTypes(ExecutableElement e) {
   return e.getParameters()
       .stream()
       .map(VariableElement::asType)
       //                .map(typeUtils::asElement)
       //                .map((t) -> ((TypeElement) t).getQualifiedName().toString())
       .map(TypeMirror::toString)
       .toArray((i) -> new String[i]);
 }
Exemplo n.º 15
0
  public static boolean isSimpleMethod(final Element element) {
    if (element instanceof ExecutableElement) {
      final ExecutableElement ee = (ExecutableElement) element;
      final List<? extends VariableElement> parameters = ee.getParameters();

      return !hasAnyModifier(ee, Modifier.STATIC) && parameters.isEmpty();
    }
    return false;
  }
Exemplo n.º 16
0
  public Parameter getSingleParameter(TypeElement includingType, ExecutableElement method) {
    List<? extends VariableElement> parameters = method.getParameters();

    if (parameters.size() != 1) {
      // TODO: Log error
      return null;
    }

    return Collections.first(getParameters(includingType, method));
  }
Exemplo n.º 17
0
 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;
     }
   }
 }
Exemplo n.º 18
0
    public SectorMethod build() {
      SectorMethod method = new SectorMethod();
      String methodName = methodElement.getSimpleName().toString();
      SectorOperation operationAnnotation = methodElement.getAnnotation(SectorOperation.class);
      if (operationAnnotation == null) {
        return null;
      }

      int argCount = methodElement.getParameters().size();

      method.cellbased = operationAnnotation.cellbased();
      method.name = "hz_" + methodName;

      method.returnType = methodElement.getReturnType().toString();
      method.invocationClassName =
          CodeGenerationUtils.capitalizeFirstLetter(methodName) + argCount + "Invocation";
      method.targetMethod = methodName;
      method.readonly = operationAnnotation.readonly();
      method.functionId = sectorClassModel.getMethods().size();

      List<FormalArgument> args = new LinkedList<>();

      for (VariableElement variableElement : methodElement.getParameters()) {
        FormalArgument formalArgument = new FormalArgument();
        if (method.cellbased && args.isEmpty()) {
          formalArgument.name = "id";
          formalArgument.type = "long";
        } else {
          formalArgument.name = "arg" + (args.size() + 1);
          formalArgument.type = variableElement.asType().toString();
        }
        args.add(formalArgument);
      }

      method.formalArguments = args;

      buildOriginalMethos(method);

      buildAsyncMethod(method);

      return method;
    }
Exemplo n.º 19
0
 // 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);
       }
     }
   }
 }
Exemplo n.º 20
0
  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());
      }
    }
  }
Exemplo n.º 21
0
  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());
      }
    }
  }
Exemplo n.º 22
0
 private void setConstructor() {
   constructor = generatedClass.constructor(PRIVATE);
   JVar constructorContextParam = constructor.param(getClasses().CONTEXT, "context");
   JBlock constructorBody = constructor.body();
   List<ExecutableElement> constructors =
       ElementFilter.constructorsIn(annotatedElement.getEnclosedElements());
   ExecutableElement superConstructor = constructors.get(0);
   if (superConstructor.getParameters().size() == 1) {
     constructorBody.invoke("super").arg(constructorContextParam);
   }
   constructorBody.assign(getContextField(), constructorContextParam);
 }
Exemplo n.º 23
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());
  }
Exemplo n.º 24
0
 /** Returns the no-args constructor for {@code type}, or null if no such constructor exists. */
 public static ExecutableElement getNoArgsConstructor(TypeElement type) {
   for (Element enclosed : type.getEnclosedElements()) {
     if (enclosed.getKind() != ElementKind.CONSTRUCTOR) {
       continue;
     }
     ExecutableElement constructor = (ExecutableElement) enclosed;
     if (constructor.getParameters().isEmpty()) {
       return constructor;
     }
   }
   return null;
 }
Exemplo n.º 25
0
 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);
   }
 }
Exemplo n.º 26
0
 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;
 }
Exemplo n.º 27
0
 private boolean hasParcelableConstructor(TypeElement typeElement) {
   for (Element e : typeElement.getEnclosedElements()) {
     if (e.getKind() == ElementKind.CONSTRUCTOR && hasSomeModifier(e, Modifier.PUBLIC)) {
       ExecutableElement c = (ExecutableElement) e;
       List<? extends VariableElement> params = c.getParameters();
       if (params.size() == 1
           && ClassName.get(params.get(0).asType()).equals(ClassName.get(Parcel.class))) {
         return true;
       }
     }
   }
   return false;
 }
  /**
   * Formats an ExecutableElement as if it were contained within the container, if the container is
   * present.
   */
  public String format(ExecutableElement method, Optional<DeclaredType> container) {
    StringBuilder builder = new StringBuilder();
    TypeElement type = MoreElements.asType(method.getEnclosingElement());
    ExecutableType executableType = MoreTypes.asExecutable(method.asType());
    if (container.isPresent()) {
      executableType = MoreTypes.asExecutable(types.asMemberOf(container.get(), method));
      type = MoreElements.asType(container.get().asElement());
    }

    // TODO(cgruber): AnnotationMirror formatter.
    List<? extends AnnotationMirror> annotations = method.getAnnotationMirrors();
    if (!annotations.isEmpty()) {
      Iterator<? extends AnnotationMirror> annotationIterator = annotations.iterator();
      for (int i = 0; annotationIterator.hasNext(); i++) {
        if (i > 0) {
          builder.append(' ');
        }
        builder.append(ErrorMessages.format(annotationIterator.next()));
      }
      builder.append(' ');
    }
    builder.append(nameOfType(executableType.getReturnType()));
    builder.append(' ');
    builder.append(type.getQualifiedName());
    builder.append('.');
    builder.append(method.getSimpleName());
    builder.append('(');
    checkState(method.getParameters().size() == executableType.getParameterTypes().size());
    Iterator<? extends VariableElement> parameters = method.getParameters().iterator();
    Iterator<? extends TypeMirror> parameterTypes = executableType.getParameterTypes().iterator();
    for (int i = 0; parameters.hasNext(); i++) {
      if (i > 0) {
        builder.append(", ");
      }
      appendParameter(builder, parameters.next(), parameterTypes.next());
    }
    builder.append(')');
    return builder.toString();
  }
  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();
  }
Exemplo n.º 30
0
 /** {@inheritDoc} */
 public void inherit(DocFinder.Input input, DocFinder.Output output) {
   Utils utils = input.utils;
   if (input.tagId == null) {
     input.isTypeVariableParamTag = ((ParamTree) input.docTreeInfo.docTree).isTypeParameter();
     ExecutableElement ee = (ExecutableElement) input.docTreeInfo.element;
     CommentHelper ch = utils.getCommentHelper(ee);
     List<? extends Element> parameters =
         input.isTypeVariableParamTag ? ee.getTypeParameters() : ee.getParameters();
     String target = ch.getParameterName(input.docTreeInfo.docTree);
     for (int i = 0; i < parameters.size(); i++) {
       Element e = parameters.get(i);
       String pname =
           input.isTypeVariableParamTag
               ? utils.getTypeName(e.asType(), false)
               : utils.getSimpleName(e);
       if (pname.equals(target)) {
         input.tagId = String.valueOf(i);
         break;
       }
     }
   }
   ExecutableElement md = (ExecutableElement) input.element;
   CommentHelper ch = utils.getCommentHelper(md);
   List<? extends DocTree> tags =
       input.isTypeVariableParamTag ? utils.getTypeParamTrees(md) : utils.getParamTrees(md);
   List<? extends Element> parameters =
       input.isTypeVariableParamTag ? md.getTypeParameters() : md.getParameters();
   Map<String, String> rankMap = getRankMap(utils, parameters);
   for (DocTree tag : tags) {
     String paramName = ch.getParameterName(tag);
     if (rankMap.containsKey(paramName) && rankMap.get(paramName).equals((input.tagId))) {
       output.holder = input.element;
       output.holderTag = tag;
       output.inlineTags = ch.getBody(utils.configuration, tag);
       return;
     }
   }
 }