Search in sources :

Example 1 with GenerationDirectory

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

the class MainSTJSMojo method getGeneratedSourcesDirectory.

/**
 * {@inheritDoc}
 */
@Override
public GenerationDirectory getGeneratedSourcesDirectory() throws MojoExecutionException {
    if (webjar) {
        if (!project.getPackaging().equals("jar")) {
            throw new MojoExecutionException("<webjar>true</webjar> is only compatible with <packaging>jar</packaging>");
        } else if (generatedSourcesDirectory != null) {
            throw new MojoExecutionException("Cannot set <generatedSourcesDirectory> when <webjar>true</webjar> is set");
        }
    }
    Path generatedSourcesPath;
    if (generatedSourcesDirectory == null) {
        if (webjar) {
            // default path for webjar packaging
            generatedSourcesPath = // 
            Paths.get(// 
            project.getBuild().getOutputDirectory(), // 
            "META-INF", // 
            "resources", // 
            "webjars", // 
            project.getArtifactId(), // 
            project.getVersion());
        } else if (project.getPackaging().equals("jar")) {
            // default path for .jar packaging
            generatedSourcesPath = Paths.get(project.getBuild().getOutputDirectory());
        } else {
            // default path for .war packaging
            generatedSourcesPath = Paths.get(project.getBuild().getDirectory(), project.getBuild().getFinalName(), "generated-js");
        }
    } else {
        // user specified path
        generatedSourcesPath = generatedSourcesDirectory.toPath();
    }
    generatedSourcesPath = generatedSourcesPath.toAbsolutePath();
    URI generatedSourcesRuntimePath;
    try {
        if (webjar) {
            // webjar packaging
            generatedSourcesRuntimePath = new URI("webjar:/");
        } else if (project.getPackaging().equals("jar")) {
            // .jar packaging
            Path outputDir = Paths.get(project.getBuild().getOutputDirectory()).toAbsolutePath();
            Path classpathOuputDir = outputDir.relativize(generatedSourcesPath);
            generatedSourcesRuntimePath = new URI("classpath:/").resolve(classpathOuputDir.toString());
        } else {
            // .war packaging
            Path artifactPath = Paths.get(project.getBuild().getDirectory(), project.getBuild().getFinalName());
            String jsPath = artifactPath.relativize(generatedSourcesPath).toString();
            if (!jsPath.startsWith("/")) {
                jsPath = "/" + jsPath;
            }
            if (!jsPath.endsWith("/")) {
                jsPath = jsPath + "/";
            }
            generatedSourcesRuntimePath = new URI(jsPath);
        }
    } catch (URISyntaxException use) {
        throw new MojoExecutionException("Unable to generate runtime path", use);
    }
    GenerationDirectory gendir = new // 
    GenerationDirectory(// 
    generatedSourcesPath.toFile(), // 
    null, // 
    generatedSourcesRuntimePath);
    return gendir;
}
Also used : Path(java.nio.file.Path) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) URISyntaxException(java.net.URISyntaxException) GenerationDirectory(org.stjs.generator.GenerationDirectory) URI(java.net.URI)

Example 2 with GenerationDirectory

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

the class TestSTJSMojo method getGeneratedSourcesDirectory.

/**
 * {@inheritDoc}
 */
@Override
protected GenerationDirectory getGeneratedSourcesDirectory() throws MojoExecutionException {
    try {
        File baseDir = project.getBasedir();
        File classpath = new File(generatedTestSourcesDirectory.getAbsolutePath().substring(baseDir.getAbsolutePath().length() + 1));
        URI runtimePath = new URI("classpath:/");
        GenerationDirectory gendir = new GenerationDirectory(generatedTestSourcesDirectory, classpath, runtimePath);
        return gendir;
    } catch (URISyntaxException use) {
        throw new MojoExecutionException("Could not generate runtime path");
    }
}
Also used : MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) GenerationDirectory(org.stjs.generator.GenerationDirectory) URISyntaxException(java.net.URISyntaxException) File(java.io.File) URI(java.net.URI)

Example 3 with GenerationDirectory

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

the class AbstractSTJSMojo method execute.

/**
 * {@inheritDoc}
 */
@Override
public void execute() throws MojoExecutionException, MojoFailureException {
    GenerationDirectory gendir = getGeneratedSourcesDirectory();
    long t1 = System.currentTimeMillis();
    getLog().info("Generating JavaScript files to " + gendir.getGeneratedSourcesAbsolutePath());
    ClassLoader builtProjectClassLoader = getBuiltProjectClassLoader();
    GeneratorConfigurationBuilder configBuilder = new GeneratorConfigurationBuilder();
    configBuilder.generateArrayHasOwnProperty(generateArrayHasOwnProperty);
    configBuilder.generateSourceMap(generateSourceMap);
    if (sourceEncoding != null) {
        configBuilder.sourceEncoding(sourceEncoding);
    }
    // configBuilder.allowedPackage("org.stjs.javascript");
    configBuilder.allowedPackage("org.junit");
    if (allowedPackages != null) {
        configBuilder.allowedPackages(allowedPackages);
    }
    if (annotations != null) {
        configBuilder.annotations(annotations);
    }
    // scan all the packages
    for (String sourceRoot : getCompileSourceRoots()) {
        File sourceDir = new File(sourceRoot);
        Collection<String> packages = accumulatePackages(sourceDir);
        configBuilder.allowedPackages(packages);
    }
    configBuilder.stjsClassLoader(builtProjectClassLoader);
    configBuilder.targetFolder(getBuildOutputDirectory());
    configBuilder.generationFolder(gendir);
    GeneratorConfiguration configuration = configBuilder.build();
    Generator generator = new Generator(configuration);
    int generatedFiles = 0;
    boolean hasFailures = false;
    // scan the modified sources
    for (String sourceRoot : getCompileSourceRoots()) {
        File sourceDir = new File(sourceRoot);
        SourceMapping mapping = new SuffixMapping(".java", ".js");
        SourceMapping stjsMapping = new SuffixMapping(".java", ".stjs");
        List<File> sources = accumulateSources(gendir, sourceDir, mapping, stjsMapping, staleMillis);
        for (File source : sources) {
            if (source.getName().equals(PACKAGE_INFO_JAVA)) {
                getLog().debug("Skipping " + source);
                continue;
            }
            File absoluteSource = new File(sourceDir, source.getPath());
            try {
                File absoluteTarget = (File) mapping.getTargetFiles(gendir.getGeneratedSourcesAbsolutePath(), source.getPath()).iterator().next();
                if (getLog().isDebugEnabled()) {
                    getLog().debug("Generating " + absoluteTarget);
                }
                buildContext.removeMessages(absoluteSource);
                if (!absoluteTarget.getParentFile().exists() && !absoluteTarget.getParentFile().mkdirs()) {
                    getLog().error("Cannot create output directory:" + absoluteTarget.getParentFile());
                    continue;
                }
                String className = getClassNameForSource(source.getPath());
                ClassWithJavascript stjsClass = generator.generateJavascript(className, sourceDir);
                if (!(stjsClass instanceof BridgeClass)) {
                    ++generatedFiles;
                }
            } catch (InclusionScanException e) {
                throw new MojoExecutionException("Cannot scan the source directory:" + e, e);
            } catch (MultipleFileGenerationException e) {
                for (JavascriptFileGenerationException jse : e.getExceptions()) {
                    buildContext.addMessage(jse.getSourcePosition().getFile(), jse.getSourcePosition().getLine(), jse.getSourcePosition().getColumn(), jse.getMessage(), BuildContext.SEVERITY_ERROR, null);
                }
                hasFailures = true;
            // continue with the next file
            } catch (JavascriptFileGenerationException e) {
                buildContext.addMessage(e.getSourcePosition().getFile(), e.getSourcePosition().getLine(), e.getSourcePosition().getColumn(), e.getMessage(), BuildContext.SEVERITY_ERROR, null);
                hasFailures = true;
            // continue with the next file
            } catch (Exception e) {
                // TODO - maybe should filter more here
                buildContext.addMessage(absoluteSource, 1, 1, e.toString(), BuildContext.SEVERITY_ERROR, e);
                hasFailures = true;
            // throw new MojoExecutionException("Error generating javascript:" + e, e);
            }
        }
    }
    generator.close();
    long t2 = System.currentTimeMillis();
    getLog().info("Generated " + generatedFiles + " JavaScript files in " + (t2 - t1) + " ms");
    if (generatedFiles > 0) {
        filesGenerated(generator, gendir);
    }
    if (hasFailures) {
        throw new MojoFailureException("Errors generating JavaScript");
    }
}
Also used : BridgeClass(org.stjs.generator.BridgeClass) InclusionScanException(org.codehaus.plexus.compiler.util.scan.InclusionScanException) MojoExecutionException(org.apache.maven.plugin.MojoExecutionException) MojoFailureException(org.apache.maven.plugin.MojoFailureException) GenerationDirectory(org.stjs.generator.GenerationDirectory) SuffixMapping(org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping) JavascriptFileGenerationException(org.stjs.generator.JavascriptFileGenerationException) 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) MultipleFileGenerationException(org.stjs.generator.MultipleFileGenerationException) URLClassLoader(java.net.URLClassLoader) ClassWithJavascript(org.stjs.generator.ClassWithJavascript) GeneratorConfiguration(org.stjs.generator.GeneratorConfiguration) GeneratorConfigurationBuilder(org.stjs.generator.GeneratorConfigurationBuilder) File(java.io.File) SourceMapping(org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping) Generator(org.stjs.generator.Generator)

Example 4 with GenerationDirectory

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

the class CommandLine method generate.

static void generate(final String path, final String className, List<File> dependencies, String outputDir) {
    Generator gen = null;
    try {
        List<URL> classpathElements = new ArrayList<URL>();
        classpathElements.add(new File(path).toURI().toURL());
        for (File dep : dependencies) {
            classpathElements.add(dep.toURI().toURL());
        }
        ClassLoader builtProjectClassLoader = new URLClassLoader(classpathElements.toArray(new URL[classpathElements.size()]), Thread.currentThread().getContextClassLoader());
        File sourceFolder = new File(path);
        GenerationDirectory generationFolder = new GenerationDirectory(new File(outputDir), null, new URI("/"));
        GeneratorConfigurationBuilder configBuilder = new GeneratorConfigurationBuilder();
        configBuilder.allowedPackage(builtProjectClassLoader.loadClass(className).getPackage().getName());
        configBuilder.generationFolder(generationFolder);
        configBuilder.targetFolder(generationFolder.getGeneratedSourcesAbsolutePath());
        configBuilder.stjsClassLoader(builtProjectClassLoader);
        GeneratorConfiguration configuration = configBuilder.build();
        gen = new Generator(configuration);
        gen.generateJavascript(className, sourceFolder);
    } catch (Exception e) {
        throw Throwables.propagate(e);
    } finally {
        if (gen != null) {
            gen.close();
        }
    }
}
Also used : URLClassLoader(java.net.URLClassLoader) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) GenerationDirectory(org.stjs.generator.GenerationDirectory) GeneratorConfiguration(org.stjs.generator.GeneratorConfiguration) GeneratorConfigurationBuilder(org.stjs.generator.GeneratorConfigurationBuilder) File(java.io.File) URI(java.net.URI) URL(java.net.URL) STJSRuntimeException(org.stjs.generator.STJSRuntimeException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) Generator(org.stjs.generator.Generator)

Example 5 with GenerationDirectory

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

the class AbstractStjsTest method executeOrGenerate.

/**
 * @return the javascript code generator from the given class
 */
private Object executeOrGenerate(Class<?> clazz, boolean execute, boolean withSourceMap, GeneratorConfiguration extraConfig) {
    File generationPath = new File("target", TEMP_GENERATION_PATH);
    // which fucks up URI.resolve
    if (!generationPath.exists() && !generationPath.mkdirs()) {
        throw new STJSRuntimeException("Unable to create generation directory");
    }
    GenerationDirectory generationFolder = new GenerationDirectory(generationPath, new File(TEMP_GENERATION_PATH), generationPath.toURI());
    final File sourcePath = new File("src/test/java");
    File resourcePath = new File("src/test/resources");
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    GeneratorConfiguration config = // 
    new GeneratorConfigurationBuilder(extraConfig).allowedPackage(// 
    "org.stjs.javascript").allowedPackage(// 
    "org.stjs.generator").allowedPackage(// 
    clazz.getPackage().getName()).sourceEncoding("UTF-8").generateSourceMap(// 
    withSourceMap).stjsClassLoader(// 
    classLoader).generationFolder(generationFolder).targetFolder(new File("target", "test-classes")).classResolver(new LazyGenerationClassResolver(classLoader, new LazyGenerator() {

        @Override
        public ClassWithJavascript generateJavaScript(String className) {
            return generator.generateJavascript(className, sourcePath);
        }
    })).build();
    // 
    this.generator = new Generator(config);
    ClassWithJavascript stjsClass = this.generator.generateJavascript(clazz.getName(), sourcePath);
    Timers.start("js-exec");
    List<File> javascriptFiles = new ArrayList<File>();
    try {
        File jsFile = new File(stjsClass.getJavascriptFiles().get(0).getPath());
        String content = Files.toString(jsFile, Charset.defaultCharset());
        List<ClassWithJavascript> allDeps = new DependencyCollector().orderAllDependencies(stjsClass);
        for (ClassWithJavascript dep : allDeps) {
            for (URI js : dep.getJavascriptFiles()) {
                if (dep instanceof BridgeClass) {
                    javascriptFiles.add(new File(resourcePath, js.getPath()));
                } else {
                    javascriptFiles.add(new File(js.getPath()));
                }
            }
        }
        ExecutionResult execResult = new RhinoExecutor().run(javascriptFiles, !execute);
        if (execute) {
            return execResult.getResult();
        }
        return content;
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    } catch (ScriptException ex) {
        // display the generated code in case of exception
        for (File file : javascriptFiles) {
            displayWithLines(file);
        }
        throw new STJSRuntimeException(ex);
    } finally {
        Timers.end("js-exec");
    }
}
Also used : BridgeClass(org.stjs.generator.BridgeClass) STJSRuntimeException(org.stjs.generator.STJSRuntimeException) ArrayList(java.util.ArrayList) LazyGenerator(org.stjs.generator.utils.LazyGenerationClassResolver.LazyGenerator) ExecutionResult(org.stjs.generator.executor.ExecutionResult) GenerationDirectory(org.stjs.generator.GenerationDirectory) IOException(java.io.IOException) RhinoExecutor(org.stjs.generator.executor.RhinoExecutor) URI(java.net.URI) ScriptException(javax.script.ScriptException) STJSRuntimeException(org.stjs.generator.STJSRuntimeException) URLClassLoader(java.net.URLClassLoader) ClassWithJavascript(org.stjs.generator.ClassWithJavascript) GeneratorConfiguration(org.stjs.generator.GeneratorConfiguration) GeneratorConfigurationBuilder(org.stjs.generator.GeneratorConfigurationBuilder) File(java.io.File) DependencyCollector(org.stjs.generator.DependencyCollector) Generator(org.stjs.generator.Generator) LazyGenerator(org.stjs.generator.utils.LazyGenerationClassResolver.LazyGenerator)

Aggregations

GenerationDirectory (org.stjs.generator.GenerationDirectory)5 File (java.io.File)4 URI (java.net.URI)4 IOException (java.io.IOException)3 URISyntaxException (java.net.URISyntaxException)3 URLClassLoader (java.net.URLClassLoader)3 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)3 Generator (org.stjs.generator.Generator)3 GeneratorConfiguration (org.stjs.generator.GeneratorConfiguration)3 GeneratorConfigurationBuilder (org.stjs.generator.GeneratorConfigurationBuilder)3 ArrayList (java.util.ArrayList)2 BridgeClass (org.stjs.generator.BridgeClass)2 ClassWithJavascript (org.stjs.generator.ClassWithJavascript)2 STJSRuntimeException (org.stjs.generator.STJSRuntimeException)2 URL (java.net.URL)1 Path (java.nio.file.Path)1 ScriptException (javax.script.ScriptException)1 DependencyResolutionRequiredException (org.apache.maven.artifact.DependencyResolutionRequiredException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 InclusionScanException (org.codehaus.plexus.compiler.util.scan.InclusionScanException)1