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

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

Introduction

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

Prototype

void outdent();

Source Link

Usage

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

License:Open Source License

private void writeModelBridgeImpl(SourceWriter sw) {
    sw.println("private static final class %sModelBridge extends ModelBridge<%s> {", modelClassName,
            modelClassName);/*from   www  . jav a  2s.  c  o  m*/
    sw.indent();

    sw.println("public %sModelBridge(%s jsoBuilder) {", modelClassName, BridgeCapabilities.JSO_BUILDER_CLASS);
    sw.indentln("super(jsoBuilder);");
    sw.println("}");
    sw.println();

    sw.println("@Override");
    sw.println("protected JavaScriptObject bridgeInternal(%s in, %s jsoBuilder) {", modelClassName,
            BridgeCapabilities.JSO_BUILDER_CLASS);
    sw.indent();

    sw.println("JavaScriptObject target = JavaScriptObject.createObject();");
    sw.println("jsoBuilder.setTarget(target);");

    for (MappableMethod modelMethod : inspector.getMappableModelMethods()) {
        BridgeMethod bridgeMethod = bridgeCapabilities.getBridgeMethod(modelMethod.getReturnType());
        sw.println("jsoBuilder.%s(\"%s\", in.%s());", bridgeMethod.getName(), modelMethod.getAttributeName(),
                modelMethod.getName());
    }

    MappableMethod modelIdGeneratorMethod = inspector.getModelIdGeneratorMethod();
    if (modelIdGeneratorMethod != null) {
        BridgeMethod bridgeMethod = bridgeCapabilities.getBridgeMethod(modelIdGeneratorMethod.getReturnType());
        sw.println();
        sw.println("jsoBuilder.%s(\"%s\", in.%s());", bridgeMethod.getName(), "id",
                modelIdGeneratorMethod.getName());
    }

    if (inspector.modelUsesCustomAttributes()) {
        sw.println("((%s) in).setCustomRhizosphereAttributes(jsoBuilder);",
                ModelInspector.CUSTOM_ATTRIBUTES_INTERFACE);
    }

    sw.println("return target;");

    // Close bridgeInternal() method
    sw.outdent();
    sw.println("}");

    // Close class definition
    sw.outdent();
    sw.println("}");
}

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

License:Open Source License

private void writeMetaModelFactoryImpl(SourceWriter sw) {
    sw.println("private static final class %sMetaModelFactory extends MetaModelFactory {", modelClassName);
    sw.indent();//from   w ww  .jav  a  2 s  . co m

    sw.println("public %sMetaModelFactory() {", modelClassName);
    sw.indentln("super();");
    sw.println("}");
    sw.println();

    sw.println("public %sMetaModelFactory(%s attrBuilder) {", modelClassName,
            BridgeCapabilities.METAMODEL_ATTRIBUTE_BUILDER_CLASS);
    sw.indentln("super(attrBuilder);");
    sw.println("}");
    sw.println();

    sw.println("@Override");
    sw.println("protected void fillMetaModelAttributes("
            + "RhizosphereMetaModel metaModel, AttributeBuilder attrBuilder) {");
    sw.indent();

    sw.println("Attribute attr;");
    sw.println("AttributeDescriptor descriptor;");
    sw.println("RhizosphereKind kind;");
    for (MappableMethod modelMethod : inspector.getMappableModelMethods()) {
        if (!modelMethod.contributesToMetaModel()) {
            continue;
        }
        String labelParameter = modelMethod.getAttributeLabel() != null
                ? "\"" + modelMethod.getAttributeLabel() + "\""
                : "null";
        sw.println("attr = metaModel.newAttribute(\"%s\");", modelMethod.getAttributeName());
        sw.println("descriptor = new %s();", modelMethod.getAttributeDescriptorClassName());
        sw.println("kind = RhizosphereKind.valueOf(RhizosphereKind.class, \"%s\");",
                bridgeCapabilities.getBridgeMethod(modelMethod.getReturnType()).getRhizosphereKind().name());
        sw.println("attrBuilder.fillAttribute(attr, descriptor, \"%s\", %s, kind);",
                modelMethod.getAttributeName(), labelParameter);
        sw.println();
    }

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

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

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

License:Apache License

private void writeMethods(SourceWriter sw) throws UnableToCompleteException {
    final String keyParamName = "key";
    final String varKeyValueName = "keyValue";
    for (StorageKeyProviderMethod method : model.getMethods()) {
        final String returnName = method.getReturnType().getParameterizedQualifiedSourceName();
        final String parameters = method.isDynamicKey()
                ? (method.getKeyValueType().getQualifiedSourceName() + " " + keyParamName)
                : "";
        final String keyPrefix = method.getKeyPrefix();
        final String keySuffix = method.getKeySuffix();

        sw.println();//from ww w  .  j ava 2  s  .  c om
        sw.println("public %s %s(%s) {", returnName, method.getName(), parameters);
        sw.indent();
        String keyClazz = method.getKeyClazz().getQualifiedSourceName();
        if (method.isDynamicKey()) {
            String keyPrefixStr = "";
            String keySuffixStr = "";
            if (keyPrefix != null && !keyPrefix.trim().isEmpty()) {
                keyPrefixStr = "\"" + keyPrefix + "\" + ";
            }
            if (keySuffix != null && !keySuffix.trim().isEmpty()) {
                keySuffixStr = " + \"" + keySuffix + "\"";
            }
            sw.println("String %s = %sString.valueOf(key)%s;", varKeyValueName, keyPrefixStr, keySuffixStr);
            sw.println("return createIfAbsent(%s, %s.class);", varKeyValueName, keyClazz);
        } else {
            String staticKeyValue = method.getStaticKeyValue();
            if (keyPrefix != null && !keyPrefix.trim().isEmpty()) {
                staticKeyValue = keyPrefix + staticKeyValue;
            }
            if (keySuffix != null && !keySuffix.trim().isEmpty()) {
                staticKeyValue += keySuffix;
            }
            sw.println("return createIfAbsent(\"%s\", %s.class);", staticKeyValue, keyClazz);
        }
        sw.outdent();
        sw.println("}");
    }
}

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  .ja  v  a  2  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 va  2 s  .co  m*/
    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.useragent.UserAgentPropertyGenerator.java

License:sencha.com license

@Override
public String generate(TreeLogger logger, SortedSet<String> possibleValues, String fallback,
        SortedSet<ConfigurationProperty> configProperties) throws UnableToCompleteException {

    SourceWriter sw = new StringSourceWriter();
    sw.println("{");

    sw.println("var ua = navigator.userAgent.toLowerCase();");

    // Microsoft Edge
    uaContains(sw, "edge/", "edge");

    uaContains(sw, "chrome", "chrome");

    sw.println("if (ua.indexOf('trident') != -1 || ua.indexOf('msie') != -1) {");
    sw.indent();/*from  www. j a va 2  s .c o  m*/

    // TODO ChromeFrame?
    docModeGreaterThan(sw, 11, "ie11");
    docModeGreaterThan(sw, 10, "ie10");
    docModeGreaterThan(sw, 9, "ie9");
    docModeGreaterThan(sw, 8, "ie8");

    // last assume newest
    sw.println("return 'ie10';");
    sw.outdent();
    sw.println("}");

    sw.println("if (ua.indexOf('safari') != -1) {");
    sw.indent();
    uaContains(sw, "version/3", "safari3");
    uaContains(sw, "version/4", "safari4");
    // else assume newest
    // simpleStatement(sw, "version/5", "safari5");
    sw.println("return 'safari5';");
    sw.outdent();
    sw.println("}");

    sw.println("if (ua.indexOf('gecko') != -1) {");
    sw.indent();
    uaContains(sw, "rv:1.8", "gecko1_8");
    // Don't check for rev 1.9, check instead for the newest version, and treat
    // all
    // gecko browsers that don't match a rule as the newest version
    // simpleStatement(sw, "rv:1.9", "gecko1_9");
    sw.println("return 'gecko1_9';");
    sw.outdent();
    sw.println("}");

    uaContains(sw, "adobeair", "air");

    sw.println("return null;}");
    return sw.toString();
}

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();
    }//from   w ww .ja  va  2  s  .  com
    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  .  j  a  v a2s .  c  o m
 * 
 * @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   www  .  jav  a2 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();/*www .j a va  2s .  c o m*/

    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);
    }

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