Example usage for com.google.gwt.core.ext.linker CompilationResult getJavaScript

List of usage examples for com.google.gwt.core.ext.linker CompilationResult getJavaScript

Introduction

In this page you can find the example usage for com.google.gwt.core.ext.linker CompilationResult getJavaScript.

Prototype

public abstract String[] getJavaScript();

Source Link

Document

Returns the JavaScript compilation.

Usage

From source file:com.ait.toolkit.node.dev.linker.NodeJsLinker.java

License:Open Source License

@Override
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
        throws UnableToCompleteException {
    ArtifactSet toReturn = new ArtifactSet(artifacts);
    DefaultTextOutput out = new DefaultTextOutput(true);
    // inject other scripts
    // for (ScriptReference resource :
    // artifacts.find(ScriptReference.class)) {
    // out.print(resource.toString());
    // }// ww w .  j a  va2  s  .  co  m
    // closure
    // out.print("(function () {");
    // out.newline();
    // grab compilation result
    Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    CompilationResult result = null;
    if (results.size() > 1) {
        logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
                + " permutation when using the " + getDescription() + " Linker.", null);
        throw new UnableToCompleteException();
    } else if (!results.isEmpty()) {
        result = results.iterator().next();
        // dump JS
        String[] js = result.getJavaScript();
        if (js.length != 1) {
            logger.log(TreeLogger.ERROR, "The module must not have multiple fragments when using the "
                    + getDescription() + " Linker.", null);
            throw new UnableToCompleteException();
        }
        out.print(js[0]);
        out.newline();
    }
    out.print("var $stats = function() { };");
    out.newline();
    out.print("var $sessionId = function() { };");
    out.newline();
    // global window
    // TODO: check this against jsdom
    // out.print("var window = { };");
    // out.newline();
    // preload code
    addPreloadCode(logger, context, artifacts, result, out);
    out.newline();
    out.print("gwtOnLoad(null, '" + context.getModuleName() + "', null);");
    out.newline();
    // out.print("})();");
    // out.newline();
    // and to string
    toReturn.add(emitString(logger, out.toString(), context.getModuleName() + ".js"));
    return toReturn;
}

From source file:com.chrome.gwt.linker.ExtensionLinker.java

License:Apache License

private static String generateHtmlContents(TreeLogger logger, CompilationResult js)
        throws UnableToCompleteException {
    // Thou shalt not reference $doc or $wnd !!!
    String compiledJs = js.getJavaScript()[0];

    // Work around for GWT 2.0, there are 2 harmless $wnd references that creep
    // in//  w ww.j  a v a  2  s.  c o  m
    checkForDisallowedJs(compiledJs, "\\$wnd", 2, logger);
    checkForDisallowedJs(compiledJs, "\\$doc", 0, logger);

    final StringBuffer buffer = new StringBuffer();
    buffer.append("<html>");
    buffer.append("<head></head>");
    buffer.append("<body>");
    buffer.append("<script>var $stats;\n" + compiledJs + "gwtOnLoad();\n</script>");
    buffer.append("</body>");
    buffer.append("</html>");
    return buffer.toString();
}

From source file:com.emitrom.ti4j.mobile.hybrid.linker.TiMobileHybridLinker.java

License:Apache License

public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
        throws UnableToCompleteException {

    ArtifactSet toReturn = new ArtifactSet(artifacts);
    DefaultTextOutput out = new DefaultTextOutput(true);
    long compilationTime = System.currentTimeMillis();
    out.print("(function(){");
    out.newline();/*from  w w  w. jav a2s  .c  om*/

    // get compilation result
    Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    if (results.size() == 0) {
        logger.log(TreeLogger.WARN, "Requested 0 permutations");
        return toReturn;
    }

    CompilationResult result = results.iterator().next();

    // get the generated javascript
    String[] javaScript = result.getJavaScript();
    out.print("var $wnd;var $doc;");
    out.print("var $moduleName, $moduleBase;");
    out.newline();
    out.print("if(typeof(window) != 'undefined'){ $wnd = window;  $doc = $wnd.document; }");
    out.newline();
    out.print("var $gwt_version = \"" + About.getGwtVersionNum() + "\";");
    out.newlineOpt();
    out.print(javaScript[0]);
    out.newline();
    out.print("var $stats = function(){};");
    out.newline();
    out.print("var $sessionId = function(){};");
    out.newline();
    out.print("var navigator = {};");
    out.newline();
    out.print("navigator.userAgent = 'timobile';");
    out.newline();
    out.print("$strongName = '" + result.getStrongName() + "';");
    out.newline();
    out.print("$ti4jCompilationDate = " + compilationTime + ";");
    out.newline();
    out.print("gwtOnLoad(null,'" + context.getModuleName() + "',null);");
    out.newline();
    out.print("})();");
    out.newline();

    toReturn.add(emitString(logger, out.toString(), context.getModuleName() + ".js"));
    // toReturn.add(emitString(logger, Long.toString(compilationTime),
    // APP_COMPILATION_FILE_NAME));

    return toReturn;
}

From source file:com.envjs.gwt.linker.ServerSingleScriptLinker.java

License:Apache License

@Override
protected Collection<EmittedArtifact> doEmitCompilation(TreeLogger logger, LinkerContext context,
        CompilationResult result) throws UnableToCompleteException {
    if (result.getJavaScript().length != 1) {
        logger.branch(TreeLogger.ERROR,//from   w  w w  .  ja  va  2s . co m
                "The module must not have multiple fragments when using the " + getDescription() + " Linker.",
                null);
        throw new UnableToCompleteException();
    }
    return super.doEmitCompilation(logger, context, result);
}

From source file:com.envjs.gwt.linker.ServerSingleScriptLinker.java

License:Apache License

@Override
protected EmittedArtifact emitSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
        throws UnableToCompleteException {

    DefaultTextOutput out = new DefaultTextOutput(true);

    // Emit the selection script.
    // this for 'real browsers' to load the script
    // we don't need this.
    /*/*w w w.  j a  v a  2  s.co m*/
    String bootstrap = generateSelectionScript(logger, context, artifacts);
    bootstrap = context.optimizeJavaScript(logger, bootstrap);
    out.print(bootstrap);
    out.newlineOpt();
    */

    // we need a ref to the top level window
    //  it is referenced in the closure below
    out.print("var $_window = this;");
    out.newlineOpt();

    // this is a hack to make backwards compatible
    out.print("var __defineParser__ = function(){};");
    out.newlineOpt();

    // Emit the module's JS a closure.
    out.newlineOpt();
    out.print("(function () {");
    out.newlineOpt();
    out.print("var $gwt_version = \"" + About.getGwtVersionNum() + "\";");
    out.newlineOpt();
    out.print("var $wnd = $_window;");
    out.newlineOpt();
    out.print("var $doc = $wnd.document;");
    out.newlineOpt();
    out.print("var $moduleName, $moduleBase;");
    out.newlineOpt();
    out.print("var $stats = $wnd.__gwtStatsEvent ? function(a) {$wnd.__gwtStatsEvent(a)} : null;");
    out.newlineOpt();

    // Find the single CompilationResult
    Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    if (results.size() != 1) {
        logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
                + " permutation when using the " + getDescription() + " Linker.", null);
        throw new UnableToCompleteException();
    }
    CompilationResult result = results.iterator().next();

    out.print("var $strongName = '" + result.getStrongName() + "';");
    out.newlineOpt();

    String[] js = result.getJavaScript();
    if (js.length != 1) {
        logger.log(TreeLogger.ERROR,
                "The module must not have multiple fragments when using the " + getDescription() + " Linker.",
                null);
        throw new UnableToCompleteException();
    }

    out.print(js[0]);

    // Generate the call to tell the bootstrap code that we're ready to go.
    out.newlineOpt();

    // the original code setup an "onScriptLoad" event. 
    // Here we just do it
    out.print("gwtOnLoad();");

    out.newlineOpt();
    out.print("})();");
    out.newlineOpt();

    return emitString(logger, out.toString(), context.getModuleName() + ".nocache.js");
}

From source file:com.google.javascript.jscomp.gwt.linker.MinimalLinker.java

License:Apache License

@Override
public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts, boolean onePermutation)
        throws UnableToCompleteException {
    ArtifactSet toReturn = new ArtifactSet(artifacts);
    ArtifactSet writableArtifacts = new ArtifactSet(artifacts);

    for (CompilationResult result : toReturn.find(CompilationResult.class)) {
        String[] js = result.getJavaScript();
        Preconditions.checkArgument(js.length == 1, "MinimalLinker doesn't support GWT.runAsync");

        byte[] primary = Util.getBytes(PREFIX + js[0] + SUFFIX);
        toReturn.add(emitBytes(logger, primary, context.getModuleName() + ".js"));
    }//from  w w w .  j  av  a2 s .c  o  m

    for (SymbolMapsLinker.ScriptFragmentEditsArtifact ea : writableArtifacts
            .find(SymbolMapsLinker.ScriptFragmentEditsArtifact.class)) {
        toReturn.add(ea);
    }
    return toReturn;
}

From source file:delight.gwt.simplelinker.SimpleLinker.java

License:Apache License

@Override
public ArtifactSet link(final TreeLogger logger, final LinkerContext context, final ArtifactSet artifacts)
        throws UnableToCompleteException {
    final ArtifactSet toReturn = new ArtifactSet(artifacts);
    final DefaultTextOutput out = new DefaultTextOutput(true);

    // out.print("var $stats = function() { };");
    out.print("var $_window = this;");
    out.newline();/*from w w  w. j  a v  a 2s  .  co m*/
    out.print("var $gwt_version = \"" + About.getGwtVersionNum() + "\";");
    out.newline();
    out.print("var $stats = $wnd.__gwtStatsEvent ? function(a) {$wnd.__gwtStatsEvent(a)} : null;");
    out.newline();
    out.print("var $sessionId = function() { };");
    out.newline();

    final Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    CompilationResult result = null;
    if (results.size() > 1) {
        logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
                + " permutation when using the " + getDescription() + " Linker.", null);
        throw new UnableToCompleteException();
    } else if (!results.isEmpty()) {
        result = results.iterator().next();
        // dump JS
        final String[] js = result.getJavaScript();
        if (js.length != 1) {
            logger.log(TreeLogger.ERROR, "The module must not have multiple fragments when using the "
                    + getDescription() + " Linker.", null);
            throw new UnableToCompleteException();
        }
        out.print(js[0]);
        out.newline();
    }

    addPreloadCode(logger, context, artifacts, result, out);
    out.newline();
    out.print("gwtOnLoad(null, '" + context.getModuleName() + "', null);");
    out.newline();
    // out.print("})();");
    // out.newline();
    // and to string
    toReturn.add(emitString(logger, out.toString(), context.getModuleName() + ".js"));
    return toReturn;
}

From source file:gwt.ns.webworker.linker.WorkerCompilationLinker.java

License:Apache License

/**
 * Searches for all instances of a placeholder String in a
 * CompilationResult. If found, they are replaced as specified and a
 * new CompilationResult, with a newly generated strong name, is returned.
 * If no occurrences were found, the original CompilationResult is
 * returned./*  w  w  w  . j  a v  a  2  s  .c o m*/
 * 
 * @param logger
 * @param result CompilationResult to process
 * @param placeholder String to be replaced
 * @param replacement String to insert in place of placeholder
 * 
 * @return A CompilationResult suitable for emitting
 */
public CompilationResult replacePlaceholder(TreeLogger logger, CompilationResult result, String placeholder,
        String replacement) {

    boolean needsMod = false;

    String[] js = result.getJavaScript();
    StringBuffer[] jsbuf = new StringBuffer[js.length];
    for (int i = 0; i < jsbuf.length; i++) {
        jsbuf[i] = new StringBuffer(js[i]);
    }

    // search and replace in all fragments
    for (StringBuffer fragment : jsbuf) {
        needsMod |= replaceAll(fragment, placeholder, replacement);
    }

    // by default, returning unaltered result
    CompilationResult toReturn = result;

    // code has been altered, need to create new CompilationResult
    if (needsMod) {
        logger.log(TreeLogger.SPAM,
                "Compilation permutation " + result.getPermutationId() + " being modified.");

        // new js for compilation result
        byte[][] newcode = new byte[jsbuf.length][];
        for (int i = 0; i < jsbuf.length; i++) {
            newcode[i] = Util.getBytes(jsbuf[i].toString());
        }

        // new strong name
        String strongName = Util.computeStrongName(newcode);

        // same symbolMap copied over since none altered
        // symbolMap a little more complicated
        // can only get deserialized version, need to reserialize
        // code from com.google.gwt.dev.jjs.JavaToJavaScriptCompiler
        // TODO: turns out this can get pretty bad. Workaround?
        SymbolData[] symbolMap = result.getSymbolMap();
        byte[] serializedSymbolMap;
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Util.writeObjectToStream(baos, (Object) symbolMap);
            serializedSymbolMap = baos.toByteArray();
        } catch (IOException e) {
            // should still never happen
            logger.log(TreeLogger.ERROR, "IOException while reserializing " + "SymbolMap.");
            throw new RuntimeException("Should never happen with in-memory stream", e);
        }

        StandardCompilationResult altered = new StandardCompilationResult(strongName, newcode,
                serializedSymbolMap, result.getStatementRanges(), result.getPermutationId());

        // need to copy permutation properties to new result
        for (Map<SelectionProperty, String> propertyMap : result.getPropertyMap()) {
            altered.addSelectionPermutation(propertyMap);
        }

        toReturn = altered;

        logger.log(TreeLogger.SPAM, "Compilation permuation " + toReturn.getPermutationId()
                + " altered to include path to worker script(s).");
    }

    return toReturn;
}

From source file:gwt.ns.webworker.linker.WorkerModuleLinker.java

License:Apache License

@Override
protected Collection<EmittedArtifact> doEmitCompilation(TreeLogger logger, LinkerContext context,
        CompilationResult result) throws UnableToCompleteException {

    if (result.getJavaScript().length != 1) {
        logger.branch(TreeLogger.ERROR,//  w w w .ja  v a  2  s  .c o m
                "The module must not have multiple fragments when using the " + getDescription() + " Linker.",
                null);
        throw new UnableToCompleteException();
    }

    return super.doEmitCompilation(logger, context, result);
}

From source file:gwt.ns.webworker.linker.WorkerModuleLinker.java

License:Apache License

@Override
protected EmittedArtifact emitSelectionScript(TreeLogger logger, LinkerContext context, ArtifactSet artifacts)
        throws UnableToCompleteException {

    DefaultTextOutput out = new DefaultTextOutput(true);

    // Emit the selection script from template
    String bootstrap = generateSelectionScript(logger, context, artifacts);
    bootstrap = context.optimizeJavaScript(logger, bootstrap);
    out.print(bootstrap);// w  ww .j a  v  a  2 s  .  c  o  m
    out.newlineOpt();

    // Emit the module's JS within a closure.
    out.print("(function () {");
    out.newlineOpt();
    out.print("var $gwt_version = \"" + About.getGwtVersionNum() + "\";");
    out.newlineOpt();

    /* Point $wnd and $doc to insideWorker global scope. Shouldn't be used, but there
     * in case preexisting code uses either as a generic global variable
     * normal access of $wnd and $doc attributes and methods will be broken,
     * per Worker spec
     */
    out.print("var $self = self;");
    out.newlineOpt();
    out.print("var $wnd = self;");
    out.newlineOpt();
    out.print("var $doc = self;");
    out.newlineOpt();

    out.print("var $moduleName, $moduleBase;"); //needed if no stats/error handling?
    out.newlineOpt();
    out.print("var $stats = null;");
    out.newlineOpt();

    // append module code

    // Find the single CompilationResult
    Set<CompilationResult> results = artifacts.find(CompilationResult.class);
    if (results.size() != 1) {
        logger.log(TreeLogger.ERROR, "The module must have exactly one distinct"
                + " permutation when using the " + getDescription() + " Linker.", null);

        // give a hint to reason for failure
        logPermutationProperties(logger, context.getProperties());

        throw new UnableToCompleteException();
    }
    CompilationResult result = results.iterator().next();

    out.print("var $strongName = '" + result.getStrongName() + "';");
    out.newlineOpt();

    // get actual compiled javascript and output
    // only one fragment currently supported (no runAsync)
    String[] js = result.getJavaScript();
    if (js.length != 1) {
        logger.log(TreeLogger.ERROR,
                "The module must not have multiple fragments when using the " + getDescription()
                        + " Linker. Use of GWT.runAsync within Worker"
                        + " code is the most likely cause of this error.",
                null);
        throw new UnableToCompleteException();
    }
    out.print(js[0]);

    // Generate the call to tell the bootstrap code that we're ready to go.
    out.newlineOpt();
    out.print("if (" + context.getModuleFunctionName() + ") " + context.getModuleFunctionName()
            + ".onScriptLoad(gwtOnLoad);");
    out.newlineOpt();
    out.print("})();");
    out.newlineOpt();

    // TODO: this naming scheme helps WorkerCompilationLinker, but users
    // compiling separate worker scripts may desire a strong file name
    return emitString(logger, out.toString(), context.getModuleName() + WORKER_EXTENSION);
}