Example usage for com.google.gwt.dev.util Util getBytes

List of usage examples for com.google.gwt.dev.util Util getBytes

Introduction

In this page you can find the example usage for com.google.gwt.dev.util Util getBytes.

Prototype

public static byte[][] getBytes(String[] s) 

Source Link

Document

Returns an array of byte-arrays representing the default encoding for an array of Strings.

Usage

From source file:cc.alcina.framework.gwt.appcache.linker.AppCacheManifestLinker.java

License:Apache License

private EmittedArtifact emitManifest(TreeLogger logger, LinkerContext context, EmittedArtifact userManifest,
        SortedSet<EmittedArtifact> artifacts) throws UnableToCompleteException {
    logger = logger.branch(TreeLogger.DEBUG, "Creating manifest artifact", null);
    // Try getting a user-defined manifest
    StringBuffer out = readManifestTemplate(logger, userManifest);
    // Use the template in the MD5 computation
    digester.update(Util.getBytes(out.toString()));
    // Look for @filter expressions in the manifest template
    Set<Pattern> filters = extractFilters(logger, out);
    // Append the builtin filters
    for (String pattern : BUILTIN_FILTERS) {
        filters.add(Pattern.compile(pattern));
    }/*  ww w  .ja va2 s.c o  m*/
    filters.add(Pattern.compile(".*?(^|/)\\.[^/]+"));// ignore .-prefixed
    // files (e.g.
    // .cvsignore)
    // Generate the manifest entries
    String entries = generateEntries(logger, context, filters, artifacts);
    replaceAll(out, "__VERSION__", StringUtils.toHexString(digester.digest()));
    replaceAll(out, "__ENTRIES__", entries.toString());
    /*
     * NB: It's tempting to use LinkerContext.optimizeJavaScript here, but
     * the JSON standard requires that the keys in the object literal will
     * be enclosed in double-quotes. In our optimized JS form, the
     * double-quotes would normally be removed.
     */
    return emitBytes(logger, Util.getBytes(out.toString()), "appcache.nocache.manifest");
}

From source file:com.bedatadriven.rebar.appcache.linker.AppCacheIFrameLinker.java

License:Apache License

private EmittedArtifact doEmitManifest(TreeLogger logger, PermutationContext context, ManifestWriter writer)
        throws UnableToCompleteException {

    logger = logger.branch(TreeLogger.DEBUG, "Generating " + writer.getSuffix() + " contents", null);

    StringBuffer out = readManifestTemplate(logger, context, writer.getSuffix());

    // Generate the manifest entries
    appendEntries(logger, context, writer);

    // use the current time as the version number
    replaceAll(out, "__NAME__", context.getModuleName());
    replaceAll(out, "__VERSION__", context.getStrongName());
    replaceAll(out, "__ENTRIES__", writer.getEntries());

    /*//from   w  ww  .ja  va  2s .co m
    * NB: It's tempting to use LinkerContext.optimizeJavaScript here, but the
    * JSON standard requires that the keys in the object literal will be
    * enclosed in double-quotes. In our optimized JS form, the double-quotes
    * would normally be removed.
    */
    return emitBytes(logger, Util.getBytes(out.toString()), context.getStrongName() + "." + writer.getSuffix());
}

From source file:com.google.gwt.dev.javac.testing.impl.MockResource.java

License:Apache License

@Override
public InputStream openContents() {
    return new ByteArrayInputStream(Util.getBytes(getContent().toString()));
}

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   www .  j a va 2 s . com

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

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

License:Apache License

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

    ArtifactSet toReturn = new ArtifactSet(artifacts);

    // get set of requests for insideWorker compilations from artifacts
    SortedSet<WorkerRequestArtifact> workerRequests = toReturn.find(WorkerRequestArtifact.class);
    if (workerRequests.size() == 0) {
        logger.log(TreeLogger.SPAM, "No Worker compilations requested. No action taken.");
        return toReturn; // early exit, sorry
    }// w w  w . java2 s. c  o  m

    // compile all requested workers
    // if this is a recursive call, requests were passed up to parent so
    // returned value is null
    SortedMap<WorkerRequestArtifact, String> workerScripts = WorkerCompiler.run(logger, workerRequests);

    // if they exist, deal with compiled scripts:
    if (workerScripts != null && workerScripts.size() != 0) {
        // directory strong name from all scripts
        byte[][] bytejs = Util.getBytes(workerScripts.values().toArray(new String[0]));
        String scriptDirStrongName = Util.computeStrongName(bytejs);

        // emit worker scripts
        for (Map.Entry<WorkerRequestArtifact, String> script : workerScripts.entrySet()) {
            WorkerRequestArtifact req = script.getKey();
            toReturn.add(emitString(logger, script.getValue(),
                    req.getRelativePath(scriptDirStrongName, File.separator)));
        }

        // get the set of current compilation results
        SortedSet<CompilationResult> compResults = toReturn.find(CompilationResult.class);

        /*
         * Reading the js from and writing it to a new CompilationResult is
         * expensive (possibly disk cached), so read once and write only if
         * altered.
         */
        for (CompilationResult compRes : compResults) {
            // assume all need modification
            // TODO: rule out emulated permutations via properties
            toReturn.remove(compRes);

            CompilationResult altered = replacePlaceholder(logger, compRes,
                    WorkerRequestArtifact.getPlaceholderStrongName(), scriptDirStrongName);
            toReturn.add(altered);
        }
    }

    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  ww  .j a  v  a2 s  .  c om
 * 
 * @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;
}