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

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

Introduction

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

Prototype

public static String computeStrongName(byte[][] contents) 

Source Link

Document

Computes the MD5 hash of the specified byte arrays.

Usage

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

License:Apache License

private static IconInfo[] createIconResources(TreeLogger logger, GeneratorContext context, JClassType userType,
        String[] icons) throws UnableToCompleteException {
    final IconInfo[] result = new IconInfo[icons.length];
    for (int i = 0, n = icons.length; i < n; ++i) {
        final String icon = icons[i];

        // Open a stream for the icon resource.
        InputStream iconStream = ExtensionGenerator.class.getClassLoader()
                .getResourceAsStream(getResourcePath(userType, icon));
        if (iconStream == null) {
            logger.log(TreeLogger.ERROR, "Resource not found on classpath: " + icon);
            throw new UnableToCompleteException();
        }/*from  w  ww. jav a2  s.c o  m*/

        try {
            // Read the icon's byte data and decode it to determine the size.
            final byte[] iconData = getBytesFromStream(iconStream);
            assert iconData != null;
            final String strongname = Util.computeStrongName(iconData) + getIconExtension(icon);
            result[i] = new IconInfo(strongname, getImageSize(iconData));

            // Write the icon's bytes into GWT resource.
            try {
                final OutputStream resStream = context.tryCreateResource(logger, strongname);
                if (resStream != null) {
                    resStream.write(iconData);
                    context.commitResource(logger, resStream);
                }
            } catch (IOException e) {
                logger.log(TreeLogger.ERROR, "Unable to write resource: " + icon, e);
                throw new UnableToCompleteException();
            }

        } catch (IOException e) {
            logger.log(TreeLogger.ERROR, "Unable to read image: " + icon, e);
            throw new UnableToCompleteException();
        }
    }

    return result;
}

From source file:com.eleven.rebind.SkinBundleBuilder.java

License:Apache License

public String writeBundledImage(final TreeLogger logger, final GeneratorContext context)
        throws UnableToCompleteException {

    // Create the bundled image from all of the constituent images.
    BufferedImage bundledImage = drawBundledImage();

    // Write the bundled image into a byte array, so that we can compute
    // its strong name.
    byte[] imageBytes;

    try {/*  w ww  .  j  av  a 2s. c  om*/
        ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bundledImage, BUNDLE_FILE_TYPE, byteOutputStream);
        imageBytes = byteOutputStream.toByteArray();
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, "Unable to generate file name for image bundle file", null);
        throw new UnableToCompleteException();
    }

    // Compute the file name. The strong name is generated from the bytes of
    // the bundled image. The '.cache' part indicates that it can be
    // permanently cached.
    String bundleFileName = Util.computeStrongName(imageBytes) + ".cache." + BUNDLE_FILE_TYPE;

    // Try and write the file to disk. If a file with bundleFileName already
    // exists, then the file will not be written.
    OutputStream outStream = context.tryCreateResource(logger, bundleFileName);

    if (outStream != null) {
        try {
            // Write the image bytes from the byte array to the pending
            // stream.
            outStream.write(imageBytes);

            // Commit the stream.
            context.commitResource(logger, outStream);

        } catch (IOException e) {
            logger.log(TreeLogger.ERROR, "Failed while writing", e);
            throw new UnableToCompleteException();
        }
    } else
        logger.log(TreeLogger.TRACE, "Generated image bundle file already exists; no need to rewrite it.",
                null);

    return bundleFileName;
}

From source file:de.csenk.gwt.ws.rebind.filter.serialization.GWTSerializerGenerator.java

License:Open Source License

/**
 * @param serializerLogger/* ww  w  .  ja  v a  2  s .c o  m*/
 * @param context
 * @param typesSentFromBrowser
 * @param typesSentToBrowser
 * @param typeStrings
 * @return
 */
private String writeSerializationPolicyFile(TreeLogger logger, GeneratorContext ctx,
        SerializableTypeOracle serializationSto, SerializableTypeOracle deserializationSto,
        Map<JType, String> typeStrings, JClassType serializerInterface) throws UnableToCompleteException {
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        OutputStreamWriter osw = new OutputStreamWriter(baos,
                SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING);
        TypeOracle oracle = ctx.getTypeOracle();
        PrintWriter pw = new PrintWriter(osw);

        JType[] serializableTypes = unionOfTypeArrays(serializationSto.getSerializableTypes(),
                deserializationSto.getSerializableTypes(), new JType[] { serializerInterface });

        for (int i = 0; i < serializableTypes.length; ++i) {
            JType type = serializableTypes[i];
            String binaryTypeName = TypeOracleMediator.computeBinaryClassName(type);
            pw.print(binaryTypeName);
            pw.print(", " + Boolean.toString(deserializationSto.isSerializable(type)));
            pw.print(", " + Boolean.toString(deserializationSto.maybeInstantiated(type)));
            pw.print(", " + Boolean.toString(serializationSto.isSerializable(type)));
            pw.print(", " + Boolean.toString(serializationSto.maybeInstantiated(type)));
            pw.print(", " + typeStrings.get(type));

            /*
             * Include the serialization signature to bump the RPC file name
             * if obfuscated identifiers are used.
             */
            pw.print(", " + SerializationUtils.getSerializationSignature(oracle, type));
            pw.print('\n');

            /*
             * Emit client-side field information for classes that may be
             * enhanced on the server. Each line consists of a
             * comma-separated list containing the keyword '@ClientFields',
             * the class name, and a list of all potentially serializable
             * client-visible fields.
             */
            if ((type instanceof JClassType) && ((JClassType) type).isEnhanced()) {
                JField[] fields = ((JClassType) type).getFields();
                JField[] rpcFields = new JField[fields.length];
                int numRpcFields = 0;
                for (JField f : fields) {
                    if (f.isTransient() || f.isStatic() || f.isFinal()) {
                        continue;
                    }
                    rpcFields[numRpcFields++] = f;
                }

                pw.print(SerializationPolicyLoader.CLIENT_FIELDS_KEYWORD);
                pw.print(',');
                pw.print(binaryTypeName);
                for (int idx = 0; idx < numRpcFields; idx++) {
                    pw.print(',');
                    pw.print(rpcFields[idx].getName());
                }
                pw.print('\n');
            }
        }

        // Closes the wrapped streams.
        pw.close();

        byte[] serializationPolicyFileContents = baos.toByteArray();
        String serializationPolicyName = Util.computeStrongName(serializationPolicyFileContents);

        String serializationPolicyFileName = SerializationPolicyLoader
                .getSerializationPolicyFileName(serializationPolicyName);
        OutputStream os = ctx.tryCreateResource(logger, serializationPolicyFileName);
        if (os != null) {
            os.write(serializationPolicyFileContents);
            GeneratedResource resource = ctx.commitResource(logger, os);

            /*
             * Record which proxy class created the resource. A manifest
             * will be emitted by the RpcPolicyManifestLinker.
             */
            ctx.commitArtifact(logger,
                    new RpcPolicyFileArtifact(serializerInterface.getQualifiedSourceName(), resource));
        } else {
            logger.log(TreeLogger.TRACE, "SerializationPolicy file for RemoteService '"
                    + serializerInterface.getQualifiedSourceName() + "' already exists; no need to rewrite it.",
                    null);
        }

        return serializationPolicyName;
    } catch (UnsupportedEncodingException e) {
        logger.log(TreeLogger.ERROR,
                SerializationPolicyLoader.SERIALIZATION_POLICY_FILE_ENCODING + " is not supported", e);
        throw new UnableToCompleteException();
    } catch (IOException e) {
        logger.log(TreeLogger.ERROR, null, e);
        throw new UnableToCompleteException();
    }
}

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. j a va2  s .  c  om*/

    // 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./*from   w ww  .  j a v a 2 s . co 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:rocket.generator.rebind.GeneratorContextImpl.java

License:Apache License

/**
 * Helper which writes a resource if it doesnt already exist generating a
 * strong filename to guarantee uniqueness.
 * /*from   www .j a  v  a  2  s.  co m*/
 * @param contents
 * @param suffix
 *            A suffix which is appended to the hash. Typically this will
 *            include "nocache." + the file extension.
 * @return The partial path of the written file.
 */
public String createResource(final byte[] contents, final String suffix) {
    Checker.notNull("parameter:contents", contents);
    Checker.notEmpty("parameter:suffix", suffix);

    final String hash = Util.computeStrongName(contents);
    final String filename = hash + suffix;

    OutputStream outputStream = this.createResource(filename);
    if (null != outputStream) {
        try {
            outputStream.write(contents);
            outputStream.flush();
        } catch (final IOException io) {
            InputOutput.throwIOException(io);
        } finally {
            InputOutput.closeIfNecessary(outputStream);
        }
    }
    return filename;
}