com.thoughtworks.qdox.model.JavaAnnotation Java Examples

The following examples show how to use com.thoughtworks.qdox.model.JavaAnnotation. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: OnosCfgMojo.java    From onos with Apache License 2.0 6 votes vote down vote up
private void processClass(JavaClass javaClass) throws IOException {
    Optional<JavaAnnotation> annotation = javaClass.getAnnotations().stream()
            .filter(ja -> ja.getType().getName().endsWith(COMPONENT))
            .findFirst();
    if (annotation.isPresent()) {
        AnnotationValue property = annotation.get().getProperty(PROPERTY);
        List<String> lines = new ArrayList<>();
        if (property instanceof AnnotationValueList) {
            AnnotationValueList list = (AnnotationValueList) property;
            list.getValueList().forEach(v -> processProperty(lines, javaClass, v));
        } else {
            processProperty(lines, javaClass, property);
        }

        if (!lines.isEmpty()) {
            writeCatalog(javaClass, lines);
        }
    }
}
 
Example #2
Source File: JavaDocExtractor.java    From jaxb2-maven-plugin with Apache License 2.0 6 votes vote down vote up
private static boolean hasAnnotation(final Class<?> annotationType,
                                     final List<JavaAnnotation> annotations) {

    if (annotations != null && !annotations.isEmpty() && annotationType != null) {

        final String fullAnnotationClassName = annotationType.getName();

        for (JavaAnnotation current : annotations) {
            if (current.getType().isA(fullAnnotationClassName)) {
                return true;
            }
        }
    }

    return false;
}
 
Example #3
Source File: CfgDefGenerator.java    From onos with Apache License 2.0 6 votes vote down vote up
private void processClass(JarOutputStream jar, JavaClass javaClass) throws IOException {
    Optional<JavaAnnotation> annotation = javaClass.getAnnotations().stream()
            .filter(ja -> ja.getType().getName().equals(COMPONENT))
            .findFirst();
    if (annotation.isPresent()) {
        AnnotationValue property = annotation.get().getProperty(PROPERTY);
        List<String> lines = new ArrayList<>();
        if (property instanceof AnnotationValueList) {
            AnnotationValueList list = (AnnotationValueList) property;
            list.getValueList().forEach(v -> processProperty(lines, javaClass, v));
        } else {
            processProperty(lines, javaClass, property);
        }

        if (!lines.isEmpty()) {
            writeCatalog(jar, javaClass, lines);
        }
    }
}
 
Example #4
Source File: DocJavaField.java    From smart-doc with Apache License 2.0 5 votes vote down vote up
public List<JavaAnnotation> getAnnotations() {
    List<JavaAnnotation> fieldAnnotations = javaField.getAnnotations();
    if (fieldAnnotations != null && !fieldAnnotations.isEmpty()) {
        return fieldAnnotations;
    }
    if (annotations == null) {
        return new ArrayList<>();
    }
    return this.annotations;
}
 
Example #5
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 5 votes vote down vote up
private String getIOType(JavaAnnotation annotation) {
    if (annotation.getNamedParameter("value").toString().equals(JSON)) {
        return "application/json";
    } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)) {
        return "application/octet_stream";
    }
    return "";
}
 
Example #6
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 5 votes vote down vote up
void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags, ObjectNode definitions) {
    // If the class does not have a Path tag then ignore it
    JavaAnnotation annotation = getPathAnnotation(javaClass);
    if (annotation == null) {
        return;
    }

    String path = getPath(annotation);
    if (path == null) {
        return;
    }

    String resourcePath = "/" + path;
    String tagPath = path.isEmpty() ? "/" : path;

    // Create tag node for this class.
    ObjectNode tagObject = mapper.createObjectNode();
    tagObject.put("name", tagPath);
    if (javaClass.getComment() != null) {
        tagObject.put("description", shortText(javaClass.getComment()));
    }
    tags.add(tagObject);

    // Create an array node add to all methods from this class.
    ArrayNode tagArray = mapper.createArrayNode();
    tagArray.add(tagPath);

    processAllMethods(javaClass, resourcePath, paths, tagArray, definitions);
}
 
Example #7
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 5 votes vote down vote up
private String getIOType(JavaAnnotation annotation) {
    if (annotation.getNamedParameter("value").toString().equals(JSON)) {
        return "application/json";
    } else if (annotation.getNamedParameter("value").toString().equals(OCTET_STREAM)) {
        return "application/octet_stream";
    }
    return "";
}
 
Example #8
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 5 votes vote down vote up
private void addResponses(JavaMethod javaMethod, ObjectNode methodNode, DocletTag tag, boolean responseJson) {
    ObjectNode responses = mapper.createObjectNode();
    methodNode.set("responses", responses);

    Optional<JavaAnnotation> responsesAnnotation = getResponsesAnnotation(javaMethod);

    if (responsesAnnotation.isPresent()) {
        Object annotationsObj = responsesAnnotation.get().getNamedParameter("value");
        if (annotationsObj != null && annotationsObj instanceof List) {
            List<JavaAnnotation> responseAnnotation = (List<JavaAnnotation>) annotationsObj;
            responseAnnotation.forEach(
                    javaAnnotation -> {
                        ObjectNode response = mapper.createObjectNode();
                        response.put("description",
                                String.valueOf(javaAnnotation.getNamedParameter("message"))
                                        .replaceAll("^\"|\"$", ""));
                        responses.set(String.valueOf(javaAnnotation.getNamedParameter("code")), response);
                    }
            );
        }
    } else {
        ObjectNode success = mapper.createObjectNode();
        success.put("description", "successful operation");
        responses.set("200", success);

        ObjectNode defaultObj = mapper.createObjectNode();
        defaultObj.put("description", "Unexpected error");
        responses.set("default", defaultObj);

        if (tag != null && responseJson) {
            ObjectNode schema = mapper.createObjectNode();
            tag.getParameters().stream().forEach(
                    param -> schema.put("$ref", "#/definitions/" + param));
            success.set("schema", schema);
        }
    }
}
 
Example #9
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 5 votes vote down vote up
void processClass(JavaClass javaClass, ObjectNode paths, ArrayNode tags,
                  ObjectNode definitions, File srcDirectory) {
    // If the class does not have a Path tag then ignore it
    JavaAnnotation annotation = getPathAnnotation(javaClass);
    if (annotation == null) {
        return;
    }

    String path = getPath(annotation);
    if (path == null) {
        return;
    }

    String resourcePath = "/" + path;
    String tagPath = path.isEmpty() ? "/" : path;

    // Create tag node for this class.
    ObjectNode tagObject = mapper.createObjectNode();
    tagObject.put("name", tagPath);
    if (javaClass.getComment() != null) {
        tagObject.put("description", shortText(javaClass.getComment()));
    }
    tags.add(tagObject);

    // Create an array node add to all methods from this class.
    ArrayNode tagArray = mapper.createArrayNode();
    tagArray.add(tagPath);

    processAllMethods(javaClass, resourcePath, paths, tagArray, definitions, srcDirectory);
}
 
Example #10
Source File: DocUtil.java    From smart-doc with Apache License 2.0 5 votes vote down vote up
/**
 * handle spring mvc mapping value
 *
 * @param annotation JavaAnnotation
 * @return String
 */
public static String handleMappingValue(JavaAnnotation annotation) {
    if (null == annotation.getNamedParameter(DocAnnotationConstants.VALUE_PROP)) {
        return "/";
    } else {
        return StringUtil.trimBlank(String.valueOf(annotation.getNamedParameter(DocAnnotationConstants.VALUE_PROP)));
    }
}
 
Example #11
Source File: DefaultDescriptorsExtractor.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean isExcludedFromDocumentation(JavaClass javaClass) {
    return javaClass.getAnnotations()
        .stream()
        .anyMatch((JavaAnnotation annotation) -> annotation.getType().getCanonicalName()
                .equals(ExcludeFromDocumentation.class.getName()));
}
 
Example #12
Source File: DefaultDescriptorsExtractor.java    From james-project with Apache License 2.0 4 votes vote down vote up
private boolean isExperimental(JavaClass javaClass) {
    return javaClass.getAnnotations()
        .stream()
        .anyMatch((JavaAnnotation annotation) -> annotation.getType().getCanonicalName()
                .equals(Experimental.class.getName()));
}
 
Example #13
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
    Optional<JavaAnnotation> optional = javaClass.getAnnotations()
            .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
    return optional.orElse(null);
}
 
Example #14
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
private void processRestMethod(JavaMethod javaMethod, String method,
                               Map<String, ObjectNode> pathMap,
                               String resourcePath, ArrayNode tagArray,
                               ObjectNode definitions, File srcDirectory) {
    String fullPath = resourcePath, consumes = "", produces = "",
            comment = javaMethod.getComment();
    DocletTag tag = javaMethod.getTagByName("onos.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(srcDirectory, definitions, tag);

    processParameters(javaMethod, methodNode, method, tag);

    processConsumesProduces(methodNode, "consumes", consumes);
    processConsumesProduces(methodNode, "produces", produces);
    if (tag == null || !(tag.getParameters().size() > 1)) {
        addResponses(javaMethod, methodNode, tag, false);
    } else {
        addResponses(javaMethod, 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);
    }
}
 
Example #15
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
private Optional<JavaAnnotation> getResponsesAnnotation(JavaMethod javaMethod) {
    return javaMethod.getAnnotations().stream().filter(
            a -> a.getType().getName().equals(RESPONSES)
    ).findAny();
}
 
Example #16
Source File: JavaDocExtractor.java    From jaxb2-maven-plugin with Apache License 2.0 4 votes vote down vote up
/**
 * Finds the value of the attribute with the supplied name within the first matching JavaAnnotation of
 * the given type encountered in the given annotations List. This is typically used for reading values of
 * annotations such as {@link XmlElement}, {@link XmlAttribute} or {@link XmlEnumValue}.
 *
 * @param annotations    The list of JavaAnnotations to filter from.
 * @param annotationType The type of annotation to read attribute values from.
 * @param attributeName  The name of the attribute the value of which should be returned.
 * @return The first matching JavaAnnotation of type annotationType within the given annotations
 * List, or {@code null} if none was found.
 * @since 2.2
 */
private static String getAnnotationAttributeValueFrom(
        final Class<?> annotationType,
        final String attributeName,
        final List<JavaAnnotation> annotations) {

    // QDox uses the fully qualified class name of the annotation for comparison.
    // Extract it.
    final String fullyQualifiedClassName = annotationType.getName();

    JavaAnnotation annotation = null;
    String toReturn = null;

    if (annotations != null) {

        for (JavaAnnotation current : annotations) {
            if (current.getType().isA(fullyQualifiedClassName)) {
                annotation = current;
                break;
            }
        }

        if (annotation != null) {

            final Object nameValue = annotation.getNamedParameter(attributeName);

            if (nameValue != null && nameValue instanceof String) {

                toReturn = ((String) nameValue).trim();

                // Remove initial and trailing " chars, if present.
                if (toReturn.startsWith("\"") && toReturn.endsWith("\"")) {
                    toReturn = (((String) nameValue).trim()).substring(1, toReturn.length() - 1);
                }
            }
        }
    }

    // All Done.
    return toReturn;
}
 
Example #17
Source File: SpringMVCRequestHeaderHandler.java    From smart-doc with Apache License 2.0 4 votes vote down vote up
/**
 * handle Spring MVC Request Header
 *
 * @param method JavaMethod
 * @return list of ApiReqHeader
 */
public List<ApiReqHeader> handle(JavaMethod method) {
    List<ApiReqHeader> apiReqHeaders = new ArrayList<>();
    for (JavaParameter javaParameter : method.getParameters()) {
        List<JavaAnnotation> javaAnnotations = javaParameter.getAnnotations();
        String className = method.getDeclaringClass().getCanonicalName();
        Map<String, String> paramMap = DocUtil.getParamsComments(method, DocTags.PARAM, className);
        String paramName = javaParameter.getName();
        ApiReqHeader apiReqHeader;
        for (JavaAnnotation annotation : javaAnnotations) {
            String annotationName = annotation.getType().getValue();
            if (SpringMvcAnnotations.REQUEST_HERDER.equals(annotationName)) {
                apiReqHeader = new ApiReqHeader();
                Map<String, Object> requestHeaderMap = annotation.getNamedParameterMap();
                if (requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP) != null) {
                    apiReqHeader.setName(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.VALUE_PROP)));
                } else {
                    apiReqHeader.setName(paramName);
                }
                StringBuilder desc = new StringBuilder();
                String comments = paramMap.get(paramName);
                desc.append(comments);

                if (requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP) != null) {
                    apiReqHeader.setValue(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP)));
                    desc.append("(defaultValue: ")
                            .append(StringUtil.removeQuotes((String) requestHeaderMap.get(DocAnnotationConstants.DEFAULT_VALUE_PROP)))
                            .append(")");
                }
                apiReqHeader.setDesc(desc.toString());
                if (requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP) != null) {
                    apiReqHeader.setRequired(!Boolean.FALSE.toString().equals(requestHeaderMap.get(DocAnnotationConstants.REQUIRED_PROP)));
                } else {
                    apiReqHeader.setRequired(true);
                }
                String typeName = javaParameter.getType().getValue().toLowerCase();
                apiReqHeader.setType(DocClassUtil.processTypeNameForParams(typeName));
                apiReqHeaders.add(apiReqHeader);
                break;
            }
        }
    }
    return apiReqHeaders;
}
 
Example #18
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
private String getPath(JavaAnnotation annotation) {
    String path = annotation.getNamedParameter("value").toString();
    return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
}
 
Example #19
Source File: SwaggerGenerator.java    From onos with Apache License 2.0 4 votes vote down vote up
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.orElse(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)) {
                String description = "";
                if (p.getValue().split(" ", 2).length >= 2) {
                    description = p.getValue().split(" ", 2)[1].trim();
                    if (description.contains("optional")) {
                        required = false;
                    }
                } else {
                    throw new RuntimeException(String.format("No description for parameter \"%s\" in " +
                                                                     "method \"%s\" in %s (line %d)",
                                                             p.getValue(), javaMethod.getName(),
                                                             javaMethod.getDeclaringClass().getName(),
                                                             javaMethod.getLineNumber()));
                }
                individualParameterNode.put("description", description);
            }
        }
        individualParameterNode.put("required", required);
        parameters.add(individualParameterNode);
    }
}
 
Example #20
Source File: SpringMVCRequestMappingHandler.java    From smart-doc with Apache License 2.0 4 votes vote down vote up
/**
 * handle spring request mapping
 *
 * @param serverUrl         server url
 * @param controllerBaseUrl spring mvc controller base url
 * @param method            JavaMethod
 * @return RequestMapping
 */
public RequestMapping handle(String serverUrl, String controllerBaseUrl, JavaMethod method) {
    List<JavaAnnotation> annotations = method.getAnnotations();
    String url;
    String methodType = null;
    String shortUrl = null;
    String mediaType = null;

    boolean deprecated = false;
    for (JavaAnnotation annotation : annotations) {
        String annotationName = annotation.getType().getName();
        Object produces = annotation.getNamedParameter("produces");
        if (produces != null) {
            mediaType = produces.toString();
        }
        if ("Deprecated".equals(annotationName)) {
            deprecated = true;
        }
        if (SpringMvcAnnotations.REQUEST_MAPPING.equals(annotationName) || DocGlobalConstants.REQUEST_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            Object nameParam = annotation.getNamedParameter("method");
            if (null != nameParam) {
                methodType = nameParam.toString();
                methodType = DocUtil.handleHttpMethod(methodType);
            } else {
                methodType = Methods.GET.getValue();
            }
        } else if (SpringMvcAnnotations.GET_MAPPING.equals(annotationName) || DocGlobalConstants.GET_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            methodType = Methods.GET.getValue();
        } else if (SpringMvcAnnotations.POST_MAPPING.equals(annotationName) || DocGlobalConstants.POST_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            methodType = Methods.POST.getValue();
        } else if (SpringMvcAnnotations.PUT_MAPPING.equals(annotationName) || DocGlobalConstants.PUT_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            methodType = Methods.PUT.getValue();

        } else if (SpringMvcAnnotations.PATCH_MAPPING.equals(annotationName) || DocGlobalConstants.PATCH_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            methodType = Methods.PATCH.getValue();

        } else if (SpringMvcAnnotations.DELETE_MAPPING.equals(annotationName) || DocGlobalConstants.DELETE_MAPPING_FULLY.equals(annotationName)) {
            shortUrl = DocUtil.handleMappingValue(annotation);
            methodType = Methods.DELETE.getValue();

        }
    }
    if (shortUrl != null) {
        if (null != method.getTagByName(IGNORE)) {
            return null;
        }
        shortUrl = StringUtil.removeQuotes(shortUrl);
        String[] urls = shortUrl.split(",");
        if (urls.length > 1) {
            url = DocUrlUtil.getMvcUrls(serverUrl, controllerBaseUrl, Arrays.asList(urls));
            shortUrl = DocUrlUtil.getMvcUrls("", controllerBaseUrl, Arrays.asList(urls));
        } else {
            url = UrlUtil.simplifyUrl(serverUrl + "/" + controllerBaseUrl + "/" + shortUrl);
            shortUrl = UrlUtil.simplifyUrl("/" + controllerBaseUrl + "/" + shortUrl);
        }
        return RequestMapping.builder().setMediaType(mediaType).setMethodType(methodType)
                .setUrl(url).setShortUrl(shortUrl).setDeprecated(deprecated);
    }
    return null;
}
 
Example #21
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 4 votes vote down vote up
private JavaAnnotation getPathAnnotation(JavaClass javaClass) {
    Optional<JavaAnnotation> optional = javaClass.getAnnotations()
            .stream().filter(a -> a.getType().getName().equals(PATH)).findAny();
    return optional.orElse(null);
}
 
Example #22
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 4 votes vote down vote up
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("onos.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);

    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);
    }
}
 
Example #23
Source File: DocJavaField.java    From smart-doc with Apache License 2.0 4 votes vote down vote up
public DocJavaField setAnnotations(List<JavaAnnotation> annotations) {
    this.annotations = annotations;
    return this;
}
 
Example #24
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 4 votes vote down vote up
private String getPath(JavaAnnotation annotation) {
    String path = annotation.getNamedParameter("value").toString();
    return path == null ? null : path.replaceAll("(^[\\\"/]*|[/\\\"]*$)", "");
}
 
Example #25
Source File: OnosSwaggerMojo.java    From onos with Apache License 2.0 4 votes vote down vote up
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.orElse(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().forEach(param -> {
                    schema.put("$ref", "#/definitions/" + param);
                });
                individualParameterNode.set("schema", schema);
            }
        }
        for (DocletTag p : javaMethod.getTagsByName("param")) {
            if (p.getValue().contains(annotationName)) {
                String description = "";
                if (p.getValue().split(" ", 2).length >= 2) {
                    description = p.getValue().split(" ", 2)[1].trim();
                    if (description.contains("optional")) {
                        required = false;
                    }
                } else {
                    getLog().warn(String.format(
                                "No description for parameter \"%s\" in " +
                                "method \"%s\" in %s (line %d)",
                                  p.getValue(), javaMethod.getName(),
                                  javaMethod.getDeclaringClass().getName(),
                                  javaMethod.getLineNumber()));
                }
                individualParameterNode.put("description", description);
            }
        }
        individualParameterNode.put("required", required);
        parameters.add(individualParameterNode);
    }
}