Example usage for com.google.gwt.user.rebind SourceWriter commit

List of usage examples for com.google.gwt.user.rebind SourceWriter commit

Introduction

In this page you can find the example usage for com.google.gwt.user.rebind SourceWriter commit.

Prototype

void commit(TreeLogger logger);

Source Link

Usage

From source file:com.mvp4g.rebind.Mvp4gGenerator.java

License:Apache License

private RebindResult create(TreeLogger logger, GeneratorContext context, String moduleName)
        throws UnableToCompleteException {

    Date start = new Date();

    String generatedClassQualifiedName;

    try {/*  ww w . j a v a  2s.co m*/
        TypeOracle typeOracle = context.getTypeOracle();

        JClassType module = typeOracle.findType(moduleName);
        if (module == null) {
            logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + moduleName + "'", null);
            throw new UnableToCompleteException();
        }

        @SuppressWarnings("unchecked")
        Map<Class<? extends Annotation>, List<JClassType>> scanResult = AnnotationScanner.scan(logger,
                typeOracle, new Class[] { Presenter.class, History.class, Events.class, Service.class,
                        EventHandler.class });

        Mvp4gConfiguration configuration = new Mvp4gConfiguration(logger, context);

        String suffix = "Impl" + configuration.load(module, scanResult);

        generatedClassQualifiedName = module.getParameterizedQualifiedSourceName() + suffix;

        String packageName = module.getPackage().getName();
        String originalClassName = module.getSimpleSourceName();
        String generatedClassName = originalClassName + suffix;

        // check weather there is a usual version or not.
        if (checkAlreadyGenerated(logger, context, configuration)) {
            // Log
            logger.log(TreeLogger.INFO, "Reuse already generated files", null);
            // stop generating
            return new RebindResult(RebindMode.USE_EXISTING, packageName + "." + generatedClassName);
        }

        // Log
        logger.log(TreeLogger.INFO, "Start generate files ... ", null);

        // No, there is non. Create a new one.
        SourceWriter sourceWriter = getSourceWriter(logger, context, module, packageName, generatedClassName);

        if (sourceWriter != null) {
            logger.log(TreeLogger.INFO, "Generating source for " + generatedClassQualifiedName + " ", null);
            Mvp4gConfigurationFileWriter writer = new Mvp4gConfigurationFileWriter(sourceWriter, configuration);
            writer.writeConf();
            sourceWriter.commit(logger);
        } else {
            // don't expect this to occur, but could happen if an instance was
            // recently generated but not yet committed
            new RebindResult(RebindMode.USE_EXISTING, generatedClassQualifiedName);
        }

        Date end = new Date();

        logger.log(TreeLogger.INFO, "Mvp4g Compilation: " + (end.getTime() - start.getTime()) + "ms.");

        return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, packageName + "." + generatedClassName);
    } catch (InvalidMvp4gConfigurationException e) {
        logger.log(TreeLogger.ERROR, e.getMessage(), e);
        throw new UnableToCompleteException();
    }
}

From source file:com.mvp4g.rebind.Mvp4gRunAsyncGenerator.java

License:Apache License

private RebindResult create(JClassType originalType, TreeLogger logger, GeneratorContext context,
        String typeName) throws UnableToCompleteException {

    Date start = new Date();

    String packageName = originalType.getPackage().getName();
    String originalClassName = originalType.getSimpleSourceName();
    String generatedClassName = originalClassName + "Impl";
    String generatedClassQualifiedName = packageName + "." + generatedClassName;

    // check weather there is a usual version or not.
    if (checkAlreadyGenerated(logger, context, generatedClassQualifiedName)) {
        // Log//from   www  . j a va2s  . c o m
        logger.log(TreeLogger.INFO, "reuse already generated files", null);
        // stop generating
        return new RebindResult(RebindMode.USE_EXISTING, generatedClassQualifiedName);
    }

    logger.log(TreeLogger.INFO, "Generating writer for " + packageName + "." + generatedClassName, null);

    PrintWriter printWriter = context.tryCreate(logger, packageName, generatedClassName);

    ClassSourceFileComposerFactory classFactory = new ClassSourceFileComposerFactory(packageName,
            generatedClassName);

    classFactory.addImplementedInterface(originalType.getName());
    String[] classesToImport = getClassesToImport();
    for (String classToImport : classesToImport) {
        classFactory.addImport(classToImport);
    }

    if (printWriter != null) {
        SourceWriter sourceWriter = classFactory.createSourceWriter(context, printWriter);
        logger.log(TreeLogger.INFO, "Generating source for " + generatedClassQualifiedName + " ", null);
        writeClass(sourceWriter, getRunAsync(originalType));
        sourceWriter.commit(logger);
    }

    Date end = new Date();

    logger.log(TreeLogger.INFO, "Mvp4g Module Cretor: " + (end.getTime() - start.getTime()) + "ms.");

    return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, generatedClassQualifiedName);
}

From source file:com.ponysdk.ui.server.AddonListGenerator.java

License:Apache License

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

    final List<JClassType> ponyAddons = new ArrayList<JClassType>();

    final TypeOracle typeOracle = context.getTypeOracle();
    assert (typeOracle != null);

    JClassType classType = null;//  ww  w. j  a v  a  2  s. c om
    try {
        classType = typeOracle.getType(typeName);
    } catch (final NotFoundException e) {
        e.printStackTrace();
        return null;
    }

    final SourceWriter src = getSourceWriter(classType, context, logger);
    if (src == null) {
        return typeName + "Generated";
    }

    final JClassType[] types = typeOracle.getTypes();

    System.out.println("Generating AddonListGenerator " + typeName);
    System.out.println("\tAnalysing " + types.length + " types ...");

    for (final JClassType jClassType : types) {
        if (jClassType.isAnnotationPresent(PonyAddOn.class)) {
            System.out.println("\tAdding Pony Addon " + jClassType.getParameterizedQualifiedSourceName());
            ponyAddons.add(jClassType);
        }
    }

    // Here you would retrieve the metadata based on typeName for this Screen
    src.println("public List<AddonFactory> getAddonFactoryList() {");
    src.indent();
    src.println("List<AddonFactory> addonList = new ArrayList();");
    for (final JClassType addon : ponyAddons) {
        src.println("addonList.add(new AddonFactory(){");
        src.indent();
        src.println("public PTAddon newAddon(){");
        src.indent();
        src.println("PTAddon addon =  new " + addon.getParameterizedQualifiedSourceName() + "();");
        src.println("return addon;");
        src.outdent();
        src.println("}");
        src.println();

        src.println("public String getSignature(){");
        src.indent();
        src.println("return \"" + addon.getParameterizedQualifiedSourceName() + "\";");
        src.outdent();
        src.println("}");
        src.println();
        src.outdent();
        src.println("});");
    }
    src.println("return addonList;");
    src.outdent();
    src.println("}");

    src.commit(logger);
    System.out.println("Generating for: " + typeName);
    return typeName + "Generated";
}

From source file:com.rhizospherejs.gwt.rebind.MappingWriter.java

License:Open Source License

public void write() {
    SourceWriter sw = getSourceWriter();
    writeModelBridgeFactoryMethod(sw);/*from w  w w  .  ja  v  a  2 s  . c  om*/
    sw.println();
    writeMetaModelFactoryInterfaceImpl(sw);
    sw.println();
    writeModelBridgeImpl(sw);
    sw.println();
    writeMetaModelFactoryImpl(sw);
    sw.commit(logger);
}

From source file:com.seanchenxi.gwt.storage.rebind.StorageKeyProviderGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType keyProviderIntf = oracle.findType(typeName);
    JClassType toGenerate = keyProviderIntf.isInterface();

    if (toGenerate == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }//from  w  w  w .ja  v  a2 s. com

    String packageName = toGenerate.getPackage().getName();
    simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    model = new StorageKeyProviderModel(logger, toGenerate);
    model.loadMethods();

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(AbstractStorageKeyProvider.class.getCanonicalName());
    factory.addImplementedInterface(typeName);
    SourceWriter sw = factory.createSourceWriter(context, pw);
    writeMethods(sw);
    sw.commit(logger);
    return factory.getCreatedClassName();
}

From source file:com.seanchenxi.resteasy.autobean.generator.RESTServiceGenerator.java

License:Apache License

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

    TypeOracle oracle = context.getTypeOracle();

    String asyncTypeName = typeName + "Async";
    JClassType asyncType = null;//from  w  w w  .  java2  s .c om
    String packageName = null;
    String simpleName = null;
    try {
        asyncType = oracle.findType(asyncTypeName);
        asyncType = asyncType.isInterface();
        packageName = asyncType.getPackage().getName();
        simpleName = asyncType.getSimpleSourceName() + "Impl";
    } catch (Exception e) {
        logger.log(TreeLogger.ERROR, asyncTypeName + " is not found or is not an interface", e);
        throw new UnableToCompleteException();
    }

    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);
    if (printWriter == null) {
        return packageName + "." + simpleName;
    }

    // This method will complete httpMethods map and restPaths map;
    parseSyncType(typeName, oracle, logger);

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.addImplementedInterface(asyncTypeName);
    factory.setSuperclass(RESTServiceProxy.class.getName());
    factory.addImport(RequestBuilder.class.getName());
    factory.addImport(RESTRequest.class.getName());

    SourceWriter writer = factory.createSourceWriter(context, printWriter);
    writer.indent();
    writer.println("");
    for (JMethod asyncMethod : asyncType.getMethods()) {
        writeAsyncMethod(asyncTypeName, asyncMethod, writer, logger);
    }
    writer.outdent();
    writer.commit(logger);
    return factory.getCreatedClassName();
}

From source file:com.seanchenxi.resteasy.autobean.generator.ThrowableFactoryGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType type = oracle.findType(typeName);
    type = type.isInterface();/*from  www.  j  a va2s  .c om*/
    if (type == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not found");
        throw new UnableToCompleteException();
    }

    String packageName = type.getPackage().getName();
    String simpleName = type.getSimpleSourceName() + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);
    if (printWriter == null) {
        return packageName + "." + simpleName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.addImplementedInterface(typeName);
    factory.addImport(Throwable.class.getName());

    SourceWriter writer = factory.createSourceWriter(context, printWriter);
    writer.indent();
    writer.println("@Override");
    writer.println("public Throwable create(String className, String message){");
    for (String qname : getAllThrowableTypes(oracle, logger)) {
        writer.println("   if(\"" + qname + "\".equals(className)) {");
        writer.println("      return new " + qname + " (message);");
        writer.println("   }");
    }
    writer.println("   return new Throwable(message);");
    writer.println("}");
    writer.outdent();
    writer.commit(logger);
    return factory.getCreatedClassName();
}

From source file:com.sencha.gxt.core.rebind.AbstractCreator.java

License:sencha.com license

public final String create() throws UnableToCompleteException {

    PrintWriter pw = context.tryCreate(getLogger(), getPackageName(), getSimpleName());
    if (pw == null) {
        // someone else already generated type, no need to change it
        return getPackageName() + "." + getSimpleName();
    }/*from w w w.  java2s.  c  om*/

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(getPackageName(),
            getSimpleName());
    configureFactory(factory);

    SourceWriter sw = factory.createSourceWriter(getContext(), pw);
    create(sw);

    sw.commit(getLogger());
    return factory.getCreatedClassName();
}

From source file:com.sencha.gxt.core.rebind.BindingPropertyGenerator.java

License:sencha.com license

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();

    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(Type.ERROR, typeName + " is not an interface");
        throw new UnableToCompleteException();
    }/* w ww .j  a  v a  2s .c  o  m*/

    PropertyName annotation = toGenerate.getAnnotation(PropertyName.class);
    if (annotation == null) {
        logger.log(Type.ERROR, "Cannot generate with a @PropertyName anntation on the type");
        throw new UnableToCompleteException();
    }

    String propertyName = annotation.value();
    SelectionProperty property;
    String value;
    try {
        property = context.getPropertyOracle().getSelectionProperty(logger, propertyName);
        value = property.getCurrentValue();
    } catch (BadPropertyValueException e) {
        logger.log(Type.ERROR, "Error occured loading property: ", e);
        throw new UnableToCompleteException();
    }
    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "_" + value;
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);
    SourceWriter sw = factory.createSourceWriter(context, pw);

    for (JMethod method : toGenerate.getMethods()) {
        if (method.getReturnType().isPrimitive() != JPrimitiveType.BOOLEAN && !method.getReturnType().isClass()
                .getQualifiedSourceName().equals(Name.getSourceNameForClass(Boolean.class))) {
            logger.log(Type.ERROR, "Methods must return boolean or Boolean");
            throw new UnableToCompleteException();
        }
        sw.println("%1$s {", method.getReadableDeclaration(false, true, true, true, true));

        PropertyValue val = method.getAnnotation(PropertyValue.class);
        if (val == null) {
            logger.log(Type.ERROR, "Method must have a @PropertyValue annotation");
            throw new UnableToCompleteException();
        }

        if (!property.getPossibleValues().contains(val.value()) && val.warn()) {
            logger.log(Type.WARN,
                    "Value '" + val
                            + "' is not present in the current set of possible values for selection property "
                            + propertyName);
        }
        sw.indentln("return %1$b;", val.value().equals(value));

        sw.println("}");
    }

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.sencha.gxt.core.rebind.XTemplatesGenerator.java

License:sencha.com license

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // make sure it is an interface
    TypeOracle oracle = context.getTypeOracle();

    this.logger = logger;

    this.xTemplatesInterface = oracle.findType(Name.getSourceNameForClass(XTemplates.class));
    this.listInterface = oracle.findType(Name.getSourceNameForClass(List.class));
    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }/*  www. ja v a  2  s  .  c  om*/
    if (!toGenerate.isAssignableTo(xTemplatesInterface)) {
        logger.log(Type.ERROR, "This isn't a XTemplates subtype...");
        throw new UnableToCompleteException();
    }

    // Get the name of the new type
    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);
    // imports
    factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(SafeHtml.class));
    factory.addImport(Name.getSourceNameForClass(SafeHtmlBuilder.class));

    // Loop through the formatters declared for this type and supertypes
    FormatCollector formatters = new FormatCollector(context, logger, toGenerate);
    MethodCollector invokables = new MethodCollector(context, logger, toGenerate);

    SourceWriter sw = factory.createSourceWriter(context, pw);

    for (JMethod method : toGenerate.getOverridableMethods()) {
        TreeLogger l = logger.branch(Type.DEBUG, "Creating XTemplate method " + method.getName());
        final String template;
        XTemplate marker = method.getAnnotation(XTemplate.class);
        if (marker == null) {
            l.log(Type.ERROR, "Unable to create template for method " + method.getReadableDeclaration()
                    + ", this may cause other failures.");
            continue;
        } else {
            if (marker.source().length() != 0) {
                if (marker.value().length() != 0) {
                    l.log(Type.WARN, "Found both source file and inline template, using source file");
                }

                InputStream stream = getTemplateResource(context, method.getEnclosingType(), l,
                        marker.source());
                if (stream == null) {
                    l.log(Type.ERROR, "No data could be loaded - no data at path " + marker.source());
                    throw new UnableToCompleteException();
                }
                template = Util.readStreamAsString(stream);
            } else if (marker.value().length() != 0) {
                template = marker.value();
            } else {
                l.log(Type.ERROR, "XTemplate annotation found with no contents, cannot generate method "
                        + method.getName() + ", this may cause other failures.");
                continue;
            }
        }

        XTemplateParser p = new XTemplateParser(
                l.branch(Type.DEBUG, "Parsing provided template for " + method.getReadableDeclaration()));
        TemplateModel m = p.parse(template);
        SafeHtmlTemplatesCreator safeHtml = new SafeHtmlTemplatesCreator(context,
                l.branch(Type.DEBUG, "Building SafeHtmlTemplates"), method);

        sw.println(method.getReadableDeclaration(false, true, true, false, true) + "{");
        sw.indent();

        Map<String, JType> params = new HashMap<String, JType>();
        for (JParameter param : method.getParameters()) {
            params.put(param.getName(), param.getType());
        }
        Context scopeContext = new Context(context, l, params, formatters);
        // if there is only one parameter, wrap the scope up so that properties
        // can be accessed directly
        if (method.getParameters().length == 1) {
            JParameter param = method.getParameters()[0];
            scopeContext = new Context(scopeContext, param.getName(), param.getType());

        }

        String outerSHVar = scopeContext.declareLocalVariable("outer");
        sw.println("SafeHtml %1$s;", outerSHVar);

        buildSafeHtmlTemplates(outerSHVar, sw, m, safeHtml, scopeContext, invokables);

        sw.println("return %1$s;", outerSHVar);

        sw.outdent();
        sw.println("}");

        safeHtml.create();
    }

    // Save the file and return its type name
    sw.commit(logger);
    return factory.getCreatedClassName();
}