Search in sources :

Example 1 with DependencyType

use of org.stjs.generator.name.DependencyType in project st-js by st-js.

the class ClassWriter method getInterfaces.

/**
 * @return the list of implemented interfaces. for intefaces, the super class goes also in the interfaces list
 */
private JS getInterfaces(ClassTree clazz, GenerationContext<JS> context) {
    Element type = TreeUtils.elementFromDeclaration(clazz);
    DependencyType depType = getDependencyTypeForClassDef(type);
    List<JS> ifaces = new ArrayList<JS>();
    for (Tree iface : clazz.getImplementsClause()) {
        TreeWrapper<Tree, JS> ifaceType = context.getCurrentWrapper().child(iface);
        if (!ifaceType.isSyntheticType()) {
            ifaces.add(context.js().name(ifaceType.getTypeName(depType)));
        }
    }
    if (clazz.getExtendsClause() != null && type.getKind() == ElementKind.INTERFACE) {
        TreeWrapper<Tree, JS> superType = context.getCurrentWrapper().child(clazz.getExtendsClause());
        if (!superType.isSyntheticType()) {
            ifaces.add(0, context.js().name(superType.getTypeName(DependencyType.EXTENDS)));
        }
    }
    return context.js().array(ifaces);
}
Also used : VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) DependencyType(org.stjs.generator.name.DependencyType) ArrayList(java.util.ArrayList) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) AssignmentTree(com.sun.source.tree.AssignmentTree) NewArrayTree(com.sun.source.tree.NewArrayTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) BlockTree(com.sun.source.tree.BlockTree)

Example 2 with DependencyType

use of org.stjs.generator.name.DependencyType in project st-js by st-js.

the class Generator method generateJavascript.

/**
 * <p>generateJavascript.</p>
 *
 * @return the list of imports needed by the generated class
 * @param className a {@link java.lang.String} object.
 * @param sourceFolder a {@link java.io.File} object.
 * @throws org.stjs.generator.JavascriptFileGenerationException if any.
 * @throws org.stjs.generator.JavascriptFileGenerationException if any.
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public ClassWithJavascript generateJavascript(String className, File sourceFolder) throws JavascriptFileGenerationException {
    Class<?> clazz = ClassUtils.getClazz(config.getStjsClassLoader(), className);
    if (ClassUtils.isBridge(config.getStjsClassLoader(), clazz)) {
        return new BridgeClass(config.getClassResolver(), clazz);
    }
    File inputFile = getInputFile(sourceFolder, className);
    File outputFile = getOutputFile(config.getGenerationFolder().getGeneratedSourcesAbsolutePath(), className);
    JavaScriptNameProvider names = new DefaultJavaScriptNameProvider();
    GenerationPlugins<Object> currentClassPlugins = plugins.forClass(clazz);
    GenerationContext<Object> context = new GenerationContext<Object>(inputFile, config, names, null, cacheAnnotations, getJavaScriptBuilder());
    CompilationUnitTree cu = parseAndResolve(inputFile, context, config.getStjsClassLoader(), config.getSourceEncoding());
    // check the code
    Timers.start("check-java");
    currentClassPlugins.getCheckVisitor().scan(cu, (GenerationContext) context);
    context.getChecks().check();
    Timers.end("check-java");
    // generate the javascript code
    Timers.start("write-js-ast");
    Object javascriptRoot = currentClassPlugins.getWriterVisitor().scan(cu, context);
    // check for any error arriving during writing
    context.getChecks().check();
    Timers.end("write-js-ast");
    Class<?> javaClass = config.getClassResolver().resolveJavaClass(className);
    STJSClass stjsClass = new STJSClass(config.getClassResolver(), config.getTargetFolder(), javaClass);
    Map<String, DependencyType> resolvedClasses = new LinkedHashMap<String, DependencyType>(names.getResolvedTypes());
    resolvedClasses.remove(className);
    stjsClass.setDependencies(resolvedClasses);
    stjsClass.setGeneratedJavascriptFile(getRuntimeUri(className));
    TypeElement classElement = context.getElements().getTypeElement(clazz.getCanonicalName());
    stjsClass.setJavascriptNamespace(context.wrap(classElement).getNamespace());
    // dump the ast to a file
    taskExecutor.execute(new DumpFilesTask<>(outputFile, context, javascriptRoot, stjsClass));
    return stjsClass;
}
Also used : DefaultJavaScriptNameProvider(org.stjs.generator.name.DefaultJavaScriptNameProvider) JavaScriptNameProvider(org.stjs.generator.name.JavaScriptNameProvider) CompilationUnitTree(com.sun.source.tree.CompilationUnitTree) TypeElement(javax.lang.model.element.TypeElement) LinkedHashMap(java.util.LinkedHashMap) DefaultJavaScriptNameProvider(org.stjs.generator.name.DefaultJavaScriptNameProvider) DependencyType(org.stjs.generator.name.DependencyType) JavaFileObject(javax.tools.JavaFileObject) File(java.io.File)

Example 3 with DependencyType

use of org.stjs.generator.name.DependencyType in project st-js by st-js.

the class AbstractSTJSMojo method packFiles.

/**
 * packs all the files in a single file
 *
 * @param generator
 *            a {@link org.stjs.generator.Generator} object.
 * @param gendir
 *            a {@link org.stjs.generator.GenerationDirectory} object.
 * @throws org.apache.maven.plugin.MojoFailureException
 * @throws org.apache.maven.plugin.MojoExecutionException
 */
protected void packFiles(Generator generator, GenerationDirectory gendir) throws MojoFailureException, MojoExecutionException {
    if (!pack) {
        return;
    }
    OutputStream allSourcesFile = null;
    Writer packMapStream = null;
    ClassLoader builtProjectClassLoader = getBuiltProjectClassLoader();
    Map<String, File> currentProjectsFiles = new HashMap<String, File>();
    // pack the files
    try {
        DirectedGraph<String, DefaultEdge> dependencyGraph = new DefaultDirectedGraph<String, DefaultEdge>(DefaultEdge.class);
        File outputFile = new File(gendir.getGeneratedSourcesAbsolutePath(), project.getArtifactId() + ".js");
        allSourcesFile = new BufferedOutputStream(new FileOutputStream(outputFile));
        for (String sourceRoot : getCompileSourceRoots()) {
            File sourceDir = new File(sourceRoot);
            List<File> sources = new ArrayList<File>();
            SourceMapping mapping = new SuffixMapping(".java", ".js");
            SourceMapping stjsMapping = new SuffixMapping(".java", ".stjs");
            // take all the files
            sources = accumulateSources(gendir, sourceDir, mapping, stjsMapping, Integer.MIN_VALUE);
            for (File source : sources) {
                File absoluteTarget = (File) mapping.getTargetFiles(gendir.getGeneratedSourcesAbsolutePath(), source.getPath()).iterator().next();
                String className = getClassNameForSource(source.getPath());
                if (!absoluteTarget.exists()) {
                    getLog().debug(className + " is a bridge. Don't add it to the pack file");
                    continue;
                }
                // add this file to the hashmap to know that this class is part of the project
                currentProjectsFiles.put(className, absoluteTarget);
                if (getLog().isDebugEnabled()) {
                    getLog().debug("Packing " + absoluteTarget);
                }
                ClassWithJavascript cjs = generator.getExistingStjsClass(builtProjectClassLoader, builtProjectClassLoader.loadClass(className));
                dependencyGraph.addVertex(className);
                for (Map.Entry<ClassWithJavascript, DependencyType> dep : cjs.getDirectDependencyMap().entrySet()) {
                    if (dep.getKey() instanceof STJSClass) {
                        dependencyGraph.addVertex(dep.getKey().getJavaClassName());
                        if (dep.getValue() != DependencyType.OTHER) {
                            dependencyGraph.addEdge(dep.getKey().getJavaClassName(), className);
                        }
                    }
                }
            }
        }
        // check for cycles
        detectCycles(dependencyGraph);
        // dump all the files in the dependency order in the pack file
        SourceMapGeneratorV3 packSourceMap = (SourceMapGeneratorV3) SourceMapGeneratorFactory.getInstance(SourceMapFormat.V3);
        int currentLine = 0;
        Iterator<String> it = new TopologicalOrderIterator<String, DefaultEdge>(dependencyGraph);
        while (it.hasNext()) {
            File targetFile = currentProjectsFiles.get(it.next());
            // target file is absolute
            if (targetFile != null) {
                // for this project's files
                if (generateSourceMap) {
                    currentLine = SourceMapUtils.appendFileSkipSourceMap(gendir.getGeneratedSourcesAbsolutePath(), allSourcesFile, targetFile, currentLine, packSourceMap, sourceEncoding);
                } else {
                    Files.copy(targetFile, allSourcesFile);
                }
                allSourcesFile.flush();
            }
        }
        if (generateSourceMap) {
            File packMapFile = new File(gendir.getGeneratedSourcesAbsolutePath(), project.getArtifactId() + ".map");
            packMapStream = new BufferedWriter(new FileWriter(packMapFile));
            packSourceMap.appendTo(packMapStream, project.getArtifactId() + ".js");
            allSourcesFile.write(("//# sourceMappingURL=" + project.getArtifactId() + ".map\n").getBytes());
            allSourcesFile.flush();
        }
    } catch (Exception ex) {
        throw new MojoFailureException("Error when packing files:" + ex.getMessage(), ex);
    } finally {
        try {
            Closeables.close(allSourcesFile, true);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "IOException should not have been thrown.", e);
        }
        try {
            Closeables.close(packMapStream, true);
        } catch (IOException e) {
            LOG.log(Level.SEVERE, "IOException should not have been thrown.", e);
        }
    }
}
Also used : HashMap(java.util.HashMap) DefaultDirectedGraph(org.jgrapht.graph.DefaultDirectedGraph) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileWriter(java.io.FileWriter) ArrayList(java.util.ArrayList) TopologicalOrderIterator(org.jgrapht.traverse.TopologicalOrderIterator) STJSClass(org.stjs.generator.STJSClass) SuffixMapping(org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping) SourceMapGeneratorV3(com.google.debugging.sourcemap.SourceMapGeneratorV3) BufferedWriter(java.io.BufferedWriter) DependencyType(org.stjs.generator.name.DependencyType) URLClassLoader(java.net.URLClassLoader) BufferedOutputStream(java.io.BufferedOutputStream) MojoFailureException(org.apache.maven.plugin.MojoFailureException) DefaultEdge(org.jgrapht.graph.DefaultEdge) IOException(java.io.IOException) MultipleFileGenerationException(org.stjs.generator.MultipleFileGenerationException) DependencyResolutionRequiredException(org.apache.maven.artifact.DependencyResolutionRequiredException) JavascriptFileGenerationException(org.stjs.generator.JavascriptFileGenerationException) IOException(java.io.IOException) InclusionScanException(org.codehaus.plexus.compiler.util.scan.InclusionScanException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) FileOutputStream(java.io.FileOutputStream) ClassWithJavascript(org.stjs.generator.ClassWithJavascript) File(java.io.File) SourceMapping(org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping) Map(java.util.Map) HashMap(java.util.HashMap) Writer(java.io.Writer) BufferedWriter(java.io.BufferedWriter) FileWriter(java.io.FileWriter)

Example 4 with DependencyType

use of org.stjs.generator.name.DependencyType in project st-js by st-js.

the class ClassWriter method getSuperClass.

/**
 * @return the node to put in the super class. for intefaces, the super class goes also in the interfaces list
 */
private JS getSuperClass(ClassTree clazz, GenerationContext<JS> context) {
    Element type = TreeUtils.elementFromDeclaration(clazz);
    if (clazz.getExtendsClause() == null || type.getKind() == ElementKind.INTERFACE) {
        // no super class found
        return context.js().keyword(Keyword.NULL);
    }
    TreeWrapper<Tree, JS> superType = context.getCurrentWrapper().child(clazz.getExtendsClause());
    if (superType.isSyntheticType()) {
        return context.js().keyword(Keyword.NULL);
    }
    DependencyType depType = getDependencyTypeForClassDef(type);
    return context.js().name(superType.getTypeName(depType));
}
Also used : VariableElement(javax.lang.model.element.VariableElement) TypeElement(javax.lang.model.element.TypeElement) Element(javax.lang.model.element.Element) DependencyType(org.stjs.generator.name.DependencyType) AnnotationTree(com.sun.source.tree.AnnotationTree) MethodTree(com.sun.source.tree.MethodTree) VariableTree(com.sun.source.tree.VariableTree) AssignmentTree(com.sun.source.tree.AssignmentTree) NewArrayTree(com.sun.source.tree.NewArrayTree) Tree(com.sun.source.tree.Tree) ClassTree(com.sun.source.tree.ClassTree) ExpressionTree(com.sun.source.tree.ExpressionTree) BlockTree(com.sun.source.tree.BlockTree)

Aggregations

DependencyType (org.stjs.generator.name.DependencyType)4 TypeElement (javax.lang.model.element.TypeElement)3 AnnotationTree (com.sun.source.tree.AnnotationTree)2 AssignmentTree (com.sun.source.tree.AssignmentTree)2 BlockTree (com.sun.source.tree.BlockTree)2 ClassTree (com.sun.source.tree.ClassTree)2 ExpressionTree (com.sun.source.tree.ExpressionTree)2 MethodTree (com.sun.source.tree.MethodTree)2 NewArrayTree (com.sun.source.tree.NewArrayTree)2 Tree (com.sun.source.tree.Tree)2 VariableTree (com.sun.source.tree.VariableTree)2 File (java.io.File)2 ArrayList (java.util.ArrayList)2 Element (javax.lang.model.element.Element)2 VariableElement (javax.lang.model.element.VariableElement)2 SourceMapGeneratorV3 (com.google.debugging.sourcemap.SourceMapGeneratorV3)1 CompilationUnitTree (com.sun.source.tree.CompilationUnitTree)1 BufferedOutputStream (java.io.BufferedOutputStream)1 BufferedWriter (java.io.BufferedWriter)1 FileOutputStream (java.io.FileOutputStream)1