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);
  }
  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));
  }
 /**
  * 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();
 }
Exemple #4
0
  @Test
  public void descriptionAppearsInGetterJavadoc() throws IOException {

    JavaMethod javaMethod = classWithTitle.getMethodBySignature("getTitle", new Type[] {});
    String javaDocComment = javaMethod.getComment();

    assertThat(javaDocComment, containsString("A title for this property"));
  }
  private String _removeJavadocFromJava(JavaClass javaClass, String content) {
    Set<Integer> lineNumbers = new HashSet<Integer>();

    lineNumbers.add(_getJavaClassLineNumber(javaClass));

    JavaMethod[] javaMethods = javaClass.getMethods();

    for (JavaMethod javaMethod : javaMethods) {
      lineNumbers.add(javaMethod.getLineNumber());
    }

    JavaField[] javaFields = javaClass.getFields();

    for (JavaField javaField : javaFields) {
      lineNumbers.add(javaField.getLineNumber());
    }

    String[] lines = StringUtil.splitLines(content);

    for (int lineNumber : lineNumbers) {
      if (lineNumber == 0) {
        continue;
      }

      int pos = lineNumber - 2;

      String line = lines[pos];

      if (line == null) {
        continue;
      }

      line = line.trim();

      if (line.endsWith("*/")) {
        while (true) {
          lines[pos] = null;

          if (line.startsWith("/**") || line.startsWith("/*")) {
            break;
          }

          line = lines[--pos].trim();
        }
      }
    }

    StringBundler sb = new StringBundler(content.length());

    for (String line : lines) {
      if (line != null) {
        sb.append(line);
        sb.append("\n");
      }
    }

    return sb.toString().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);
    }
  }
Exemple #9
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);
    }
  }
Exemple #10
0
  private void processRestMethod(
      JavaMethod javaMethod,
      String method,
      Map<String, ObjectNode> pathMap,
      String resourcePath,
      ArrayNode tagArray,
      ObjectNode definitions) {
    String fullPath = resourcePath, consumes = "", produces = "", comment = javaMethod.getComment();
    DocletTag tag = javaMethod.getTagByName("rsModel");
    for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
      String name = annotation.getType().getName();
      if (name.equals(PATH)) {
        fullPath = resourcePath + "/" + getPath(annotation);
        fullPath = fullPath.replaceFirst("^//", "/");
      }
      if (name.equals(CONSUMES)) {
        consumes = getIOType(annotation);
      }
      if (name.equals(PRODUCES)) {
        produces = getIOType(annotation);
      }
    }
    ObjectNode methodNode = mapper.createObjectNode();
    methodNode.set("tags", tagArray);

    addSummaryDescriptions(methodNode, comment);
    addJsonSchemaDefinition(definitions, tag);
    addJsonSchemaDefinition(definitions, tag);

    processParameters(javaMethod, methodNode, method, tag);

    processConsumesProduces(methodNode, "consumes", consumes);
    processConsumesProduces(methodNode, "produces", produces);
    if (tag == null
        || ((method.toLowerCase().equals("post") || method.toLowerCase().equals("put"))
            && !(tag.getParameters().size() > 1))) {
      addResponses(methodNode, tag, false);
    } else {
      addResponses(methodNode, tag, true);
    }

    ObjectNode operations = pathMap.get(fullPath);
    if (operations == null) {
      operations = mapper.createObjectNode();
      operations.set(method, methodNode);
      pathMap.put(fullPath, operations);
    } else {
      operations.set(method, methodNode);
    }
  }
  private String _getMethodKey(JavaMethod javaMethod) {
    StringBuilder sb = new StringBuilder();

    sb.append(javaMethod.getName());
    sb.append("(");

    JavaParameter[] javaParameters = javaMethod.getParameters();

    for (JavaParameter javaParameter : javaParameters) {
      sb.append(javaParameter.getName());
      sb.append("|");
      sb.append(javaParameter.getType().getValue());
      sb.append(",");
    }

    sb.append(")");

    return sb.toString();
  }
  private void _addReturnElement(Element methodElement, JavaMethod javaMethod) {

    Type returns = javaMethod.getReturns();

    if ((returns == null) || returns.getValue().equals("void")) {
      return;
    }

    _addDocletElements(methodElement, javaMethod, "return");
  }
  private String _getMethodKey(JavaMethod javaMethod) {
    StringBundler sb = new StringBundler();

    sb.append(javaMethod.getName());
    sb.append(StringPool.OPEN_PARENTHESIS);

    JavaParameter[] javaParameters = javaMethod.getParameters();

    for (JavaParameter javaParameter : javaParameters) {
      sb.append(javaParameter.getName());
      sb.append("|");
      sb.append(_getTypeValue(javaParameter));
      sb.append(",");
    }

    sb.append(StringPool.CLOSE_PARENTHESIS);

    return sb.toString();
  }
Exemple #14
0
  private void processRestMethod(
      JavaMethod javaMethod,
      String method,
      Map<String, ObjectNode> pathMap,
      String resourcePath,
      ArrayNode tagArray) {
    String fullPath = resourcePath, consumes = "", produces = "", comment = javaMethod.getComment();
    for (JavaAnnotation annotation : javaMethod.getAnnotations()) {
      String name = annotation.getType().getName();
      if (name.equals(PATH)) {
        fullPath = resourcePath + "/" + getPath(annotation);
        fullPath = fullPath.replaceFirst("^//", "/");
      }
      if (name.equals(CONSUMES)) {
        consumes = getIOType(annotation);
      }
      if (name.equals(PRODUCES)) {
        produces = getIOType(annotation);
      }
    }
    ObjectNode methodNode = mapper.createObjectNode();
    methodNode.set("tags", tagArray);

    addSummaryDescriptions(methodNode, comment);
    processParameters(javaMethod, methodNode);

    processConsumesProduces(methodNode, "consumes", consumes);
    processConsumesProduces(methodNode, "produces", produces);

    addResponses(methodNode);

    ObjectNode operations = pathMap.get(fullPath);
    if (operations == null) {
      operations = mapper.createObjectNode();
      operations.set(method, methodNode);
      pathMap.put(fullPath, operations);
    } else {
      operations.set(method, methodNode);
    }
  }
Exemple #15
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));
  }
  private String _getJavaMethodComment(
      String[] lines, Map<String, Element> methodElementsMap, JavaMethod javaMethod) {

    String methodKey = _getMethodKey(javaMethod);

    Element methodElement = methodElementsMap.get(methodKey);

    if (methodElement == null) {
      return null;
    }

    String line = lines[javaMethod.getLineNumber() - 1];

    String indent = StringPool.BLANK;

    for (char c : line.toCharArray()) {
      if (Character.isWhitespace(c)) {
        indent += c;
      } else {
        break;
      }
    }

    StringBuilder sb = new StringBuilder();

    sb.append(indent);
    sb.append("/**\n");
    sb.append(indent);
    sb.append(" * ");
    sb.append(methodElement.elementText("comment"));
    sb.append("\n");
    sb.append(indent);
    sb.append(" *\n");

    _addDocletTags(methodElement, "deprecated", indent, sb);
    _addDocletTags(methodElement, "param", indent, sb);
    _addDocletTags(methodElement, "return", indent, sb);
    _addDocletTags(methodElement, "see", indent, sb);
    _addDocletTags(methodElement, "since", indent, sb);
    _addDocletTags(methodElement, "throws", indent, sb);
    _addDocletTags(methodElement, "version", indent, sb);

    sb.append(indent);
    sb.append(" */\n");

    return sb.toString();
  }
  private void _addMethodElement(Element rootElement, JavaMethod javaMethod) {
    Element methodElement = rootElement.addElement("method");

    DocUtil.add(methodElement, "name", javaMethod.getName());

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

    commentElement.addCDATA(_getCDATA(javaMethod));

    _addDocletElements(methodElement, javaMethod, "deprecated");
    _addParamElements(methodElement, javaMethod);
    _addReturnElement(methodElement, javaMethod);
    _addDocletElements(methodElement, javaMethod, "see");
    _addDocletElements(methodElement, javaMethod, "since");
    _addThrowsElements(methodElement, javaMethod);
    _addDocletElements(methodElement, javaMethod, "version");
  }
  private void _addMethodElement(Element rootElement, JavaMethod javaMethod) throws Exception {

    Element methodElement = rootElement.addElement("method");

    DocUtil.add(methodElement, "name", javaMethod.getName());

    String comment = _getCDATA(javaMethod);

    if (Validator.isNotNull(comment)) {
      Element commentElement = methodElement.addElement("comment");

      commentElement.addCDATA(_getCDATA(javaMethod));
    }

    _addDocletElements(methodElement, javaMethod, "version");
    _addParamElements(methodElement, javaMethod);
    _addReturnElement(methodElement, javaMethod);
    _addThrowsElements(methodElement, javaMethod);
    _addDocletElements(methodElement, javaMethod, "see");
    _addDocletElements(methodElement, javaMethod, "since");
    _addDocletElements(methodElement, javaMethod, "deprecated");
  }
Exemple #19
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));
  }
Exemple #20
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);
    }
  }
  private void _copyInterface(String parentDir, String srcFile) throws IOException {

    JavaClass javaClass = _getJavaClass(parentDir, srcFile);

    JavaMethod[] methods = javaClass.getMethods();

    Arrays.sort(methods, new JavaMethodComparator());

    StringMaker sm = new StringMaker();

    // Package

    sm.append("package " + javaClass.getPackage() + ";");

    // Imports

    sm.append("[$IMPORTS$]");

    // Class declaration

    sm.append(
        "public class Copy" + javaClass.getName() + " implements " + javaClass.getName() + " {");

    String varName = "_" + TextFormatter.format(javaClass.getName(), TextFormatter.I);

    // Methods

    Set imports = new TreeSet();

    for (int i = 0; i < methods.length; i++) {
      JavaMethod javaMethod = methods[i];

      String methodName = javaMethod.getName();

      if (javaMethod.isPublic()) {
        String returnValueName = javaMethod.getReturns().getValue();

        imports.add(returnValueName);

        sm.append(
            "public "
                + javaMethod.getReturns().getJavaClass().getName()
                + _getDimensions(javaMethod.getReturns())
                + " "
                + methodName
                + "(");

        JavaParameter[] parameters = javaMethod.getParameters();

        for (int j = 0; j < parameters.length; j++) {
          JavaParameter javaParameter = parameters[j];

          sm.append(
              javaParameter.getType().getJavaClass().getName()
                  + _getDimensions(javaParameter.getType())
                  + " "
                  + javaParameter.getName());

          imports.add(javaParameter.getType().getValue());

          if ((j + 1) != parameters.length) {
            sm.append(", ");
          }
        }

        sm.append(")");

        Type[] thrownExceptions = javaMethod.getExceptions();

        Set newExceptions = new LinkedHashSet();

        for (int j = 0; j < thrownExceptions.length; j++) {
          Type thrownException = thrownExceptions[j];

          newExceptions.add(thrownException.getJavaClass().getName());

          imports.add(thrownException.getValue());
        }

        if (newExceptions.size() > 0) {
          sm.append(" throws ");

          Iterator itr = newExceptions.iterator();

          while (itr.hasNext()) {
            sm.append(itr.next());

            if (itr.hasNext()) {
              sm.append(", ");
            }
          }
        }

        sm.append("{");

        if (!returnValueName.equals("void")) {
          sm.append("return ");
        }

        sm.append(varName + "." + methodName + "(");

        for (int j = 0; j < parameters.length; j++) {
          JavaParameter javaParameter = parameters[j];

          sm.append(javaParameter.getName());

          if ((j + 1) != parameters.length) {
            sm.append(", ");
          }
        }

        sm.append(");");
        sm.append("}");
      }
    }

    // Fields

    sm.append("private " + javaClass.getName() + " " + varName + ";");

    // Class close brace

    sm.append("}");

    // Imports

    String content = sm.toString();

    sm = new StringMaker();

    Iterator itr = imports.iterator();

    while (itr.hasNext()) {
      String importClass = (String) itr.next();

      if (!importClass.equals("boolean")
          && !importClass.equals("double")
          && !importClass.equals("int")
          && !importClass.equals("long")
          && !importClass.equals("short")
          && !importClass.equals("void")) {
        sm.append("import " + importClass + ";");
      }
    }

    content = StringUtil.replace(content, "[$IMPORTS$]", sm.toString());

    // Write file

    File file =
        new File(
            parentDir
                + "/"
                + StringUtil.replace(javaClass.getPackage(), ".", "/")
                + "/Copy"
                + javaClass.getName()
                + ".java");

    ServiceBuilder.writeFile(file, content);
  }
  private String _removeJavadocFromJava(String fileName, boolean log) throws Exception {

    File file = new File(_basedir + fileName);

    String oldContent = _fileUtil.read(file);

    String[] lines = StringUtil.splitLines(oldContent);

    JavaClass javaClass = _getJavaClass(fileName, new UnsyncStringReader(oldContent));

    Set<Integer> lineNumbers = new HashSet<Integer>();

    lineNumbers.add(javaClass.getLineNumber());

    JavaMethod[] javaMethods = javaClass.getMethods();

    for (JavaMethod javaMethod : javaMethods) {
      lineNumbers.add(javaMethod.getLineNumber());
    }

    JavaField[] javaFields = javaClass.getFields();

    for (JavaField javaField : javaFields) {
      lineNumbers.add(javaField.getLineNumber());
    }

    for (int lineNumber : lineNumbers) {
      int pos = lineNumber - 2;

      String line = lines[pos].trim();

      if (line.endsWith("*/")) {
        while (true) {
          lines[pos] = null;

          if (line.startsWith("/**")) {
            break;
          }

          line = lines[--pos].trim();
        }
      }
    }

    StringBuilder sb = new StringBuilder(oldContent.length());

    for (String line : lines) {
      if (line != null) {
        sb.append(line);
        sb.append("\n");
      }
    }

    String newContent = sb.toString().trim();

    if ((oldContent == null) || !oldContent.equals(newContent)) {
      _fileUtil.write(file, newContent);

      if (log) {
        System.out.println("Writing " + file);
      }
    }

    return newContent;
  }
  private void _updateJavaFromJavadoc(String fileName, String oldContent) throws Exception {

    File javadocFile = new File(_basedir + fileName + "doc");

    if (!javadocFile.exists()) {
      return;
    }

    File file = new File(_basedir + fileName);

    if (oldContent == null) {
      oldContent = _fileUtil.read(file);
    }

    String[] lines = StringUtil.splitLines(oldContent);

    JavaClass javaClass = _getJavaClass(fileName, new UnsyncStringReader(oldContent));

    Document document = _saxReaderUtil.read(javadocFile);

    Element rootElement = document.getRootElement();

    Map<Integer, String> commentsMap = new TreeMap<Integer, String>();

    commentsMap.put(javaClass.getLineNumber(), _getJavaClassComment(rootElement, javaClass));

    Map<String, Element> methodElementsMap = new HashMap<String, Element>();

    List<Element> methodElements = rootElement.elements("method");

    for (Element methodElement : methodElements) {
      String methodKey = _getMethodKey(methodElement);

      methodElementsMap.put(methodKey, methodElement);
    }

    JavaMethod[] javaMethods = javaClass.getMethods();

    for (JavaMethod javaMethod : javaMethods) {
      if (commentsMap.containsKey(javaMethod.getLineNumber())) {
        continue;
      }

      commentsMap.put(
          javaMethod.getLineNumber(), _getJavaMethodComment(lines, methodElementsMap, javaMethod));
    }

    Map<String, Element> fieldElementsMap = new HashMap<String, Element>();

    List<Element> fieldElements = rootElement.elements("field");

    for (Element fieldElement : fieldElements) {
      String fieldKey = _getFieldKey(fieldElement);

      fieldElementsMap.put(fieldKey, fieldElement);
    }

    JavaField[] javaFields = javaClass.getFields();

    for (JavaField javaField : javaFields) {
      if (commentsMap.containsKey(javaField.getLineNumber())) {
        continue;
      }

      commentsMap.put(
          javaField.getLineNumber(), _getJavaFieldComment(lines, fieldElementsMap, javaField));
    }

    StringBuilder sb = new StringBuilder(oldContent.length());

    for (int lineNumber = 1; lineNumber <= lines.length; lineNumber++) {
      String line = lines[lineNumber - 1];

      String comments = commentsMap.get(lineNumber);

      if (comments != null) {
        sb.append(comments);
      }

      sb.append(line);
      sb.append("\n");
    }

    String newContent = sb.toString().trim();

    if ((oldContent == null) || !oldContent.equals(newContent)) {
      _fileUtil.write(file, newContent);

      System.out.println("Writing " + file);
    }
  }
Exemple #24
0
 private void buildDescription(MethodDocument document, JavaMethod javaMethod) {
   document.setDescription(javaMethod.getComment());
 }
  private void _updateJavaFromDocument(
      String fileName, String originalContent, String javadocLessContent, Document document)
      throws Exception {

    String[] lines = StringUtil.splitLines(javadocLessContent);

    JavaClass javaClass = _getJavaClass(fileName, new UnsyncStringReader(javadocLessContent));

    _updateLanguageProperties(document, javaClass.getName());

    List<Tuple> ancestorJavaClassTuples = new ArrayList<Tuple>();

    ancestorJavaClassTuples = _addAncestorJavaClassTuples(javaClass, ancestorJavaClassTuples);

    Element rootElement = document.getRootElement();

    Map<Integer, String> commentsMap = new TreeMap<Integer, String>();

    commentsMap.put(
        _getJavaClassLineNumber(javaClass), _getJavaClassComment(rootElement, javaClass));

    Map<String, Element> methodElementsMap = new HashMap<String, Element>();

    List<Element> methodElements = rootElement.elements("method");

    for (Element methodElement : methodElements) {
      String methodKey = _getMethodKey(methodElement);

      methodElementsMap.put(methodKey, methodElement);
    }

    JavaMethod[] javaMethods = javaClass.getMethods();

    for (JavaMethod javaMethod : javaMethods) {
      if (commentsMap.containsKey(javaMethod.getLineNumber())) {
        continue;
      }

      String javaMethodComment = _getJavaMethodComment(lines, methodElementsMap, javaMethod);

      // Handle override tag insertion

      if (!_hasAnnotation(javaMethod, "Override")) {
        if (_isOverrideMethod(javaClass, javaMethod, ancestorJavaClassTuples)) {

          String overrideLine = _getIndent(lines, javaMethod) + "@Override\n";

          if (Validator.isNotNull(javaMethodComment)) {
            javaMethodComment = javaMethodComment + overrideLine;
          } else {
            javaMethodComment = overrideLine;
          }
        }
      }

      commentsMap.put(javaMethod.getLineNumber(), javaMethodComment);
    }

    Map<String, Element> fieldElementsMap = new HashMap<String, Element>();

    List<Element> fieldElements = rootElement.elements("field");

    for (Element fieldElement : fieldElements) {
      String fieldKey = _getFieldKey(fieldElement);

      fieldElementsMap.put(fieldKey, fieldElement);
    }

    JavaField[] javaFields = javaClass.getFields();

    for (JavaField javaField : javaFields) {
      if (commentsMap.containsKey(javaField.getLineNumber())) {
        continue;
      }

      commentsMap.put(
          javaField.getLineNumber(), _getJavaFieldComment(lines, fieldElementsMap, javaField));
    }

    StringBundler sb = new StringBundler(javadocLessContent.length());

    for (int lineNumber = 1; lineNumber <= lines.length; lineNumber++) {
      String line = lines[lineNumber - 1];

      String comments = commentsMap.get(lineNumber);

      if (comments != null) {
        sb.append(comments);
      }

      sb.append(line);
      sb.append("\n");
    }

    String formattedContent = sb.toString().trim();

    if (!originalContent.equals(formattedContent)) {
      File file = new File(_inputDir + fileName);

      _fileUtil.write(file, formattedContent.getBytes(StringPool.UTF8));

      System.out.println("Writing " + file);
    }
  }
  private boolean _isOverrideMethod(
      JavaClass javaClass, JavaMethod javaMethod, Collection<Tuple> ancestorJavaClassTuples) {

    if (javaMethod.isConstructor() || javaMethod.isPrivate() || javaMethod.isStatic()) {

      return false;
    }

    String methodName = javaMethod.getName();

    JavaParameter[] javaParameters = javaMethod.getParameters();

    Type[] types = new Type[javaParameters.length];

    for (int i = 0; i < javaParameters.length; i++) {
      types[i] = javaParameters[i].getType();
    }

    // Check for matching method in each ancestor

    for (Tuple ancestorJavaClassTuple : ancestorJavaClassTuples) {
      JavaClass ancestorJavaClass = (JavaClass) ancestorJavaClassTuple.getObject(0);

      JavaMethod ancestorJavaMethod = null;

      if (ancestorJavaClassTuple.getSize() > 1) {

        // LPS-35613

        Type[] ancestorActualTypeArguments = (Type[]) ancestorJavaClassTuple.getObject(1);

        Type[] genericTypes = new Type[types.length];

        for (int i = 0; i < types.length; i++) {
          Type type = types[i];

          String typeValue = type.getValue();

          boolean useGenericType = false;

          for (int j = 0; j < ancestorActualTypeArguments.length; j++) {

            if (typeValue.equals(ancestorActualTypeArguments[j].getValue())) {

              useGenericType = true;

              break;
            }
          }

          if (useGenericType) {
            genericTypes[i] = new Type("java.lang.Object");
          } else {
            genericTypes[i] = type;
          }
        }

        ancestorJavaMethod = ancestorJavaClass.getMethodBySignature(methodName, genericTypes);
      } else {
        ancestorJavaMethod = ancestorJavaClass.getMethodBySignature(methodName, types);
      }

      if (ancestorJavaMethod == null) {
        continue;
      }

      boolean samePackage = false;

      JavaPackage ancestorJavaPackage = ancestorJavaClass.getPackage();

      if (ancestorJavaPackage != null) {
        samePackage = ancestorJavaPackage.equals(javaClass.getPackage());
      }

      // Check if the method is in scope

      if (samePackage) {
        return !ancestorJavaMethod.isPrivate();
      } else {
        if (ancestorJavaMethod.isProtected() || ancestorJavaMethod.isPublic()) {

          return true;
        } else {
          return false;
        }
      }
    }

    return false;
  }