Example usage for com.google.gwt.core.ext GeneratorContext commitArtifact

List of usage examples for com.google.gwt.core.ext GeneratorContext commitArtifact

Introduction

In this page you can find the example usage for com.google.gwt.core.ext GeneratorContext commitArtifact.

Prototype

void commitArtifact(TreeLogger logger, Artifact<?> artifact) throws UnableToCompleteException;

Source Link

Document

Add an Artifact to the com.google.gwt.core.ext.linker.ArtifactSet that will be presented to the Linker chain at the end of the compilation cycle.

Usage

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

License:Apache License

private static String processBrowserAction(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    BrowserAction.ManifestInfo spec = userType.getAnnotation(BrowserAction.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR,//from   w  w  w . j  a v  a 2  s. c om
                "BrowserAction (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }
    JMethod[] methods = userType.getMethods();
    List<String> iconFileNames = new ArrayList<String>();
    List<String> iconMethodNames = new ArrayList<String>();

    // TODO(jaimeyap): Do something smarter about verifying that the files
    // actually exist on disk, and then coming up with something sane for
    // the path information. May even consider strong names. See what
    // ClientBundle/ImageResource does.
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getReturnType().getQualifiedSourceName().equals(ICON_USER_TYPE)) {
            JMethod method = methods[i];
            String iconFileName;
            Icon.Source iconSource = method.getAnnotation(Icon.Source.class);
            if (iconSource == null) {
                iconFileName = method.getName() + ".png";
            } else {
                iconFileName = iconSource.value();
            }
            iconFileNames.add(iconFileName);
            iconMethodNames.add(method.getName());
        }
    }
    if (iconFileNames.size() == 0) {
        logger.log(TreeLogger.ERROR, "BrowserActions must have at least one Icon (" + typeName + ")");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger, new BrowserActionArtifact(spec.name(), iconFileNames.toArray(new String[0]),
            spec.defaultIcon(), spec.popup()));
    return emitBrowserActionCode(logger, context, userType, spec.name(), iconMethodNames, iconFileNames);
}

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

License:Apache License

private static void processContentScript(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    ManifestInfo spec = userType.getAnnotation(ContentScript.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR,//w  ww  . j  av  a 2 s.  c  o m
                "ContentScript (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger, new ContentScriptArtifact(spec.path(), spec.whiteList(), spec.runAt()));
}

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

License:Apache License

private static String processPageAction(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    PageAction.ManifestInfo spec = userType.getAnnotation(PageAction.ManifestInfo.class);
    Extension.ManifestInfo spec2 = userType.getAnnotation(Extension.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR, "PageAction (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }/*from  w  w  w  .  j  a v a  2s.co m*/
    JMethod[] methods = userType.getMethods();
    List<String> iconFileNames = new ArrayList<String>();
    List<String> iconMethodNames = new ArrayList<String>();

    // TODO(jaimeyap): Do something smarter about verifying that the files
    // actually exist on disk, and then coming up with something sane for
    // the path information. May even consider strong names. See what
    // ClientBundle/ImageResource does.
    for (int i = 0; i < methods.length; i++) {
        if (methods[i].getReturnType().getQualifiedSourceName().equals(ICON_USER_TYPE)) {
            JMethod method = methods[i];
            String iconFileName;
            Icon.Source iconSource = method.getAnnotation(Icon.Source.class);
            if (iconSource == null) {
                iconFileName = method.getName() + ".png";
            } else {
                iconFileName = iconSource.value();
            }
            iconFileNames.add(iconFileName);
            iconMethodNames.add(method.getName());
        }
    }
    if (iconFileNames.size() == 0) {
        logger.log(TreeLogger.ERROR, "PageActions must have at least one Icon (" + typeName + ")");
        throw new UnableToCompleteException();
    }
    context.commitArtifact(logger,
            new PageActionArtifact(spec.pageActionId(), spec.name(), iconFileNames.toArray(new String[0])));
    return emitPageActionCode(logger, context, userType, spec.pageActionId(), spec.name(), iconMethodNames,
            iconFileNames);
}

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

License:Apache License

private static void processPlugin(TreeLogger logger, GeneratorContext context, JClassType userType,
        String typeName) throws UnableToCompleteException {
    Plugin.ManifestInfo spec = userType.getAnnotation(Plugin.ManifestInfo.class);
    if (spec == null) {
        logger.log(TreeLogger.ERROR, "Plugin (" + typeName + ") must be annotated with a Specificaiton.");
        throw new UnableToCompleteException();
    }/*  w  ww  .jav a 2 s.c  o m*/
    context.commitArtifact(logger, new PluginArtifact(spec.path(), spec.isPublic()));
}

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

License:Apache License

private static String processToolStrip(TreeLogger logger, GeneratorContext context, JClassType userType)
        throws UnableToCompleteException {
    String name = userType.getSimpleSourceName();
    String path = name + ".html";
    emitComponentPage(logger, context, name, path);
    context.commitArtifact(logger, new ToolStripArtifact(path));
    return emitComponentPageCode(logger, context, userType);
}

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

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    try {//from w  ww . j a  va 2s.  c om
        final JClassType userType = context.getTypeOracle().getType(typeName);
        final ExtensionArtifact spec = getSpecification(logger, context, userType);
        context.commitArtifact(logger, spec);
        return generateExtensionType(logger, context, userType, spec);
    } catch (NotFoundException e) {
        // TODO(knorton): Better error message.
        logger.log(TreeLogger.ERROR, "Unknown Type: " + typeName);
        throw new UnableToCompleteException();
    }
}

From source file:com.google.code.gwt.appcache.rebind.ApplicationCacheNetworkSectionGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    // Invoke the regular RPC generator:
    String result = rebindTypeByInheritedModule("com.google.gwt.user.RemoteService", logger, context, typeName);

    TypeOracle typeOracle = context.getTypeOracle();
    JClassType remoteService = typeOracle.findType(typeName);
    RemoteServiceRelativePath moduleRelativeUrl = remoteService.getAnnotation(RemoteServiceRelativePath.class);

    if (moduleRelativeUrl != null) {
        // add URL to network section:
        if (logger.isLoggable(Type.INFO)) {
            logger.log(Type.DEBUG,
                    "Found URL for NETWORK: section in cache-manifest: '" + moduleRelativeUrl.value() + "'");
        }//ww w . j a  v  a2 s  .c o m
        NetworkSectionArtifact artifact = new NetworkSectionArtifact(IFrameAppCacheLinker.class,
                moduleRelativeUrl.value());
        context.commitArtifact(logger, artifact);
    }

    return result;
}

From source file:com.tyf.gwtphp.rebind.PHPRemoteServiceGenerator.java

License:Open Source License

/**
 * This method overrides the default RemoteService interface proxy generator, 
 * gathers type information and passes it to the linker, in addition to
 * invoking the default generator.//from w  ww.j av a2s .c  o  m
 */
@Override
public RebindResult generateIncrementally(TreeLogger logger, GeneratorContext ctx, String requestedClass)
        throws UnableToCompleteException {

    TypeOracle typeOracle = ctx.getTypeOracle();
    String qualifiedClassName;
    String packageName, className;

    try {
        // get classType and save instance variables
        JClassType classType = typeOracle.getType(requestedClass);
        packageName = classType.getPackage().getName();
        className = classType.getSimpleSourceName();
        qualifiedClassName = packageName + "." + className;
        // prevent re-discovery
        if (generatedClasses.contains(qualifiedClassName))
            return super.generateIncrementally(logger, ctx, requestedClass);

        JClassType supertype = getSuperType(classType);
        ServiceArtifact artifact = new ServiceArtifact(classType.getQualifiedSourceName(),
                classType.getSimpleSourceName(), supertype != null ? supertype.getQualifiedSourceName() : null,
                supertype != null ? supertype.getSimpleSourceName() : null, classType.isInterface() != null,
                classType.isAbstract());

        // discover new custom objects, whose information must be known by
        // the server
        Set<ObjectArtifact> objectArtifacts = new HashSet<ObjectArtifact>();
        Set<JType> discoveredTypes = new HashSet<JType>();

        JMethod[] methods = classType.getMethods();
        // parse RPC methods
        for (JMethod method : methods) {
            JType returnType = method.getReturnType();
            JType[] paramTypes = method.getParameterTypes();
            String[] params = new String[paramTypes.length];
            String[] paramNames = new String[params.length];
            JClassType[] exceptionTypes = method.getThrows();
            String[] exceptions = new String[exceptionTypes.length];

            // getRpcTypeName recursively generates the type name, while
            // adding all discovered types to the set, flattening out 
            // arrays & generics, etc.
            String returnTypeName = TypeUtil.getPHPRpcTypeName(returnType, discoveredTypes);
            for (int i = 0; i < params.length; i++) {
                params[i] = TypeUtil.getPHPRpcTypeName(paramTypes[i], discoveredTypes);
                paramNames[i] = method.getParameters()[i].getName();
            }
            for (int i = 0; i < exceptions.length; i++) {
                exceptions[i] = TypeUtil.getPHPRpcTypeName(exceptionTypes[i], discoveredTypes);
            }

            // get type signature of the return type
            String returnTypeCRC = TypeUtil.getCRC(returnType);

            Function f = new Function(method.getName(), returnTypeName, returnTypeCRC, params, paramNames,
                    exceptions);

            artifact.putMethod(method.getName(), f);
        }
        for (JType type : discoveredTypes) {
            // logger.log(TreeLogger.INFO, type.getQualifiedSourceName());
            objectArtifacts.addAll(discoverObjects(type));
        }

        ctx.commitArtifact(logger, artifact);
        for (ObjectArtifact a : objectArtifacts) {
            ctx.commitArtifact(logger, a);
        }
    } catch (Exception e) {
        logger.log(TreeLogger.ERROR, "ERROR: " + e.getMessage(), e);
        return null;
    }

    return super.generateIncrementally(logger, ctx, requestedClass);
}

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

License:Open Source License

/**
 * @param serializerLogger//  w ww . j  a  v a2  s  .com
 * @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.rebind.NativeWorkerFactoryGenerator.java

License:Apache License

@Override
public void generateWorkerFactory(TreeLogger logger, GeneratorContext context, JClassType sourceType,
        String genName, PrintWriter out, ModuleDef modDef, JClassType workerEntryType)
        throws UnableToCompleteException {

    // native worker, so request worker compilation
    WorkerRequestArtifact request = new WorkerRequestArtifact(modDef.getCanonicalName(), modDef.getName());
    context.commitArtifact(logger, request);

    ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(sourceType.getPackage().getName(),
            genName);//from  ww w.ja v a  2 s.  co  m

    // imports and interface
    f.addImport(Worker.class.getName());
    f.addImport(WorkerImplNative.class.getName());
    f.addImplementedInterface(sourceType.getName());

    // new generated source file
    if (out != null) {
        SourceWriter sw = f.createSourceWriter(context, out);

        // @Override
        // public Worker createAndStart() {
        //   return WorkerImplNative.create("PLACEHOLDER_PATH"); }
        // Note: placeholder path will be replaced by linker
        sw.println("@Override");
        sw.println("public Worker createAndStart() {");
        sw.indent();
        sw.print("return WorkerImplNative.create(\"");
        sw.print(request.getRelativePlaceholderUrl());
        sw.println("\");");
        sw.outdent();
        sw.println("}");

        sw.commit(logger);
    }
}