Search in sources :

Example 1 with JavaSource

use of com.thoughtworks.qdox.model.JavaSource in project sling by apache.

the class JcrOcmMojo method execute.

public void execute() throws MojoFailureException {
    boolean hasFailures = false;
    // prepare QDox and prime with the compile class path of the project
    JavaDocBuilder builder = new JavaDocBuilder();
    try {
        builder.getClassLibrary().addClassLoader(this.getCompileClassLoader());
    } catch (IOException ioe) {
        throw new MojoFailureException("Cannot prepare QDox");
    }
    // add the sources from the project
    for (Iterator i = this.project.getCompileSourceRoots().iterator(); i.hasNext(); ) {
        try {
            builder.addSourceTree(new File((String) i.next()));
        } catch (OutOfMemoryError oome) {
            // this may be the case for big sources and not enough VM mem
            // drop the builder to help GC now
            builder = null;
            // fail with some explanation
            throw new MojoFailureException("Failed analyzing source due to not enough memory, try setting Max Heap Size higher, e.g. using MAVEN_OPTS=-Xmx128m");
        }
    }
    // parse the sources and get them
    JavaSource[] javaSources = builder.getSources();
    List descriptors = new ArrayList();
    for (int i = 0; i < javaSources.length; i++) {
        JavaClass[] javaClasses = javaSources[i].getClasses();
        for (int j = 0; javaClasses != null && j < javaClasses.length; j++) {
            DocletTag tag = javaClasses[j].getTagByName(ClassDescriptor.TAG_CLASS_DESCRIPTOR);
            if (tag != null) {
                ClassDescriptor descriptor = this.createClassDescriptor(javaClasses[j]);
                if (descriptor != null) {
                    descriptors.add(descriptor);
                } else {
                    hasFailures = true;
                }
            }
        }
    }
    // after checking all classes, throw if there were any failures
    if (hasFailures) {
        throw new MojoFailureException("Jackrabbit OCM Descriptor parsing had failures (see log)");
    }
    // terminate if there is nothing to write
    if (descriptors.isEmpty()) {
        this.getLog().info("No Jackrabbit OCM Descriptors found in project");
        return;
    }
    // finally the descriptors have to be written ....
    if (StringUtils.isEmpty(this.finalName)) {
        this.getLog().error("Descriptor file name must not be empty");
        return;
    }
    // prepare the descriptor output file
    File descriptorFile = new File(new File(this.outputDirectory, "SLING-INF"), this.finalName);
    // ensure parent dir
    descriptorFile.getParentFile().mkdirs();
    this.getLog().info("Generating " + descriptors.size() + " OCM Mapping Descriptors to " + descriptorFile);
    // write out all the class descriptors in parse order
    FileOutputStream descriptorStream = null;
    XMLWriter xw = null;
    try {
        descriptorStream = new FileOutputStream(descriptorFile);
        xw = new XMLWriter(descriptorStream, false);
        xw.printElementStart("jackrabbit-ocm", false);
        for (Iterator di = descriptors.iterator(); di.hasNext(); ) {
            ClassDescriptor sd = (ClassDescriptor) di.next();
            sd.generate(xw);
        }
        xw.printElementEnd("jackrabbit-ocm");
    } catch (IOException ioe) {
        hasFailures = true;
        this.getLog().error("Cannot write descriptor to " + descriptorFile, ioe);
        throw new MojoFailureException("Failed to write descriptor to " + descriptorFile);
    } finally {
        IOUtil.close(xw);
        IOUtil.close(descriptorStream);
        // remove the descriptor file in case of write failure
        if (hasFailures) {
            descriptorFile.delete();
        }
    }
    // now add the descriptor file to the maven resources
    final String ourRsrcPath = this.outputDirectory.getAbsolutePath();
    boolean found = false;
    final Iterator rsrcIterator = this.project.getResources().iterator();
    while (!found && rsrcIterator.hasNext()) {
        final Resource rsrc = (Resource) rsrcIterator.next();
        found = rsrc.getDirectory().equals(ourRsrcPath);
    }
    if (!found) {
        final Resource resource = new Resource();
        resource.setDirectory(this.outputDirectory.getAbsolutePath());
        this.project.addResource(resource);
    }
    // and set include accordingly
    this.project.getProperties().setProperty("Sling-Mappings", "SLING-INF/" + this.finalName);
}
Also used : MojoFailureException(org.apache.maven.plugin.MojoFailureException) ArrayList(java.util.ArrayList) Resource(org.apache.maven.model.Resource) IOException(java.io.IOException) JavaDocBuilder(com.thoughtworks.qdox.JavaDocBuilder) JavaClass(com.thoughtworks.qdox.model.JavaClass) FileOutputStream(java.io.FileOutputStream) Iterator(java.util.Iterator) JavaSource(com.thoughtworks.qdox.model.JavaSource) ArrayList(java.util.ArrayList) List(java.util.List) File(java.io.File) DocletTag(com.thoughtworks.qdox.model.DocletTag)

Example 2 with JavaSource

use of com.thoughtworks.qdox.model.JavaSource in project geronimo-xbean by apache.

the class QdoxMappingLoader method loadElements.

private List<ElementMapping> loadElements(JavaDocBuilder builder) {
    JavaSource[] javaSources = builder.getSources();
    List<ElementMapping> elements = new ArrayList<ElementMapping>();
    for (JavaSource javaSource : javaSources) {
        if (javaSource.getClasses().length == 0) {
            log.info("No Java Classes defined in: " + javaSource.getURL());
        } else {
            JavaClass[] classes = javaSource.getClasses();
            for (JavaClass javaClass : classes) {
                ElementMapping element = loadElement(builder, javaClass);
                if (element != null && !javaClass.isAbstract()) {
                    elements.add(element);
                } else {
                    log.debug("No XML annotation found for type: " + javaClass.getFullyQualifiedName());
                }
            }
        }
    }
    return elements;
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaSource(com.thoughtworks.qdox.model.JavaSource) ArrayList(java.util.ArrayList)

Example 3 with JavaSource

use of com.thoughtworks.qdox.model.JavaSource 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 4 with JavaSource

use of com.thoughtworks.qdox.model.JavaSource in project geronimo-xbean by apache.

the class QdoxMappingLoader method loadElements.

private List<ElementMapping> loadElements(JavaDocBuilder builder) {
    JavaSource[] javaSources = builder.getSources();
    List<ElementMapping> elements = new ArrayList<ElementMapping>();
    for (JavaSource javaSource : javaSources) {
        if (javaSource.getClasses().length == 0) {
            log.info("No Java Classes defined in: " + javaSource.getURL());
        } else {
            JavaClass[] classes = javaSource.getClasses();
            for (JavaClass javaClass : classes) {
                ElementMapping element = loadElement(builder, javaClass);
                if (element != null && !javaClass.isAbstract()) {
                    elements.add(element);
                } else {
                    log.debug("No XML annotation found for type: " + javaClass.getFullyQualifiedName());
                }
            }
        }
    }
    return elements;
}
Also used : JavaClass(com.thoughtworks.qdox.model.JavaClass) JavaSource(com.thoughtworks.qdox.model.JavaSource) ArrayList(java.util.ArrayList)

Example 5 with JavaSource

use of com.thoughtworks.qdox.model.JavaSource 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)

Aggregations

JavaClass (com.thoughtworks.qdox.model.JavaClass)5 JavaSource (com.thoughtworks.qdox.model.JavaSource)5 File (java.io.File)3 ArrayList (java.util.ArrayList)3 JavaProjectBuilder (com.thoughtworks.qdox.JavaProjectBuilder)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 PrintStream (java.io.PrintStream)2 StringReader (java.io.StringReader)2 InvocationTargetException (java.lang.reflect.InvocationTargetException)2 URLClassLoader (java.net.URLClassLoader)2 Diagnostic (javax.tools.Diagnostic)2 DiagnosticCollector (javax.tools.DiagnosticCollector)2 JavaCompiler (javax.tools.JavaCompiler)2 CompilationTask (javax.tools.JavaCompiler.CompilationTask)2 JavaFileObject (javax.tools.JavaFileObject)2 SimpleJavaFileObject (javax.tools.SimpleJavaFileObject)2 JavaDocBuilder (com.thoughtworks.qdox.JavaDocBuilder)1 DocletTag (com.thoughtworks.qdox.model.DocletTag)1 FileOutputStream (java.io.FileOutputStream)1 IOException (java.io.IOException)1