Search in sources :

Example 1 with BridgeClass

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

the class LongPollingBrowser method sendTestFixture.

/**
 * Writes to the HTTP response the HTML and/or javascript code that is necessary for the browser to execute the specified test.
 *
 * @param meth     The test to send to the browser
 * @param exchange contains the HTTP response that must be written to
 */
public void sendTestFixture(MultiTestMethod meth, HttpExchange exchange) throws Exception {
    TestClassAttributes attr = testClasses.getAttributes(meth.getTestClass());
    final Test test = meth.getMethod().getAnnotation(Test.class);
    StringBuilder resp = new StringBuilder(8192);
    resp.append("<html>\n");
    resp.append("<head>\n");
    appendScriptTag(resp, httpPath(new URI("webjar:/stjs.js")));
    appendScriptTag(resp, "/junit.js");
    resp.append("<script language='javascript'>stjs.mainCallDisabled=true;</script>\n");
    // scripts added explicitly
    for (String script : attr.getScripts()) {
        appendScriptTag(resp, script);
    }
    // scripts before - new style
    for (String script : attr.getScriptsBefore()) {
        appendScriptTag(resp, script);
    }
    Set<URI> jsUris = new LinkedHashSet<>();
    for (ClassWithJavascript dep : attr.getDependencies()) {
        if (!attr.getScripts().isEmpty() && dep instanceof BridgeClass) {
            // bridge dependencies are not added when using @Scripts
            System.out.println("WARNING: You're using @Scripts deprecated annotation that disables the automatic inclusion of the Javascript files of " + "the bridges you're using! " + "Please consider using @ScriptsBefore and/or @ScriptsAfter instead.");
            continue;
        }
        for (URI file : dep.getJavascriptFiles()) {
            jsUris.add(file);
        }
    }
    for (URI uri : jsUris) {
        appendScriptTag(resp, httpPath(uri));
    }
    // scripts after - new style
    for (String script : attr.getScriptsAfter()) {
        appendScriptTag(resp, script);
    }
    resp.append("<script language='javascript'>\n");
    if (getConfig().isDebugJavaScript()) {
        resp.append(" function runTest() {\n");
        resp.append("    (elem=document.getElementById('startSection')).parentNode.removeChild(elem);\n");
    } else {
        resp.append("  window.onload=function(){\n");
    }
    // resp.append("    console.error(document.getElementsByTagName('html')[0].innerHTML);\n");
    // Adapter between generated assert (not global) and JS-test-driver assert (which is a
    // set of global methods)
    resp.append("    Assert=window;\n");
    resp.append("    try{\n");
    String testedClassName = attr.getStjsClass().getJavascriptClassName();
    resp.append("        parent.startingTest('" + testedClassName + "', '" + meth.getName() + "');\n");
    resp.append("        var stjsTest = new " + testedClassName + "();\n");
    resp.append("        var stjsResult = 'OK';\n");
    String expectedExceptionConstructor = "null";
    if (test.expected() != Test.None.class) {
        ClassWithJavascript exceptionClass = getConfig().getStjsClassResolver().resolve(test.expected().getName());
        expectedExceptionConstructor = exceptionClass.getJavascriptClassName();
    }
    resp.append("        var expectedException = " + expectedExceptionConstructor + ";\n");
    // call before methods
    for (FrameworkMethod beforeMethod : attr.getBeforeMethods()) {
        resp.append("      stjsTest." + beforeMethod.getName() + "();\n");
    }
    // call the test's method
    resp.append("      stjsTest." + meth.getName() + "();\n");
    resp.append("      if(expectedException){\n");
    resp.append("        stjsResult = 'Expected an exception, but none was thrown';\n");
    resp.append("      }\n");
    resp.append("    }catch(ex){\n");
    // an exception was caught while executing the test method
    resp.append("      if(!expectedException){\n");
    resp.append("        stjsResult = ex;\n");
    resp.append("      } else if (!stjs.isInstanceOf(ex.constructor,expectedException)){\n");
    resp.append("        stjsResult = ex;\n");
    resp.append("      }\n");
    resp.append("    }finally{\n");
    // call after methods
    for (FrameworkMethod afterMethod : attr.getAfterMethods()) {
        resp.append("     stjsTest." + afterMethod.getName() + "();\n");
    }
    resp.append("      parent.reportResultAndRunNextTest(stjsResult, stjsResult.location);\n");
    resp.append("     }\n");
    resp.append("  }\n");
    resp.append("</script>\n");
    resp.append("</head>\n");
    resp.append("<body>\n");
    if (getConfig().isDebugJavaScript()) {
        resp.append("<div id='startSection'>\n");
        resp.append("  <h2>JavaScript debugging mode</h2>\n");
        resp.append("  <ul>\n");
        resp.append("    <li>Open your developer tools</li>\n");
        resp.append("    <li>Setup your breakpoints and debugging options</li>\n");
        resp.append("    <li>Start the test</li>\n");
        resp.append("  </ul>\n");
        resp.append("  <button onclick='runTest()'>\n");
        resp.append("    Start " + attr.getStjsClass().getJavaClass().getSimpleName() + "." + meth.getName() + "\n");
        resp.append("  </button>\n");
        resp.append("</div>\n");
    }
    if (attr.getHtmlFixture() != null) {
        if (!Strings.isNullOrEmpty(attr.getHtmlFixture().value())) {
            resp.append(attr.getHtmlFixture().value());
        } else if (!Strings.isNullOrEmpty(attr.getHtmlFixture().url())) {
            StringWriter writer = new StringWriter();
            getConfig().getResource(attr.getHtmlFixture().url()).copyTo(writer);
            resp.append(writer.toString());
        }
    }
    resp.append("</body>\n");
    resp.append("</html>\n");
    sendResponse(resp.toString(), exchange);
}
Also used : LinkedHashSet(java.util.LinkedHashSet) BridgeClass(org.stjs.generator.BridgeClass) TestClassAttributes(org.stjs.testing.driver.TestClassAttributes) StringWriter(java.io.StringWriter) Test(org.junit.Test) ClassWithJavascript(org.stjs.generator.ClassWithJavascript) URI(java.net.URI) FrameworkMethod(org.junit.runners.model.FrameworkMethod)

Example 2 with BridgeClass

use of org.stjs.generator.BridgeClass 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 3 with BridgeClass

use of org.stjs.generator.BridgeClass 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

BridgeClass (org.stjs.generator.BridgeClass)3 ClassWithJavascript (org.stjs.generator.ClassWithJavascript)3 File (java.io.File)2 IOException (java.io.IOException)2 URI (java.net.URI)2 URLClassLoader (java.net.URLClassLoader)2 GenerationDirectory (org.stjs.generator.GenerationDirectory)2 Generator (org.stjs.generator.Generator)2 GeneratorConfiguration (org.stjs.generator.GeneratorConfiguration)2 GeneratorConfigurationBuilder (org.stjs.generator.GeneratorConfigurationBuilder)2 StringWriter (java.io.StringWriter)1 ArrayList (java.util.ArrayList)1 LinkedHashSet (java.util.LinkedHashSet)1 ScriptException (javax.script.ScriptException)1 DependencyResolutionRequiredException (org.apache.maven.artifact.DependencyResolutionRequiredException)1 MojoExecutionException (org.apache.maven.plugin.MojoExecutionException)1 MojoFailureException (org.apache.maven.plugin.MojoFailureException)1 InclusionScanException (org.codehaus.plexus.compiler.util.scan.InclusionScanException)1 SourceMapping (org.codehaus.plexus.compiler.util.scan.mapping.SourceMapping)1 SuffixMapping (org.codehaus.plexus.compiler.util.scan.mapping.SuffixMapping)1