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

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

Introduction

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

Prototype

void indent();

Source Link

Usage

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.  j a  v  a  2  s.  c  o m*/
    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();
}

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

License:sencha.com license

/**
 * Handles a given template chunk container by creating a method in the
 * safeHtmlTemplates impl//from   w ww .  java  2s  . c om
 * 
 * @param sw the current sourcewriter
 * @param wrapper the chunk container to act recursively on
 * @param safeHtml creator to add new SafeHtml calls to
 * @param scopeContext current scope to make method calls to
 * @param invokables
 * @throws UnableToCompleteException
 */
private void buildSafeHtmlTemplates(String safeHtmlVar, SourceWriter sw, ContainerTemplateChunk wrapper,
        SafeHtmlTemplatesCreator safeHtml, Context scopeContext, MethodCollector invokables)
        throws UnableToCompleteException {

    // debugging section to see what is about to be printed
    sw.beginJavaDocComment();
    sw.print(wrapper.toString());
    sw.endJavaDocComment();

    // make a new interface method for this content
    StringBuilder sb = new StringBuilder();
    List<String> paramTypes = new ArrayList<String>();
    List<String> params = new ArrayList<String>();

    // write out children to local vars or to the template
    int argCount = 0;
    for (TemplateChunk chunk : wrapper.children) {
        if (chunk instanceof ContentChunk) {
            ContentChunk contentChunk = (ContentChunk) chunk;
            // build up the template
            if (contentChunk.type == ContentType.LITERAL) {
                sb.append(contentChunk.content);
            } else if (contentChunk.type == ContentType.CODE) {
                sb.append("{").append(argCount++).append("}");
                paramTypes.add("java.lang.String");
                StringBuffer expr = new StringBuffer("\"\" + (");

                // parse out the quoted string literals first
                Matcher str = Pattern.compile("\"[^\"]+\"").matcher(contentChunk.content);
                TreeLogger code = logger.branch(Type.DEBUG,
                        "Parsing code segment: \"" + contentChunk.content + "\"");
                int lastMatchEnd = 0;
                while (str.find()) {
                    int begin = str.start(), end = str.end();
                    String escapedString = str.group();
                    String unmatched = contentChunk.content.substring(lastMatchEnd, begin);

                    appendCodeBlockOperatorOrIdentifier(scopeContext, expr, code, unmatched);

                    expr.append(escapedString);
                    lastMatchEnd = end;
                }

                //finish rest of non-string-lit expression
                appendCodeBlockOperatorOrIdentifier(scopeContext, expr, code,
                        contentChunk.content.substring(lastMatchEnd));

                params.add(expr.append(")").toString());
                code.log(Type.DEBUG, "Final compiled expression: " + expr);
            } else if (contentChunk.type == ContentType.REFERENCE) {
                sb.append("{").append(argCount++).append("}");

                JType argType = scopeContext.getType(contentChunk.content);
                if (argType == null) {
                    logger.log(Type.ERROR, "Reference could not be found: '" + contentChunk.content
                            + "'. Please fix the expression in your template.");
                    throw new UnableToCompleteException();
                }
                paramTypes.add(argType.getParameterizedQualifiedSourceName());
                params.add(scopeContext.deref(contentChunk.content));

            } else {
                assert false : "Content type not supported + " + contentChunk.type;
            }

        } else if (chunk instanceof ControlChunk) {
            ControlChunk controlChunk = (ControlChunk) chunk;
            // build logic, get scoped name
            boolean hasIf = controlChunk.controls.containsKey("if");
            boolean hasFor = controlChunk.controls.containsKey("for");

            if (!hasIf && !hasFor) {
                logger.log(Type.ERROR, "<tpl> tag did not define a 'for' or 'if' attribute!");
                throw new UnableToCompleteException();
            }

            // declare a sub-template, and stash content in there, interleaving it
            // into the current template
            String subTemplate = scopeContext.declareLocalVariable("subTemplate");
            String templateInBlock = scopeContext.declareLocalVariable("innerTemplate");
            sb.append("{").append(argCount++).append("}");
            paramTypes.add("com.google.gwt.safehtml.shared.SafeHtml");
            params.add(subTemplate);
            sw.println("SafeHtml %1$s;", subTemplate);
            sw.println("SafeHtmlBuilder %1$s_builder = new SafeHtmlBuilder();", subTemplate);

            // find the context that should be passed to the child template
            final Context childScope;

            // if we have both for and if, if needs to wrap the for
            if (hasIf) {
                ConditionParser p = new ConditionParser(logger);
                List<Token> tokens = p.parse(controlChunk.controls.get("if"));
                StringBuilder condition = new StringBuilder();
                for (Token t : tokens) {
                    switch (t.type) {
                    case ExpressionLiteral:
                        condition.append(t.contents);
                        break;
                    case MethodInvocation:
                        Matcher invoke = Pattern.compile("([a-zA-Z0-9\\._]+)\\:([a-zA-Z0-9_]+)\\(([^\\)]*)\\)")
                                .matcher(t.contents);
                        invoke.matches();
                        String deref = scopeContext.deref(invoke.group(1));
                        String methodName = invoke.group(2);
                        String args = "";
                        for (String a : invoke.group(3).split(",")) {
                            String possible = scopeContext.deref(a);
                            args += possible == null ? a : possible;
                        }

                        condition.append(invokables.getMethodInvocation(methodName, deref, args));
                        break;
                    case Reference:
                        condition.append("(").append(scopeContext.deref(t.contents)).append(")");
                        break;
                    default:
                        logger.log(Type.ERROR, "Unexpected token type: " + t.type);
                        throw new UnableToCompleteException();
                    }
                }
                sw.println("if (%1$s) {", condition.toString());
                sw.indent();
            }
            // if there is a for, print it out, and change scope
            if (hasFor) {
                String loopRef = controlChunk.controls.get("for");

                JType collectionType = scopeContext.getType(loopRef);
                if (collectionType == null) {
                    logger.log(Type.ERROR, "Reference in 'for' attribute could not be found: '" + loopRef
                            + "'. Please fix the expression in your template.");
                    throw new UnableToCompleteException();
                }
                final JType localType;// type accessed within the loop
                final String localAccessor;// expr to access looped instance, where
                                           // %1$s is the loop obj, and %2$s is the
                                           // int index
                if (collectionType.isArray() != null) {
                    localType = collectionType.isArray().getComponentType();
                    localAccessor = "%1$s[%2$s]";
                } else {// List subtype
                    localType = ModelUtils.findParameterizationOf(listInterface,
                            collectionType.isClassOrInterface())[0];
                    localAccessor = "%1$s.get(%2$s)";
                }

                String loopVar = scopeContext.declareLocalVariable("i");
                // make sure the collection isnt null
                sw.println("if (%1$s != null) {", scopeContext.deref(loopRef));
                sw.indent();
                sw.println("for (int %1$s = 0; %1$s < %2$s; %1$s++) {", loopVar,
                        scopeContext.derefCount(loopRef));
                String itemExpr = String.format(localAccessor, scopeContext.deref(loopRef), loopVar);
                childScope = new Context(scopeContext, itemExpr, localType);
                childScope.setCountVar(loopVar);
                sw.indent();
            } else {
                // if no for, use the same scope as the outer content
                childScope = scopeContext;
            }
            // generate a subtemplate, insert that
            sw.println("SafeHtml %1$s;", templateInBlock);
            buildSafeHtmlTemplates(templateInBlock, sw, controlChunk, safeHtml, childScope, invokables);
            sw.println("%1$s_builder.append(%2$s);", subTemplate, templateInBlock);

            // close up the blocks
            if (hasFor) {
                sw.outdent();
                sw.println("}");
                sw.outdent();
                sw.println("}");
            }
            if (hasIf) {
                sw.outdent();
                sw.println("}");
            }

            sw.println("%1$s = %1$s_builder.toSafeHtml();", subTemplate);

        } else {
            assert false : "Unsupported chunk type: " + chunk.getClass();
        }
    }

    String methodName = safeHtml.addTemplate(sb.toString(), paramTypes);
    sw.beginJavaDocComment();
    sw.println("safehtml content:");
    sw.indent();
    sw.println(sb.toString());
    sw.outdent();
    sw.println("params:");
    sw.indent();
    sw.print(args(params));
    sw.outdent();
    sw.endJavaDocComment();
    sw.println("%4$s = %1$s.%2$s(%3$s);", safeHtml.getInstanceExpression(), methodName, args(params),
            safeHtmlVar);
}

From source file:com.smartgwt.rebind.AnnotationMetaBeanFactoryGenerator.java

License:Open Source License

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

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "AnnotationMetaFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.AnnotationMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter//from ww  w .j av  a 2  s  .  c  o  m
                .println("// This class lovingly generated by " + this.getClass().getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        Set<JClassType> typesGenerated = new HashSet<JClassType>();

        // Collect the types ...
        for (JClassType classType : oracle.getTypes()) {
            BeanFactory.Generate annotation = classType.getAnnotation(BeanFactory.Generate.class);

            if (annotation != null) {
                TreeLogger annotationLogger = logger.branch(TreeLogger.DEBUG,
                        "Processing @BeanFactory.Generate annotation on " + classType.getQualifiedSourceName());

                Class[] value = annotation.value();
                if (value.length == 0) {
                    // No value supplied, so we use the class the annotation was applied to
                    if (!typesGenerated.contains(classType)) {
                        typesGenerated.add(classType);
                        generateFactory(classType, annotationLogger, context, sourceWriter);
                    }
                } else {
                    // Some values were supplied, so we use them, and not the class itself
                    for (Class klass : value) {
                        JClassType klassValue = oracle.findType(klass.getCanonicalName());
                        if (klassValue == null) {
                            annotationLogger.log(TreeLogger.ERROR,
                                    "Could not find " + klass.getName() + " in source classpath.");
                            throw new UnableToCompleteException();
                        } else {
                            if (!typesGenerated.contains(klassValue)) {
                                typesGenerated.add(klassValue);
                                generateFactory(klassValue, annotationLogger, context, sourceWriter);
                            }
                        }
                    }
                }
            }
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.BeanProperty.java

License:Open Source License

public void writeSingleConstructor(SourceWriter source, String propertyType, BeanMethod getter,
        BeanMethod setter, boolean addComma) {
    final String beanClassName = beanClass.getSimpleBeanClassName();

    source.println("new " + propertyType + "<" + beanClassName + "> (\"" + getName() + "\",");
    source.indent();

    if (getter != null && setter != null) {
        getter.writeNew(source, beanClassName, getMethodIndex(getter), getMethodIndex(setter), false);
    } else if (getter != null) {
        getter.writeNew(source, beanClassName, getMethodIndex(getter), null, false);
    } else if (setter != null) {
        setter.writeNew(source, beanClassName, null, getMethodIndex(setter), false);
    }/*from w w  w. j  a v  a 2  s . com*/

    source.outdent();
    source.println(")" + (addComma ? "," : ""));
}

From source file:com.smartgwt.rebind.BeanProperty.java

License:Open Source License

public void writeMultipleConstructor(SourceWriter source, boolean addComma) {
    final String beanClassName = beanClass.getSimpleBeanClassName();

    source.println("new BeanPropertyMultiple<" + beanClassName + "> (\"" + getName() + "\",");
    source.indent();

    if (getters.size() == 0) {
        source.println("null, // no getters");
    } else {//from  w w w  .jav  a 2  s . c om
        source.println("new BeanMethod[] {");
        source.indent();

        Iterator<BeanMethod> iterator = getters.iterator();
        while (iterator.hasNext()) {
            BeanMethod getter = iterator.next();
            getter.writeNew(source, beanClassName, getMethodIndex(getter), null, iterator.hasNext());
        }

        source.outdent();
        source.println("},");
    }

    if (setters.size() == 0) {
        source.println("null // no setters");
    } else {
        source.println("new BeanMethod[] {");
        source.indent();

        Iterator<BeanMethod> iterator = setters.iterator();
        while (iterator.hasNext()) {
            BeanMethod setter = iterator.next();
            setter.writeNew(source, beanClassName, null, getMethodIndex(setter), iterator.hasNext());
        }

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

    source.outdent();
    source.println(")" + (addComma ? "," : ""));
}

From source file:com.smartgwt.rebind.BeanValueType.java

License:Open Source License

public String generateFactory(TreeLogger logger, GeneratorContext context) {
    final String packageName = getFactoryPackage();
    final String factoryName = getSimpleFactoryName();
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, factoryName);

    composer.addImport(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName());
    composer.addImport(com.google.gwt.core.client.JavaScriptObject.class.getCanonicalName());

    // Import our valueType, but without the [] designation
    composer.addImport(getQualifiedTypeName().replace("[]", ""));

    composer.addImport(beanValueType.getQualifiedSourceName());
    composer.setSuperclass(beanValueType.getSimpleSourceName() + "<" + getSimpleGenericName() + ">");

    PrintWriter printWriter = context.tryCreate(logger, packageName, factoryName);
    if (printWriter != null) {
        SourceWriter source = composer.createSourceWriter(context, printWriter);

        source.println("// This class lovingly generated by com.smartgwt.rebind.BeanValueType\n");
        source.println("public static void registerValueType () {");

        source.indent();
        source.println("// We check first to see if it's already registered, to avoid\n"
                + "// constructing the singleton over and over again. This will\n"
                + "// be called multiple times as various BeanFactories initialize\n" + "// themselves.");
        source.println("if (BeanValueType.getBeanValueType(" + getSimpleValueTypeLiteral() + ") == null) {");

        source.indent();//w ww.j a v a  2  s  .c om
        source.println("BeanValueType.registerBeanValueType(new " + getSimpleFactoryName() + "());");

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

        source.outdent();
        source.println("}\n");

        source.println("@Override public Class<" + getSimpleTypeName() + "> getValueType () {");
        source.indent();
        source.println("return " + getSimpleTypeName() + ".class;");
        source.outdent();
        source.println("}\n");

        source.println("@Override public boolean isAssignableFrom (Object value) {");
        source.indent();
        source.println("return value == null || value instanceof " + getSimpleTypeName() + ";");
        source.outdent();
        source.println("}");

        if (componentType != null) {
            source.println("\nprivate " + getSimpleTypeName() + " emptyArray = new "
                    + componentType.getSimpleSourceName() + "[0];");
            source.println("\n@Override public " + getSimpleTypeName() + " emptyArray () {");
            source.indent();
            source.println("return emptyArray;");
            source.outdent();
            source.println("}");
        }

        if (scClassName != null) {
            source.println("\n@Override public String getScClassName () {");
            source.indent();
            source.println("return \"" + scClassName + "\";");
            source.outdent();
            source.println("}");
        }

        // Try to write a newInstance function that takes a JavaScriptObject
        if (isAbstract) {
            // If the type is abstract, our only hope is if it has a static getOrCreateRef method
            if (hasGetOrCreateRef) {
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return " + getSimpleTypeName() + ".getOrCreateRef(jsObject);");
                source.outdent();
                source.println("}");
            }
        } else {
            if (jsObjConstructor != null) {
                // If it has the right kind of constructor, then use that
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return new " + getSimpleTypeName() + "(jsObject);");
                source.outdent();
                source.println("}");
            } else if (hasSetJavaScriptObject) {
                // Custom subclasses likely won't have the constructor, but may have a a setJavaScriptObject method
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println(getSimpleTypeName() + " value = new " + getSimpleTypeName() + "();");
                source.println("value.setJavaScriptObject(jsObject);");
                source.println("return value;");
                source.outdent();
                source.println("}");
            } else if (hasGetOrCreateRef) {
                // And may as well fall back to getOrCreateRef if it exists
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return " + getSimpleTypeName() + ".getOrCreateRef(jsObject);");
                source.outdent();
                source.println("}");
            }
        }

        source.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.BeanValueTypeFactoryGenerator.java

License:Open Source License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType metaFactoryType = typeOracle.findType(typeName);

    final String genPackageName = metaFactoryType.getPackage().getName();
    final String genClassName = metaFactoryType.getSimpleSourceName() + "Impl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(typeName);
    composer.addImport(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName());
    composer.addImport("com.smartgwt.client.bean.types.*");

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + BeanValueTypeFactoryGenerator.class.getCanonicalName() + "\n");

        StringBuilder functions = new StringBuilder();

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        JClassType beanValueTypeClass = typeOracle
                .findType(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName()).isClass();

        // Iterate over the methods defined on the interface
        for (JMethod method : metaFactoryType.getMethods()) {
            if (method.getParameters().length != 0) {
                logger.log(Type.ERROR, typeName + "::" + method.getName() + " should have no parameters.");
                throw new UnableToCompleteException();
            }//from  w ww .  ja v a2s . c o m

            JParameterizedType returnType = method.getReturnType().isParameterized();
            if (returnType == null) {
                logger.log(Type.ERROR,
                        typeName + "::" + method.getName() + " has a non-parameterized return type.");
                throw new UnableToCompleteException();
            }

            if (returnType.getBaseType() != beanValueTypeClass) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " does not have BeanValueType<> as its return type.");
                throw new UnableToCompleteException();
            }

            JClassType[] typeArgs = returnType.getTypeArgs();
            if (typeArgs.length != 1) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " should have a return type with one parameterized type.");
                throw new UnableToCompleteException();
            }

            BeanValueType beanValueType = new BeanValueType(typeArgs[0], typeOracle);

            // Write the function to register the value type. Note that a side-effect
            // is that the factory for the value type is actually generated!
            beanValueType.writeRegisterValueType(sourceWriter, logger, context);

            // And we'll need to generate the function!
            functions.append("\n\n@Override public BeanValueType<" + beanValueType.getQualifiedTypeName() + "> "
                    + method.getName() + "() {\n  " + "return (BeanValueType<"
                    + beanValueType.getQualifiedTypeName() + ">) BeanValueType.getBeanValueType("
                    + beanValueType.getQualifiedValueTypeLiteral() + ");\n}");
        }

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

        sourceWriter.println(functions.toString());
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.CanvasMetaBeanFactoryGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType canvasType = oracle.findType(Canvas.class.getCanonicalName());

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "CanvasMetaBeanFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.CanvasMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + CanvasMetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        for (JClassType classType : oracle.getTypes()) {
            if (classType.isAssignableTo(canvasType) && isEligibleForGeneration(classType)) {
                BeanClass beanClass = new BeanClass(classType);
                beanClass.generateFactory(logger, context);

                // We have to instantiate the factory to register it in the BeanFactory static API
                sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");
            }// ww w . j a  va  2  s.c  o m
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.FormItemMetaBeanFactoryGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    JClassType formItemType = oracle.findType(FormItem.class.getCanonicalName());

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "FormItemMetaBeanFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.FormItemMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + FormItemMetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        for (JClassType classType : oracle.getTypes()) {
            if (classType.isAssignableTo(formItemType) && isEligibleForGeneration(classType)) {
                BeanClass beanClass = new BeanClass(classType);
                beanClass.generateFactory(logger, context);

                // We have to instantiate the factory to register it in the BeanFactory static API
                sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");
            }/*from w  ww.ja va 2s  .c om*/
        }

        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.MetaBeanFactoryGenerator.java

License:Open Source License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType metaFactoryType = typeOracle.findType(typeName);

    final String genPackageName = getFactoryPackage(metaFactoryType);
    final String genClassName = getSimpleFactoryName(metaFactoryType);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(typeName);
    composer.addImport(com.smartgwt.client.bean.BeanFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + MetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        StringBuilder functions = new StringBuilder();

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        JClassType beanFactoryType = typeOracle.findType(BeanFactory.class.getCanonicalName()).isClass();
        JClassType baseWidgetType = typeOracle.findType(BaseWidget.class.getCanonicalName()).isClass();
        JClassType dataClassType = typeOracle.findType(DataClass.class.getCanonicalName()).isClass();

        // Iterate over the methods defined on the interface
        for (JMethod method : metaFactoryType.getMethods()) {
            if (method.getParameters().length != 0) {
                logger.log(Type.ERROR, typeName + "::" + method.getName() + " should have no parameters.");
                throw new UnableToCompleteException();
            }//ww w .  j  av  a2 s .  c o m

            JParameterizedType returnType = method.getReturnType().isParameterized();
            if (returnType == null) {
                logger.log(Type.ERROR,
                        typeName + "::" + method.getName() + " has a non-parameterized return type.");
                throw new UnableToCompleteException();
            }

            if (returnType.getBaseType() != beanFactoryType) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " does not have BeanFactory<> as its return type.");
                throw new UnableToCompleteException();
            }

            JClassType[] typeArgs = returnType.getTypeArgs();
            if (typeArgs.length != 1) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " should have a return type with one parameterized type.");
                throw new UnableToCompleteException();
            }

            JClassType beanClassType = typeArgs[0];
            if (!baseWidgetType.isAssignableFrom(beanClassType)
                    && !dataClassType.isAssignableFrom(beanClassType)) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + ": for now, factories can only be created for Canvas or DataClass and subclasses.");
                throw new UnableToCompleteException();
            }

            BeanClass beanClass = new BeanClass(beanClassType);
            beanClass.generateFactory(logger, context);

            // We have to instantiate the factory to register it in the BeanFactory static API
            sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");

            // And we'll need to generate the function!
            functions.append("\n\n@Override public BeanFactory<" + beanClassType.getQualifiedSourceName() + "> "
                    + method.getName() + "() {\n  " + "return (BeanFactory<"
                    + beanClassType.getQualifiedSourceName() + ">) BeanFactory.getFactory("
                    + beanClassType.getQualifiedSourceName() + ".class);\n}");
        }

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

        sourceWriter.println(functions.toString());
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}