Example #1
0
  private void buildResponseErrors(Method method, MethodDocument document, JavaMethod javaMethod) {
    final DocletTag[] errorStatuses = javaMethod.getTagsByName("error.status");
    final DocletTag[] errorCauses = javaMethod.getTagsByName("error.cause");
    int totalErrors = errorCauses.length;
    if (errorStatuses.length != errorCauses.length) {
      LOG.warn(
          "For method {}, the number of tags @error.status is different than the"
              + " number of tags @error.cause; Because of this, the {} will only use the minimum"
              + " count from the two.",
          method.getName(),
          this.getClass().getName());
      totalErrors = Math.min(errorCauses.length, errorStatuses.length);
    }

    List<ResponseError> errors = new ArrayList<ResponseError>(totalErrors);
    for (int i = 0; i < totalErrors; i++) {
      try {
        errors.add(
            new ResponseError(
                Integer.parseInt(errorStatuses[i].getValue()), errorCauses[i].getValue()));
      } catch (NumberFormatException e) {
        LOG.error("Invalid number for @error.status: " + errorStatuses[i].getValue());
      }
    }

    document.setResponseErrors(ImmutableList.copyOf(errors));
  }
  private void _addReturnElement(Element methodElement, JavaMethod javaMethod) throws Exception {

    Type returns = javaMethod.getReturns();

    if (returns == null) {
      return;
    }

    String returnsValue = returns.getValue();

    if (returnsValue.equals("void")) {
      return;
    }

    Element returnElement = methodElement.addElement("return");

    DocletTag[] returnDocletTags = javaMethod.getTagsByName("return");

    String comment = StringPool.BLANK;

    if (returnDocletTags.length > 0) {
      DocletTag returnDocletTag = returnDocletTags[0];

      comment = GetterUtil.getString(returnDocletTag.getValue());

      DocUtil.add(returnElement, "required", true);
    }

    comment = _trimMultilineText(comment);

    Element commentElement = returnElement.addElement("comment");

    commentElement.addCDATA(comment);
  }
 /**
  * Get ITestNGMethod author(s) string, or class author(s) if no method author is present. Default
  * return value is "unknown".
  *
  * @param className
  * @param method
  * @return
  * @author hzjingcheng
  */
 private String getAuthors(String className, ITestNGMethod method) {
   JavaClass cls = builder.getClassByName(className);
   DocletTag[] authors = cls.getTagsByName("author");
   // get class authors as default author name
   String allAuthors = "";
   if (authors.length == 0) {
     allAuthors = "unknown";
   } else {
     for (DocletTag author : authors) {
       allAuthors += author.getValue() + " ";
     }
   }
   // get method author name
   JavaMethod[] mtds = cls.getMethods();
   for (JavaMethod mtd : mtds) {
     if (mtd.getName().equals(method.getMethodName())) {
       authors = mtd.getTagsByName("author");
       if (authors.length != 0) {
         allAuthors = "";
         for (DocletTag author : authors) {
           allAuthors += author.getValue() + " ";
         }
       }
       break;
     }
   }
   return allAuthors.trim();
 }
 private static void ppp(String s) {
   JavaClass jc = null;
   //		jc.getMethods()[0].getParameters()[0].getType().getGenericValue()
   //		jc.getFields()[0].getTagByName("").getParameters()
   //		jc.getFullyQualifiedName()
   JavaMethod jm = null;
   jm.getTagsByName("aa");
   System.out.println("[DoclipseJavaDocProcessor] " + s);
 }
  private void _addThrowsElements(Element methodElement, JavaMethod javaMethod) {

    Type[] exceptionTypes = javaMethod.getExceptions();

    DocletTag[] throwsDocletTags = javaMethod.getTagsByName("throws");

    for (Type exceptionType : exceptionTypes) {
      _addThrowsElement(methodElement, exceptionType, throwsDocletTags);
    }
  }
  private void _addParamElements(Element methodElement, JavaMethod javaMethod) {

    JavaParameter[] javaParameters = javaMethod.getParameters();

    DocletTag[] paramDocletTags = javaMethod.getTagsByName("param");

    for (JavaParameter javaParameter : javaParameters) {
      _addParamElement(methodElement, javaParameter, paramDocletTags);
    }
  }
Example #7
0
  // Processes parameters of javaMethod and enters the proper key-values into the methodNode
  private void processParameters(JavaMethod javaMethod, ObjectNode methodNode) {
    ArrayNode parameters = mapper.createArrayNode();
    methodNode.set("parameters", parameters);
    boolean required = true;

    for (JavaParameter javaParameter : javaMethod.getParameters()) {
      ObjectNode individualParameterNode = mapper.createObjectNode();
      Optional<JavaAnnotation> optional =
          javaParameter
              .getAnnotations()
              .stream()
              .filter(
                  annotation ->
                      annotation.getType().getName().equals(PATH_PARAM)
                          || annotation.getType().getName().equals(QUERY_PARAM))
              .findAny();
      JavaAnnotation pathType = optional.isPresent() ? optional.get() : null;

      String annotationName = javaParameter.getName();

      if (pathType != null) { // the parameter is a path or query parameter
        individualParameterNode.put(
            "name", pathType.getNamedParameter("value").toString().replace("\"", ""));
        if (pathType.getType().getName().equals(PATH_PARAM)) {
          individualParameterNode.put("in", "path");
        } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
          individualParameterNode.put("in", "query");
        }
        individualParameterNode.put("type", getType(javaParameter.getType()));
      } else { // the parameter is a body parameter
        individualParameterNode.put("name", annotationName);
        individualParameterNode.put("in", "body");

        // TODO add actual hardcoded schemas and a type
        // body parameters must have a schema associated with them
        ArrayNode schema = mapper.createArrayNode();
        individualParameterNode.set("schema", schema);
      }
      for (DocletTag p : javaMethod.getTagsByName("param")) {
        if (p.getValue().contains(annotationName)) {
          try {
            String description = p.getValue().split(" ", 2)[1].trim();
            if (description.contains("optional")) {
              required = false;
            }
            individualParameterNode.put("description", description);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      individualParameterNode.put("required", required);
      parameters.add(individualParameterNode);
    }
  }
Example #8
0
  private void buildQueryAndPathDocuments(
      Method method, JavaMethod javaMethod, MethodDocument document) {
    if (method.getParameterTypes().length != javaMethod.getParameters().length) {
      LOG.error(
          "Unable to generate argument documentation: number of method arguments is not "
              + "the same as number of @param found in javadoc.");
      return;
    }

    List<ParamDocument> queryParams = new ArrayList<ParamDocument>();
    List<ParamDocument> pathParams = new ArrayList<ParamDocument>();

    Annotation[][] annotations = method.getParameterAnnotations();
    for (int i = 0; i < annotations.length; i++) {
      JavaParameter javaParameter = javaMethod.getParameters()[i];
      DocletTag javaParameterTag = javaMethod.getTagsByName("param")[i];

      // Check annotations at parameter i
      for (Annotation a : annotations[i]) {
        if (a.annotationType() == QueryParam.class) {
          queryParams.add(
              new ParamDocument(
                  javaParameter.getName(),
                  extractParameterValue(javaParameterTag, javaParameter.getName())));
        } else if (a.annotationType() == PathParam.class) {
          pathParams.add(
              new ParamDocument(
                  javaParameter.getName(),
                  extractParameterValue(javaParameterTag, javaParameter.getName())));
        }
      }
    }

    LOG.info("Found {} query params for method {}", queryParams.size(), method.getName());
    LOG.info("Found {}  path params for method {}", pathParams.size(), method.getName());
    document.setQueryParams(ImmutableList.copyOf(queryParams));
    document.setPathParams(ImmutableList.copyOf(pathParams));
  }
Example #9
0
  private void buildExamples(JavaMethod javaMethod, MethodDocument document) {
    final DocletTag[] exampleTitles = javaMethod.getTagsByName("example.title");
    final DocletTag[] exampleDescriptions = javaMethod.getTagsByName("example.description");
    final DocletTag[] exampleRequests = javaMethod.getTagsByName("example.request");
    final DocletTag[] exampleRequestsContentType =
        javaMethod.getTagsByName("example.requestContentType");
    final DocletTag[] exampleResponses = javaMethod.getTagsByName("example.response");
    final DocletTag[] exampleResponsesContentType =
        javaMethod.getTagsByName("example.responseContentType");

    if ((exampleTitles.length != exampleDescriptions.length)
        || (exampleTitles.length != exampleRequests.length)
        || (exampleTitles.length != exampleRequestsContentType.length)
        || (exampleTitles.length != exampleResponses.length)
        || (exampleTitles.length != exampleResponsesContentType.length)) {
      LOG.error(
          "Unable to build examples. The number of tags "
              + "example/title,description,request,requestContentType,response,responseContentType "
              + "must be equal.");
      return;
    }

    List<ApiExampleDocument> examples = new ArrayList<ApiExampleDocument>();
    for (int i = 0; i < exampleTitles.length; i++) {
      ApiExampleDocument example =
          new ApiExampleDocument(
              exampleTitles[i].getValue(),
              exampleDescriptions[i].getValue(),
              exampleRequests[i].getValue(),
              exampleRequestsContentType[i].getValue(),
              exampleResponses[i].getValue(),
              exampleResponsesContentType[i].getValue());
      LOG.info("Added new example for {}: {}", document.getPath(), example);
      examples.add(example);
    }

    document.setExampleDocuments(ImmutableList.copyOf(examples));
  }
Example #10
0
  // Processes parameters of javaMethod and enters the proper key-values into the methodNode
  private void processParameters(
      JavaMethod javaMethod, ObjectNode methodNode, String method, DocletTag tag) {
    ArrayNode parameters = mapper.createArrayNode();
    methodNode.set("parameters", parameters);
    boolean required = true;

    for (JavaParameter javaParameter : javaMethod.getParameters()) {
      ObjectNode individualParameterNode = mapper.createObjectNode();
      Optional<JavaAnnotation> optional =
          javaParameter
              .getAnnotations()
              .stream()
              .filter(
                  annotation ->
                      annotation.getType().getName().equals(PATH_PARAM)
                          || annotation.getType().getName().equals(QUERY_PARAM))
              .findAny();
      JavaAnnotation pathType = optional.isPresent() ? optional.get() : null;

      String annotationName = javaParameter.getName();

      if (pathType != null) { // the parameter is a path or query parameter
        individualParameterNode.put(
            "name", pathType.getNamedParameter("value").toString().replace("\"", ""));
        if (pathType.getType().getName().equals(PATH_PARAM)) {
          individualParameterNode.put("in", "path");
        } else if (pathType.getType().getName().equals(QUERY_PARAM)) {
          individualParameterNode.put("in", "query");
        }
        individualParameterNode.put("type", getType(javaParameter.getType()));
      } else { // the parameter is a body parameter
        individualParameterNode.put("name", annotationName);
        individualParameterNode.put("in", "body");

        // Adds the reference to the Json model for the input
        // that goes in the post or put operation
        if (tag != null
            && (method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))) {
          ObjectNode schema = mapper.createObjectNode();
          tag.getParameters()
              .stream()
              .forEach(
                  param -> {
                    schema.put("$ref", "#/definitions/" + param);
                  });
          individualParameterNode.set("schema", schema);
        }
      }
      for (DocletTag p : javaMethod.getTagsByName("param")) {
        if (p.getValue().contains(annotationName)) {
          try {
            String description = p.getValue().split(" ", 2)[1].trim();
            if (description.contains("optional")) {
              required = false;
            }
            individualParameterNode.put("description", description);
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
      individualParameterNode.put("required", required);
      parameters.add(individualParameterNode);
    }
  }