Search in sources :

Example 41 with JavaClass

use of com.thoughtworks.qdox.model.JavaClass in project jsonschema2pojo by joelittlejohn.

the class JavaNameIT method inlineRequiredAppearsInFieldJavadoc.

@Test
public void inlineRequiredAppearsInFieldJavadoc() throws IOException {
    schemaRule.generateAndCompile("/schema/javaName/javaNameWithRequiredProperties.json", "com.example.required");
    File generatedJavaFileWithRequiredProperties = schemaRule.generated("com/example/required/JavaNameWithRequiredProperties.java");
    JavaDocBuilder javaDocBuilder = new JavaDocBuilder();
    javaDocBuilder.addSource(generatedJavaFileWithRequiredProperties);
    JavaClass classWithRequiredProperties = javaDocBuilder.getClassByName("com.example.required.JavaNameWithRequiredProperties");
    JavaField javaFieldWithoutJavaName = classWithRequiredProperties.getFieldByName("inlineRequiredPropertyWithoutJavaName");
    JavaField javaFieldWithJavaName = classWithRequiredProperties.getFieldByName("inlineRequiredPropertyWithoutJavaName");
    assertThat(javaFieldWithoutJavaName.getComment(), containsString("(Required)"));
    assertThat(javaFieldWithJavaName.getComment(), containsString("(Required)"));
}
Also used : JavaField(com.thoughtworks.qdox.model.JavaField) JavaClass(com.thoughtworks.qdox.model.JavaClass) File(java.io.File) JavaDocBuilder(com.thoughtworks.qdox.JavaDocBuilder) Test(org.junit.Test)

Example 42 with JavaClass

use of com.thoughtworks.qdox.model.JavaClass in project zeppelin by apache.

the class JavaSourceFromString method execute.

public static String execute(String generatedClassName, String code) throws Exception {
    JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
    DiagnosticCollector<JavaFileObject> diagnostics = new DiagnosticCollector<JavaFileObject>();
    // Java parasing
    JavaProjectBuilder builder = new JavaProjectBuilder();
    JavaSource src = builder.addSource(new StringReader(code));
    // get all classes in code (paragraph)
    List<JavaClass> classes = src.getClasses();
    String mainClassName = null;
    // Searching for class containing Main method
    for (int i = 0; i < classes.size(); i++) {
        boolean hasMain = false;
        for (int j = 0; j < classes.get(i).getMethods().size(); j++) {
            if (classes.get(i).getMethods().get(j).getName().equals("main") && classes.get(i).getMethods().get(j).isStatic()) {
                mainClassName = classes.get(i).getName();
                hasMain = true;
                break;
            }
        }
        if (hasMain == true) {
            break;
        }
    }
    // if there isn't Main method, will retuen error
    if (mainClassName == null) {
        logger.error("Exception for Main method", "There isn't any class " + "containing static main method.");
        throw new Exception("There isn't any class containing static main method.");
    }
    // replace name of class containing Main method with generated name
    code = code.replace(mainClassName, generatedClassName);
    JavaFileObject file = new JavaSourceFromString(generatedClassName, code.toString());
    Iterable<? extends JavaFileObject> compilationUnits = Arrays.asList(file);
    ByteArrayOutputStream baosOut = new ByteArrayOutputStream();
    ByteArrayOutputStream baosErr = new ByteArrayOutputStream();
    // Creating new stream to get the output data
    PrintStream newOut = new PrintStream(baosOut);
    PrintStream newErr = new PrintStream(baosErr);
    // Save the old System.out!
    PrintStream oldOut = System.out;
    PrintStream oldErr = System.err;
    // Tell Java to use your special stream
    System.setOut(newOut);
    System.setErr(newErr);
    CompilationTask task = compiler.getTask(null, null, diagnostics, null, null, compilationUnits);
    // executing the compilation process
    boolean success = task.call();
    // if success is false will get error
    if (!success) {
        for (Diagnostic diagnostic : diagnostics.getDiagnostics()) {
            if (diagnostic.getLineNumber() == -1) {
                continue;
            }
            System.err.println("line " + diagnostic.getLineNumber() + " : " + diagnostic.getMessage(null));
        }
        System.out.flush();
        System.err.flush();
        System.setOut(oldOut);
        System.setErr(oldErr);
        logger.error("Exception in Interpreter while compilation", baosErr.toString());
        throw new Exception(baosErr.toString());
    } else {
        try {
            // creating new class loader
            URLClassLoader classLoader = URLClassLoader.newInstance(new URL[] { new File("").toURI().toURL() });
            // execute the Main method
            Class.forName(generatedClassName, true, classLoader).getDeclaredMethod("main", new Class[] { String[].class }).invoke(null, new Object[] { null });
            System.out.flush();
            System.err.flush();
            // set the stream to old stream
            System.setOut(oldOut);
            System.setErr(oldErr);
            return baosOut.toString();
        } catch (ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            logger.error("Exception in Interpreter while execution", e);
            System.err.println(e);
            e.printStackTrace(newErr);
            throw new Exception(baosErr.toString(), e);
        } finally {
            System.out.flush();
            System.err.flush();
            System.setOut(oldOut);
            System.setErr(oldErr);
        }
    }
}
Also used : Diagnostic(javax.tools.Diagnostic) SimpleJavaFileObject(javax.tools.SimpleJavaFileObject) JavaFileObject(javax.tools.JavaFileObject) JavaSource(com.thoughtworks.qdox.model.JavaSource) StringReader(java.io.StringReader) DiagnosticCollector(javax.tools.DiagnosticCollector) JavaProjectBuilder(com.thoughtworks.qdox.JavaProjectBuilder) PrintStream(java.io.PrintStream) JavaCompiler(javax.tools.JavaCompiler) ByteArrayOutputStream(java.io.ByteArrayOutputStream) InvocationTargetException(java.lang.reflect.InvocationTargetException) CompilationTask(javax.tools.JavaCompiler.CompilationTask) InvocationTargetException(java.lang.reflect.InvocationTargetException) JavaClass(com.thoughtworks.qdox.model.JavaClass) URLClassLoader(java.net.URLClassLoader) JavaClass(com.thoughtworks.qdox.model.JavaClass) File(java.io.File)

Example 43 with JavaClass

use of com.thoughtworks.qdox.model.JavaClass in project maven-plugins by apache.

the class AbstractFixJavadocMojo method addMissingJavadocTags.

/**
 * Add missing tags not already written.
 *
 * @param sb             not null
 * @param entity         not null
 * @param indent         not null
 * @param isJavaExecutable
 * @param javaEntityTags not null
 * @throws MojoExecutionException if any
 */
private void addMissingJavadocTags(final StringBuilder sb, final JavaAnnotatedElement entity, final String indent, final boolean isJavaExecutable, final JavaEntityTags javaEntityTags) throws MojoExecutionException {
    if (isJavaExecutable) {
        JavaExecutable javaExecutable = (JavaExecutable) entity;
        if (fixTag(PARAM_TAG)) {
            if (javaExecutable.getParameters() != null) {
                for (JavaParameter javaParameter : javaExecutable.getParameters()) {
                    if (javaEntityTags.getJavadocParamTag(javaParameter.getName(), true) == null) {
                        appendDefaultParamTag(sb, indent, javaParameter);
                    }
                }
            }
            // is generic?
            if (javaExecutable.getTypeParameters() != null) {
                for (JavaTypeVariable<JavaGenericDeclaration> typeParam : javaExecutable.getTypeParameters()) {
                    if (javaEntityTags.getJavadocParamTag("<" + typeParam.getName() + ">", true) == null) {
                        appendDefaultParamTag(sb, indent, typeParam);
                    }
                }
            }
        }
        if (javaExecutable instanceof JavaMethod) {
            JavaMethod javaMethod = (JavaMethod) javaExecutable;
            if (fixTag(RETURN_TAG) && StringUtils.isEmpty(javaEntityTags.getJavadocReturnTag()) && javaMethod.getReturns() != null && !javaMethod.getReturns().isVoid()) {
                appendDefaultReturnTag(sb, indent, javaMethod);
            }
        }
        if (fixTag(THROWS_TAG) && javaExecutable.getExceptions() != null) {
            for (JavaType exception : javaExecutable.getExceptions()) {
                if (javaEntityTags.getJavadocThrowsTag(exception.getValue(), true) == null) {
                    appendDefaultThrowsTag(sb, indent, exception);
                }
            }
        }
    } else {
        if (!javaEntityTags.getNamesTags().contains(AUTHOR_TAG)) {
            appendDefaultAuthorTag(sb, indent);
        }
        if (!javaEntityTags.getNamesTags().contains(VERSION_TAG)) {
            appendDefaultVersionTag(sb, indent);
        }
    }
    if (fixTag(SINCE_TAG) && !javaEntityTags.getNamesTags().contains(SINCE_TAG)) {
        if (!isJavaExecutable) {
            if (!ignoreClirr) {
                if (isNewClassFromLastVersion((JavaClass) entity)) {
                    appendDefaultSinceTag(sb, indent);
                }
            } else {
                appendDefaultSinceTag(sb, indent);
                addSinceClasses((JavaClass) entity);
            }
        } else {
            if (!ignoreClirr) {
                if (isNewMethodFromLastRevision((JavaExecutable) entity)) {
                    appendDefaultSinceTag(sb, indent);
                }
            } else if (sinceClasses != null) {
                if (entity instanceof JavaMember && !sinceClassesContains(((JavaMember) entity).getDeclaringClass())) {
                    appendDefaultSinceTag(sb, indent);
                } else if (entity instanceof JavaClass && !sinceClassesContains(((JavaClass) entity).getDeclaringClass())) {
                    appendDefaultSinceTag(sb, indent);
                }
            }
        }
    }
}
Also used : JavaType(com.thoughtworks.qdox.model.JavaType) JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaGenericDeclaration(com.thoughtworks.qdox.model.JavaGenericDeclaration) JavaParameter(com.thoughtworks.qdox.model.JavaParameter) JavaMethod(com.thoughtworks.qdox.model.JavaMethod) JavaMember(com.thoughtworks.qdox.model.JavaMember) JavaExecutable(com.thoughtworks.qdox.model.JavaExecutable)

Example 44 with JavaClass

use of com.thoughtworks.qdox.model.JavaClass in project maven-plugins by apache.

the class FixJavadocMojoTest method testJavadocCommentJdk5.

/**
 * @throws Throwable if any
 */
public void testJavadocCommentJdk5() throws Exception {
    String content = "/**" + EOL + " * Dummy Class." + EOL + " */" + EOL + "public class DummyClass" + EOL + "{" + EOL + "    /**" + EOL + "     * Dummy method." + EOL + "     *" + EOL + "     * @param <K>  The Key type for the method" + EOL + "     * @param <V>  The Value type for the method" + EOL + "     * @param name The name." + EOL + "     * @return A map configured." + EOL + "     */" + EOL + "    public <K, V> java.util.Map<K, V> dummyMethod( String name )" + EOL + "    {" + EOL + "        return null;" + EOL + "    }" + EOL + "}";
    JavaProjectBuilder builder = new JavaProjectBuilder();
    builder.setEncoding("UTF-8");
    JavaClass clazz = builder.addSource(new StringReader(content)).getClassByName("DummyClass");
    JavaMethod javaMethod = clazz.getMethods().get(0);
    String methodJavadoc = AbstractFixJavadocMojo.getJavadocComment(content, javaMethod);
    assertEquals("     * Dummy method." + EOL + "     *", methodJavadoc);
    assertEquals(4, javaMethod.getTags().size());
    AbstractFixJavadocMojo mojoInstance = new FixJavadocMojo();
    setVariableValueToObject(mojoInstance, "fixTagsSplitted", new String[] { "all" });
    DocletTag tag = javaMethod.getTags().get(0);
    String tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag);
    assertEquals("     * @param <K>  The Key type for the method", tagJavadoc);
    tag = javaMethod.getTags().get(1);
    tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag);
    assertEquals("     * @param <V>  The Value type for the method", tagJavadoc);
    tag = javaMethod.getTags().get(2);
    tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag);
    assertEquals("     * @param name The name.", tagJavadoc);
    tag = javaMethod.getTags().get(3);
    tagJavadoc = mojoInstance.getJavadocComment(content, javaMethod, tag);
    assertEquals("     * @return A map configured.", tagJavadoc);
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) StringReader(java.io.StringReader) JavaMethod(com.thoughtworks.qdox.model.JavaMethod) JavaProjectBuilder(com.thoughtworks.qdox.JavaProjectBuilder) DocletTag(com.thoughtworks.qdox.model.DocletTag)

Example 45 with JavaClass

use of com.thoughtworks.qdox.model.JavaClass in project maven-plugins by apache.

the class AbstractFixJavadocMojoTest method testReplaceLinkTags_twoLinks.

public void testReplaceLinkTags_twoLinks() throws Throwable {
    String comment = "/** Use {@link ConnectException} instead of {@link Exception} */";
    String source = "import java.net.ConnectException;\n" + comment + "\n" + "public class TwoLinks {}";
    JavaClass clazz = getJavaSource(source).getClassByName("TwoLinks");
    String newComment = AbstractFixJavadocMojo.replaceLinkTags(comment, clazz);
    assertEquals("/** Use {@link java.net.ConnectException} instead of {@link java.lang.Exception} */", newComment);
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass)

Aggregations

JavaClass (com.thoughtworks.qdox.model.JavaClass)48 AbstractInheritableJavaEntity (com.thoughtworks.qdox.model.AbstractInheritableJavaEntity)12 JavaMethod (com.thoughtworks.qdox.model.JavaMethod)12 DocletTag (com.thoughtworks.qdox.model.DocletTag)10 JavaDocBuilder (com.thoughtworks.qdox.JavaDocBuilder)6 File (java.io.File)6 StringReader (java.io.StringReader)6 JavaParameter (com.thoughtworks.qdox.model.JavaParameter)5 JavaSource (com.thoughtworks.qdox.model.JavaSource)5 ArrayList (java.util.ArrayList)5 JavaProjectBuilder (com.thoughtworks.qdox.JavaProjectBuilder)4 BeanProperty (com.thoughtworks.qdox.model.BeanProperty)4 JavaField (com.thoughtworks.qdox.model.JavaField)3 HashSet (java.util.HashSet)3 List (java.util.List)3 Test (org.junit.Test)3 AbstractJavaEntity (com.thoughtworks.qdox.model.AbstractJavaEntity)2 JavaExecutable (com.thoughtworks.qdox.model.JavaExecutable)2 JavaMember (com.thoughtworks.qdox.model.JavaMember)2 JavaType (com.thoughtworks.qdox.model.JavaType)2