Search in sources :

Example 26 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 27 with JavaClass

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

the class AbstractFixJavadocMojoTest method testReplaceLinkTags_OnlyAnchor.

public void testReplaceLinkTags_OnlyAnchor() throws Throwable {
    String comment = "/** There's a {@link #getClass()} but no setClass() */";
    AbstractInheritableJavaEntity entity = spy(new PrivateAbstractInheritableJavaEntity());
    JavaClass clazz = mock(JavaClass.class);
    when(entity.getParentClass()).thenReturn(clazz);
    when(clazz.resolveType("ConnectException")).thenReturn("java.net.ConnectException");
    when(clazz.resolveType("Exception")).thenReturn("java.lang.Exception");
    String newComment = (String) PrivateAccessor.invoke(AbstractFixJavadocMojo.class, "replaceLinkTags", new Class[] { String.class, AbstractInheritableJavaEntity.class }, new Object[] { comment, entity });
    assertEquals("/** There's a {@link #getClass()} but no setClass() */", newComment);
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaClass(com.thoughtworks.qdox.model.JavaClass) AbstractInheritableJavaEntity(com.thoughtworks.qdox.model.AbstractInheritableJavaEntity)

Example 28 with JavaClass

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

the class AbstractFixJavadocMojoTest method testReplaceLinkTags_noLinkTag.

public void testReplaceLinkTags_noLinkTag() throws Throwable {
    String comment = "/** @see ConnectException */";
    AbstractInheritableJavaEntity entity = spy(new PrivateAbstractInheritableJavaEntity());
    JavaClass clazz = mock(JavaClass.class);
    when(entity.getParentClass()).thenReturn(clazz);
    when(clazz.resolveType("ConnectException")).thenReturn("java.net.ConnectException");
    String newComment = (String) PrivateAccessor.invoke(AbstractFixJavadocMojo.class, "replaceLinkTags", new Class[] { String.class, AbstractInheritableJavaEntity.class }, new Object[] { comment, entity });
    assertEquals("/** @see ConnectException */", newComment);
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaClass(com.thoughtworks.qdox.model.JavaClass) AbstractInheritableJavaEntity(com.thoughtworks.qdox.model.AbstractInheritableJavaEntity)

Example 29 with JavaClass

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

the class AbstractFixJavadocMojo method replaceLinkTags.

private static String replaceLinkTags(String comment, AbstractInheritableJavaEntity entity) {
    StringBuilder resolvedComment = new StringBuilder();
    // scan comment for {@link someClassName} and try to resolve this
    Matcher linktagMatcher = Pattern.compile("\\{@link\\s").matcher(comment);
    int startIndex = 0;
    while (linktagMatcher.find()) {
        int startName = linktagMatcher.end();
        resolvedComment.append(comment.substring(startIndex, startName));
        int endName = comment.indexOf("}", startName);
        if (endName >= 0) {
            String name;
            String link = comment.substring(startName, endName);
            int hashIndex = link.indexOf('#');
            if (hashIndex >= 0) {
                name = link.substring(0, hashIndex);
            } else {
                name = link;
            }
            if (StringUtils.isNotBlank(name)) {
                String typeName;
                if (entity instanceof JavaClass) {
                    typeName = ((JavaClass) entity).resolveType(name.trim());
                } else {
                    typeName = entity.getParentClass().resolveType(name.trim());
                }
                if (typeName == null) {
                    typeName = name.trim();
                } else {
                    typeName = typeName.replaceAll("\\$", ".");
                }
                //adjust name for inner classes
                resolvedComment.append(typeName);
            }
            if (hashIndex >= 0) {
                resolvedComment.append(link.substring(hashIndex).trim());
            }
            startIndex = endName;
        } else {
            startIndex = startName;
        }
    }
    resolvedComment.append(comment.substring(startIndex));
    return resolvedComment.toString();
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) Matcher(java.util.regex.Matcher)

Example 30 with JavaClass

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

the class AbstractFixJavadocMojo method addDefaultJavadocTags.

/**
     * @param sb           not null
     * @param entity       not null
     * @param indent       not null
     * @param isJavaMethod
     * @throws MojoExecutionException if any
     */
private void addDefaultJavadocTags(final StringBuilder sb, final AbstractInheritableJavaEntity entity, final String indent, final boolean isJavaMethod) throws MojoExecutionException {
    boolean separatorAdded = false;
    if (isJavaMethod) {
        JavaMethod javaMethod = (JavaMethod) entity;
        if (fixTag(PARAM_TAG) && javaMethod.getParameters() != null) {
            for (int i = 0; i < javaMethod.getParameters().length; i++) {
                JavaParameter javaParameter = javaMethod.getParameters()[i];
                separatorAdded = appendDefaultParamTag(sb, indent, separatorAdded, javaParameter);
            }
        }
        if (fixTag(RETURN_TAG)) {
            if (javaMethod.getReturns() != null && !javaMethod.getReturns().isVoid()) {
                separatorAdded = appendDefaultReturnTag(sb, indent, separatorAdded, javaMethod);
            }
        }
        if (fixTag(THROWS_TAG) && javaMethod.getExceptions() != null) {
            for (int i = 0; i < javaMethod.getExceptions().length; i++) {
                Type exception = javaMethod.getExceptions()[i];
                separatorAdded = appendDefaultThrowsTag(sb, indent, separatorAdded, exception);
            }
        }
    } else {
        separatorAdded = appendDefaultAuthorTag(sb, indent, separatorAdded);
        separatorAdded = appendDefaultVersionTag(sb, indent, separatorAdded);
    }
    if (fixTag(SINCE_TAG)) {
        if (!isJavaMethod) {
            JavaClass javaClass = (JavaClass) entity;
            if (!ignoreClirr) {
                if (isNewClassFromLastVersion(javaClass)) {
                    separatorAdded = appendDefaultSinceTag(sb, indent, separatorAdded);
                }
            } else {
                separatorAdded = appendDefaultSinceTag(sb, indent, separatorAdded);
                addSinceClasses(javaClass);
            }
        } else {
            JavaMethod javaMethod = (JavaMethod) entity;
            if (!ignoreClirr) {
                if (isNewMethodFromLastRevision(javaMethod)) {
                    separatorAdded = appendDefaultSinceTag(sb, indent, separatorAdded);
                }
            } else {
                if (sinceClasses != null && !sinceClassesContains(javaMethod.getParentClass())) {
                    separatorAdded = appendDefaultSinceTag(sb, indent, separatorAdded);
                }
            }
        }
    }
}
Also used : Type(com.thoughtworks.qdox.model.Type) JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaMethod(com.thoughtworks.qdox.model.JavaMethod) JavaParameter(com.thoughtworks.qdox.model.JavaParameter)

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