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.dom_distiller.client.JsTestEntryGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typename)
        throws UnableToCompleteException {
    String packageName = "com.dom_distiller.client";
    String outputClassname = "JsTestBuilderImpl";

    List<TestCase> testCases = getTestCases(logger, context);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, outputClassname);
    composer.addImplementedInterface("com.dom_distiller.client.JsTestSuiteBuilder");
    PrintWriter printWriter = context.tryCreate(logger, packageName, outputClassname);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("JsTestBuilderImpl () {");
        sourceWriter.println("}");
        sourceWriter.println("public JsTestSuiteBase build() {");
        sourceWriter.indent();/* w  w w.j  a v a  2 s  .  co  m*/
        sourceWriter.println("JsTestSuiteBase testSuite = new JsTestSuiteBase();");
        for (TestCase ts : testCases) {
            String className = ts.classType.getName();
            String qualifiedClassName = ts.classType.getPackage().getName() + "." + className;
            sourceWriter.println("testSuite.addTestCase(");
            sourceWriter.println("        new JsTestSuiteBase.TestCaseFactory() {");
            sourceWriter.println("            @Override");
            sourceWriter.println("            public JsTestCase build() {");
            sourceWriter.println("                return new " + className + "();");
            sourceWriter.println("            }");
            sourceWriter.println("        }, \"" + qualifiedClassName + "\")");
            sourceWriter.indent();
            for (JMethod test : ts.tests) {
                String methodName = test.getName();
                sourceWriter.println(".addTest(");
                sourceWriter.println("        new JsTestSuiteBase.TestCaseRunner() {");
                sourceWriter.println("            @Override");
                sourceWriter.println("            public void run(JsTestCase testCase) throws Exception {");
                sourceWriter.println("                ((" + className + ")testCase)." + methodName + "();");
                sourceWriter.println("            }");
                sourceWriter.println("        }, \"" + methodName + "\")");
            }
            sourceWriter.println(";");
            sourceWriter.outdent();
        }
        sourceWriter.println("return testSuite;");
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.ekuefler.supereventbus.rebind.EventRegistrationGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    try {//from w w w .j  a  v  a 2s. c  o m
        JClassType eventBinderType = context.getTypeOracle().getType(typeName);
        JClassType targetType = getTargetType(eventBinderType, context.getTypeOracle());
        SourceWriter writer = createSourceWriter(logger, context, eventBinderType, targetType);
        if (writer != null) { // Otherwise the class was already created
            new EventRegistrationWriter(logger).writeGetMethods(targetType, writer);
            writer.commit(logger);
        }
        return new StringBuilder().append(eventBinderType.getPackage().getName()).append('.')
                .append(getSimpleGeneratedClassName(eventBinderType)).toString();
    } catch (NotFoundException e) {
        logger.log(Type.ERROR, "Error generating " + typeName, e);
        throw new UnableToCompleteException();
    }
}

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

License:Apache License

/**
 * Generates the image bundle implementation class, checking each method for
 * validity as it is encountered.//from  ww  w.  j a v  a 2 s.co  m
 */
private String generateImplClass(final TreeLogger logger, final GeneratorContext context,
        final JClassType userType, final JMethod[] imageMethods) throws UnableToCompleteException {
    // Lookup the type info for AbstractImagePrototype so that we can check
    // for
    // the proper return type
    // on image bundle methods.
    final JClassType abstractImagePrototype;
    try {
        abstractImagePrototype = userType.getOracle().getType(ABSTRACTIMAGEPROTOTYPE_QNAME);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "GWT " + ABSTRACTIMAGEPROTOTYPE_QNAME + " class is not available", e);
        throw new UnableToCompleteException();
    }

    // Compute the package and class names of the generated class.
    String pkgName = userType.getPackage().getName();
    String subName = computeSubclassName(userType);

    // 11pc
    String pkgPrefix = pkgName.replace('.', '/');

    if (pkgPrefix.length() > 0)
        pkgPrefix += "/";

    // Begin writing the generated source.
    ClassSourceFileComposerFactory f = new ClassSourceFileComposerFactory(pkgName, subName);
    f.addImport(ABSTRACTIMAGEPROTOTYPE_QNAME);
    f.addImport(CLIPPEDIMAGEPROTOTYPE_QNAME);
    f.addImport(GWT_QNAME);
    f.addImport(HASHMAP_QNAME);
    f.addImport(IMAGE_QNAME);
    f.addImplementedInterface(userType.getQualifiedSourceName());

    PrintWriter pw = context.tryCreate(logger, pkgName, subName);

    if (pw != null) {
        SourceWriter sw = f.createSourceWriter(context, pw);

        // Build a compound image from each individual image.
        SkinBundleBuilder bulder = new SkinBundleBuilder();

        // Store the computed image names so that we don't have to lookup
        // them up again.

        // 11pc
        List<String> imageResNames = getSkinImages(logger);

        for (String imageName : imageResNames)
            bulder.assimilate(logger, imageName);

        /*
        for (JMethod method : imageMethods) {
                    String branchMsg = "Analyzing method '" + method.getName()
                          + "' in type " + userType.getQualifiedSourceName();
                    TreeLogger branch = logger.branch(TreeLogger.DEBUG, branchMsg,
                          null);
                
                    // Verify that this method is valid on an image bundle.
                    if (method.getReturnType() != abstractImagePrototype) {
                       branch.log(TreeLogger.ERROR, "Return type must be "
                             + ABSTRACTIMAGEPROTOTYPE_QNAME, null);
                       throw new UnableToCompleteException();
                    }
                
                    if (method.getParameters().length > 0) {
                       branch.log(TreeLogger.ERROR,
                             "Method must have zero parameters", null);
                       throw new UnableToCompleteException();
                    }
                
                    // Find the associated imaged resource.
                    String imageResName = getImageResourceName(branch,
                          new JMethodOracleImpl(method));
                    assert (imageResName != null);
                    imageResNames.add(imageResName);
                    bulder.assimilate(logger, imageResName);
        }
        */
        // Write the compound image into the output directory.
        //         String bundledImageUrl = bulder.writeBundledImage(logger, context);
        String bundledImageUrl = "yeayeaa";

        // Emit a constant for the composite URL. Note that we prepend the
        // module's base URL so that the module can reference its own
        // resources
        // independently of the host HTML page.
        sw.print("private static final String IMAGE_BUNDLE_URL = GWT.getModuleBaseURL() + \"");
        sw.print(escape(bundledImageUrl));
        sw.println("\";");
        /*
                 // Generate an implementation of each method.
                 int imageResNameIndex = 0;
                 for (JMethod method : imageMethods) {
                    generateImageMethod(bulder, sw, method, imageResNames
          .get(imageResNameIndex++));
                 }
        */

        generateImageDef(bulder, sw, imageResNames);

        sw.println("@Override");
        sw.println("public AbstractImagePrototype get(String image) {");
        sw.indent();
        sw.println("return imageMap.get(image);");
        sw.outdent();
        sw.print("}");

        sw.println("@Override");
        sw.println("public HashMap<String, HashMap<String, String>>   getProperties() {");
        sw.indent();
        sw.println("return null;");
        sw.outdent();
        sw.print("}");

        // Finish.
        sw.commit(logger);
    }

    return f.getCreatedClassName();
}

From source file:com.emitrom.pilot.core.shared.rebind.BeanModelGenerator.java

License:Apache License

protected String createBean(JClassType bean, TreeLogger logger, GeneratorContext context) throws Exception {
    final String genPackageName = bean.getPackage().getName();
    final String genClassName = "Bean_" + bean.getQualifiedSourceName().replace(".", "_");

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(Bean.class.getCanonicalName());
    composer.addImport(Bean.class.getName());
    composer.addImport(NestedModelUtil.class.getName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        List<JMethod> setters = findSetters(bean);
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("public " + genClassName + "(){");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
                                                                           // or
                                                                           // is
            sw.println("beanProperties.add(\"" + p + "\");");
        }//from  w  w  w. ja  v a 2 s  . c  o m
        sw.println("}");

        createGetMethods(getters, sw, bean.getQualifiedSourceName());
        createSetMethods(setters, sw, bean.getQualifiedSourceName());

        // delegate equals to bean
        sw.println("public boolean equals(Object obj) {");
        sw.println("  if (obj instanceof " + "Bean" + ") {");
        sw.println("    obj = ((Bean)obj).getBean();");
        sw.println("  }");
        sw.println("  return bean.equals(obj);");
        sw.println("}");

        // delegate hashCode to bean
        sw.println("public int hashCode(){");
        sw.println("  return bean.hashCode();");
        sw.println("}");

        sw.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.emitrom.touch4j.rebind.BeanModelGenerator.java

License:Open Source License

protected String createBean(JClassType bean, TreeLogger logger, GeneratorContext context) throws Exception {
    final String genPackageName = bean.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_");

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModel.class.getCanonicalName());
    composer.addImport(BeanModel.class.getName());
    composer.addImport(NestedModelUtil.class.getName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        List<JMethod> setters = findSetters(bean);
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("public " + genClassName + "(){");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
            // or
            // is
            sw.println("beanProperties.add(\"" + p + "\");");
        }/*w  w w  .ja  v  a2  s .  c  o  m*/
        sw.println("}");

        createGetMethods(getters, sw, bean.getQualifiedSourceName());
        createSetMethods(setters, sw, bean.getQualifiedSourceName());

        // delegate equals to bean
        sw.println("public boolean equals(Object obj) {");
        sw.println("  if (obj instanceof " + "BeanModel" + ") {");
        sw.println("    obj = ((BeanModel)obj).getBean();");
        sw.println("  }");
        sw.println("  return bean.equals(obj);");
        sw.println("}");

        // delegate hashCode to bean
        sw.println("public int hashCode(){");
        sw.println("  return bean.hashCode();");
        sw.println("}");

        sw.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.example.gwt.dagger2.rebind.VersionGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    String result = null;/* w  w w . j av  a2  s.c o  m*/
    try {
        String version = findVersion(logger, context);
        JClassType classType = context.getTypeOracle().getType(typeName);
        String packageName = packageNameFrom(classType);
        String simpleName = simpleNameFrom(classType);
        result = packageName + '.' + simpleName;
        SourceWriter source = getSourceWriter(logger, context, classType);
        if (source != null) { //? Otherwise, work needs to be done.
            source.println();
            source.println("private String value;");
            source.println();
            source.println("public " + simpleName + "() {");
            populateInstanceFactory(logger, context, typeName, source, version);
            source.println("}");
            source.println();
            source.println("@Override");
            source.println("public String getValue() {");
            source.println(" return value;");
            source.println("}");
            source.println();
            source.commit(logger);
            //emitVersionArtifact(logger, context, version);
        }
    } catch (NotFoundException nfe) {
        logger.log(Type.ERROR, "Could not find extension point type '" + typeName + "'!", nfe);
        throw new UnableToCompleteException();
    }
    return result;
}

From source file:com.extjs.gxt.ui.rebind.core.BeanModelGenerator.java

License:sencha.com license

protected String createFactory(JClassType bean, String beanModelName, TreeLogger logger,
        GeneratorContext context) throws Exception {
    final String genPackageName = BeanModelLookup.class.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_") + "_Factory";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModelFactory.class.getCanonicalName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        SourceWriter sw = composer.createSourceWriter(context, pw);
        sw.println("public BeanModel newInstance() {");
        sw.println("return new " + beanModelName + "();");
        sw.println("}");
        sw.commit(logger);
    }/*from w  w w . jav a 2s .c o m*/
    return composer.getCreatedClassName();
}

From source file:com.extjs.gxt.ui.rebind.core.BeanModelGenerator.java

License:sencha.com license

protected String createBean(JClassType bean, TreeLogger logger, GeneratorContext context) throws Exception {
    final String genPackageName = bean.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_");

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModel.class.getCanonicalName());
    composer.addImport(BeanModel.class.getName());
    composer.addImport(NestedModelUtil.class.getName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        List<JMethod> setters = findSetters(bean);
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("public " + genClassName + "(){");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get or
            // is
            sw.println("beanProperties.add(\"" + p + "\");");
        }//www . j  av a 2s  .  co m
        sw.println("}");

        createGetMethods(getters, sw, bean.getQualifiedSourceName());
        createSetMethods(setters, sw, bean.getQualifiedSourceName());

        // delegate equals to bean
        sw.println("public boolean equals(Object obj) {");
        sw.println("  if (obj instanceof " + "BeanModel" + ") {");
        sw.println("    obj = ((BeanModel)obj).getBean();");
        sw.println("  }");
        sw.println("  return bean.equals(obj);");
        sw.println("}");

        // delegate hashCode to bean
        sw.println("public int hashCode(){");
        sw.println("  return bean.hashCode();");
        sw.println("}");

        sw.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.gafactory.core.rebind.PropertyAccessGenerator.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();

    propertyAccessInterface = oracle.findType(Name.getSourceNameForClass(PropertyAccess.class));
    modelKeyProviderInterface = oracle.findType(Name.getSourceNameForClass(ModelKeyProvider.class));
    valueProviderInterface = oracle.findType(Name.getSourceNameForClass(ValueProvider.class));
    labelProviderInterface = oracle.findType(Name.getSourceNameForClass(LabelProvider.class));
    JClassType toGenerate = oracle.findType(typeName).isInterface();
    if (toGenerate == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }// ww  w.j  a  v  a  2 s . co  m
    if (!toGenerate.isAssignableTo(propertyAccessInterface)) {
        logger.log(Type.ERROR, "This isn't a PropertyAccess 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;
    }

    // start making the class, with basic imports
    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);
    SourceWriter sw = factory.createSourceWriter(context, pw);

    // for each method,
    for (JMethod m : toGenerate.getOverridableMethods()) {
        TreeLogger l = logger.branch(Type.DEBUG, "Building method: " + m.getReadableDeclaration());

        // no support for params at this time
        if (m.getParameters().length != 0) {
            l.log(Type.ERROR, "Method " + m.toString() + " must not have parameters.");
            throw new UnableToCompleteException();
        }

        // ask for the types that provide the property data
        JClassType ret = m.getReturnType().isClassOrInterface();
        final AbstractCreator c;
        if (ret.isAssignableTo(valueProviderInterface)) {
            c = new ValueProviderCreator(context, l, m);
        } else if (ret.isAssignableTo(modelKeyProviderInterface)) {
            c = new ModelKeyProviderCreator(context, l, m);
        } else if (ret.isAssignableTo(labelProviderInterface)) {
            c = new LabelProviderCreator(context, l, m);
        } else {
            logger.log(Type.ERROR, "Method uses a return type that cannot be generated");
            throw new UnableToCompleteException();
        }
        c.create();
        // build the method
        // public ValueProvider<T, V> name() { return NameValueProvider.instance;
        // }
        sw.println("public %1$s %2$s() {", m.getReturnType().getQualifiedSourceName(), m.getName());
        sw.indentln("return %1$s;", c.getInstanceExpression());
        sw.println("}");
    }

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.google.code.gwt.rest.rebind.BeanConverterGenerator.java

License:Apache License

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

    Map<String, Object> contextMap = createContextMap();

    try {/*from ww w. j  a v  a  2  s .  c o  m*/
        TypeOracle oracle = context.getTypeOracle();
        JClassType type = oracle.findType(typeName);

        // Define creation class name
        String packageName = type.getPackage().getName();
        String simpleSourceName = type.getName().replace('.', '_') + "Impl";

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

        // set SuperClass and Interface
        JClassType beanType = type.getImplementedInterfaces()[0].isParameterized().getTypeArgs()[0];

        ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName,
                simpleSourceName);
        if (type.isInterface() != null) {
            factory.setSuperclass(
                    AbstractBeanConverter.class.getName() + "<" + beanType.getQualifiedSourceName() + ">");
            factory.addImplementedInterface(typeName);
        } else {
            factory.setSuperclass(typeName);
        }

        logger.log(logLevel, "create FormParamConverter " + beanType);

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

        StringBuilder converterDeclarations = new StringBuilder();
        StringBuilder convertLogic = new StringBuilder();

        contextMap.put("typeName", beanType.getQualifiedSourceName());

        // call super class FormParamConverter

        JClassType superClass = beanType.getSuperclass();
        if (superClass != null) {
            if (!superClass.getQualifiedSourceName().equals(Object.class.getName())) {
                contextMap.put("actualType", superClass.getQualifiedSourceName());
                contextMap.put("propertyName", "__super__");
                converterDeclarations.append(ACTUAL_TYPE_CONVERTER.resolve(contextMap));
                convertLogic.append(SUPERTYPE_CONERTER.resolve(contextMap));
            }
        }

        for (JMethod method : beanType.getMethods()) {

            if (!isGetter(method)) {
                continue;
            }

            JClassType returnType = method.getReturnType().isClass();
            if (returnType == null) {
                returnType = method.getReturnType().isInterface();
            }

            contextMap.put("propertyName", toPropertyName(method));
            contextMap.put("getterName", method.getName());
            contextMap.put("propertyType", method.getReturnType().getQualifiedSourceName());

            if (returnType != null && returnType.isAssignableTo(oracle.findType(Map.class.getName()))) {
                convertLogic.append(MAP_CONVERTER.resolve(contextMap));
                continue;
            }

            if (returnType != null && returnType.isAssignableTo(oracle.findType(JsArray.class.getName()))) {
                JClassType actualType = returnType.isParameterized().getTypeArgs()[0];

                contextMap.put("actualType", actualType.getQualifiedSourceName());

                converterDeclarations.append(ACTUAL_TYPE_CONVERTER.resolve(contextMap));
                convertLogic.append(LIST_CONVERTER.resolve(contextMap));
                continue;
            }

            if (isReturnTypeJdkTypeOrPrimitiveType(method)) {
                convertLogic.append(PRIMITIVE_TYPE_CONVERTER.resolve(contextMap));
                continue;
            }
            converterDeclarations.append(PROPERTY_COMVERTER.resolve(contextMap));
            convertLogic.append(BEAN_CONVERTER.resolve(contextMap));

        }

        contextMap.put("converterDeclarations", converterDeclarations);
        contextMap.put("convertLogic", convertLogic);

        String mainCode = MAIN_CLASS.resolve(contextMap);
        logger.log(logLevel, "create souce " + simpleSourceName + " \n" + mainCode);
        sw.print(mainCode);
        sw.commit(logger);

        return packageName + "." + simpleSourceName;
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }
}