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

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

Introduction

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

Prototype

void indentln(String s);

Source Link

Usage

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

private void writeAutoBean(AutoBeanType type) throws UnableToCompleteException {
    PrintWriter pw = context.tryCreate(logger, type.getPackageNome(), type.getSimpleSourceName());
    if (pw == null) {
        // Previously-created
        return;/* w ww.  j a v a  2s .  c  om*/
    }

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(type.getPackageNome(),
            type.getSimpleSourceName());
    factory.setSuperclass(AbstractAutoBean.class.getCanonicalName() + "<"
            + type.getPeerType().getQualifiedSourceName() + ">");
    SourceWriter sw = factory.createSourceWriter(context, pw);

    writeShim(sw, type);

    // Instance initializer code to set the shim's association
    sw.println("{ %s.set(shim, %s.class.getName(), this); }", WeakMapping.class.getCanonicalName(),
            AutoBean.class.getCanonicalName());

    // Only simple wrappers have a default constructor
    if (type.isSimpleBean()) {
        // public FooIntfAutoBean(AutoBeanFactory factory) {}
        sw.println("public %s(%s factory) {super(factory);}", type.getSimpleSourceName(),
                AutoBeanFactory.class.getCanonicalName());
    }

    // Wrapping constructor
    // public FooIntfAutoBean(AutoBeanFactory factory, FooIntfo wrapped) {
    sw.println("public %s(%s factory, %s wrapped) {", type.getSimpleSourceName(),
            AutoBeanFactory.class.getCanonicalName(), type.getPeerType().getQualifiedSourceName());
    sw.indentln("super(wrapped, factory);");
    sw.println("}");

    // public FooIntf as() {return shim;}
    sw.println("public %s as() {return shim;}", type.getPeerType().getQualifiedSourceName());

    // public Class<Intf> getType() {return Intf.class;}
    sw.println("public Class<%1$s> getType() {return %1$s.class;}",
            ModelUtils.ensureBaseType(type.getPeerType()).getQualifiedSourceName());

    if (type.isSimpleBean()) {
        writeCreateSimpleBean(sw, type);
    }
    writeTraversal(sw, type);
    sw.commit(logger);
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

/**
 * Create the shim instance of the AutoBean's peer type that lets us hijack
 * the method calls. Using a shim type, as opposed to making the AutoBean
 * implement the peer type directly, means that there can't be any conflicts
 * between methods in the peer type and methods declared in the AutoBean
 * implementation.//from  w  ww.j  av a2  s  .  co  m
 */
private void writeShim(SourceWriter sw, AutoBeanType type) throws UnableToCompleteException {
    // private final FooImpl shim = new FooImpl() {
    sw.println("private final %1$s shim = new %1$s() {", type.getPeerType().getQualifiedSourceName());
    sw.indent();
    for (AutoBeanMethod method : type.getMethods()) {
        JMethod jmethod = method.getMethod();
        String methodName = jmethod.getName();
        JParameter[] parameters = jmethod.getParameters();
        if (isObjectMethodImplementedByShim(jmethod)) {
            // Skip any methods declared on Object, since we have special handling
            continue;
        }

        // foo, bar, baz
        StringBuilder arguments = new StringBuilder();
        {
            for (JParameter param : parameters) {
                arguments.append(",").append(param.getName());
            }
            if (arguments.length() > 0) {
                arguments = arguments.deleteCharAt(0);
            }
        }

        sw.println("public %s {", getBaseMethodDeclaration(jmethod));
        sw.indent();

        switch (method.getAction()) {
        case GET:
            /*
             * The getter call will ensure that any non-value return type is
             * definitely wrapped by an AutoBean instance.
             */
            sw.println("%s toReturn = %s.this.getWrapped().%s();",
                    ModelUtils.getQualifiedBaseSourceName(jmethod.getReturnType()), type.getSimpleSourceName(),
                    methodName);

            // Non-value types might need to be wrapped
            writeReturnWrapper(sw, type, method);
            sw.println("return toReturn;");
            break;
        case SET:
        case SET_BUILDER:
            // getWrapped().setFoo(foo);
            sw.println("%s.this.getWrapped().%s(%s);", type.getSimpleSourceName(), methodName,
                    parameters[0].getName());
            // FooAutoBean.this.set("setFoo", foo);
            sw.println("%s.this.set(\"%s\", %s);", type.getSimpleSourceName(), methodName,
                    parameters[0].getName());
            if (JBeanMethod.SET_BUILDER.equals(method.getAction())) {
                sw.println("return this;");
            }
            break;
        case CALL:
            // XXX How should freezing and calls work together?
            // sw.println("checkFrozen();");
            if (JPrimitiveType.VOID.equals(jmethod.getReturnType())) {
                // getWrapped().doFoo(params);
                sw.println("%s.this.getWrapped().%s(%s);", type.getSimpleSourceName(), methodName, arguments);
                // call("doFoo", null, params);
                sw.println("%s.this.call(\"%s\", null%s %s);", type.getSimpleSourceName(), methodName,
                        arguments.length() > 0 ? "," : "", arguments);
            } else {
                // Type toReturn = getWrapped().doFoo(params);
                sw.println("%s toReturn = %s.this.getWrapped().%s(%s);",
                        ModelUtils.ensureBaseType(jmethod.getReturnType()).getQualifiedSourceName(),
                        type.getSimpleSourceName(), methodName, arguments);
                // Non-value types might need to be wrapped
                writeReturnWrapper(sw, type, method);
                // call("doFoo", toReturn, params);
                sw.println("%s.this.call(\"%s\", toReturn%s %s);", type.getSimpleSourceName(), methodName,
                        arguments.length() > 0 ? "," : "", arguments);
                sw.println("return toReturn;");
            }
            break;
        default:
            throw new RuntimeException();
        }
        sw.outdent();
        sw.println("}");
    }

    // Delegate equals(), hashCode(), and toString() to wrapped object
    sw.println("@Override public boolean equals(Object o) {");
    sw.indentln("return this == o || getWrapped().equals(o);");
    sw.println("}");
    sw.println("@Override public int hashCode() {");
    sw.indentln("return getWrapped().hashCode();");
    sw.println("}");
    sw.println("@Override public String toString() {");
    sw.indentln("return getWrapped().toString();");
    sw.println("}");

    // End of shim field declaration and assignment
    sw.outdent();
    sw.println("};");
}

From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java

License:Apache License

/**
 * Generate traversal logic./*  ww  w . j a va  2s .c o  m*/
 */
private void writeTraversal(SourceWriter sw, AutoBeanType type) {
    List<AutoBeanMethod> referencedSetters = new ArrayList<AutoBeanMethod>();
    sw.println("@Override protected void traverseProperties(%s visitor, %s ctx) {",
            AutoBeanVisitor.class.getCanonicalName(), OneShotContext.class.getCanonicalName());
    sw.indent();
    sw.println("%s bean;", AbstractAutoBean.class.getCanonicalName());
    sw.println("Object value;");
    sw.println("%s propertyContext;", ClientPropertyContext.class.getCanonicalName());
    // Local variable ref cleans up emitted js
    sw.println("%1$s as = as();", type.getPeerType().getQualifiedSourceName());

    for (AutoBeanMethod method : type.getMethods()) {
        if (!method.getAction().equals(JBeanMethod.GET)) {
            continue;
        }

        AutoBeanMethod setter = null;
        // If it's not a simple bean type, try to find a real setter method
        if (!type.isSimpleBean()) {
            for (AutoBeanMethod maybeSetter : type.getMethods()) {
                boolean isASetter = maybeSetter.getAction().equals(JBeanMethod.SET)
                        || maybeSetter.getAction().equals(JBeanMethod.SET_BUILDER);
                if (isASetter && maybeSetter.getPropertyName().equals(method.getPropertyName())) {
                    setter = maybeSetter;
                    break;
                }
            }
        }

        // The type of property influences the visitation
        String valueExpression = String.format("bean = (%1$s) %2$s.getAutoBean(as.%3$s());",
                AbstractAutoBean.class.getCanonicalName(), AutoBeanUtils.class.getCanonicalName(),
                method.getMethod().getName());
        String visitMethod;
        String visitVariable = "bean";
        if (method.isCollection()) {
            visitMethod = "Collection";
        } else if (method.isMap()) {
            visitMethod = "Map";
        } else if (method.isValueType()) {
            valueExpression = String.format("value = as.%s();", method.getMethod().getName());
            visitMethod = "Value";
            visitVariable = "value";
        } else {
            visitMethod = "Reference";
        }
        sw.println(valueExpression);

        // Map<List<Foo>, Bar> --> Map, List, Foo, Bar
        List<JType> typeList = new ArrayList<JType>();
        createTypeList(typeList, method.getMethod().getReturnType());
        assert typeList.size() > 0;

        /*
         * Make the PropertyContext that lets us call the setter. We allow
         * multiple methods to be bound to the same property (e.g. to allow JSON
         * payloads to be interpreted as different types). The leading underscore
         * allows purely numeric property names, which are valid JSON map keys.
         */
        // propertyContext = new CPContext(.....);
        sw.println("propertyContext = new %s(", ClientPropertyContext.class.getCanonicalName());
        sw.indent();
        // The instance on which the context is nominally operating
        sw.println("as,");
        // Produce a JSNI reference to a setter function to call
        {
            if (setter != null) {
                // Call a method that returns a JSNI reference to the method to call
                // setFooMethodReference(),
                sw.println("%sMethodReference(as),", setter.getMethod().getName());
                referencedSetters.add(setter);
            } else {
                // Create a function that will update the values map
                // CPContext.beanSetter(FooBeanImpl.this, "foo");
                sw.println("%s.beanSetter(%s.this, \"%s\"),",
                        ClientPropertyContext.Setter.class.getCanonicalName(), type.getSimpleSourceName(),
                        method.getPropertyName());
            }
        }
        if (typeList.size() == 1) {
            sw.println("%s.class", ModelUtils.ensureBaseType(typeList.get(0)).getQualifiedSourceName());
        } else {
            // Produce the array of parameter types
            sw.print("new Class<?>[] {");
            boolean first = true;
            for (JType lit : typeList) {
                if (first) {
                    first = false;
                } else {
                    sw.print(", ");
                }
                sw.print("%s.class", ModelUtils.ensureBaseType(lit).getQualifiedSourceName());
            }
            sw.println("},");

            // Produce the array of parameter counts
            sw.print("new int[] {");
            first = true;
            for (JType lit : typeList) {
                if (first) {
                    first = false;
                } else {
                    sw.print(", ");
                }
                JParameterizedType hasParam = lit.isParameterized();
                if (hasParam == null) {
                    sw.print("0");
                } else {
                    sw.print(String.valueOf(hasParam.getTypeArgs().length));
                }
            }
            sw.println("}");
        }
        sw.outdent();
        sw.println(");");

        // if (visitor.visitReferenceProperty("foo", value, ctx))
        sw.println("if (visitor.visit%sProperty(\"%s\", %s, propertyContext)) {", visitMethod,
                method.getPropertyName(), visitVariable);
        if (!method.isValueType()) {
            // Cycle-detection in AbstractAutoBean.traverse
            sw.indentln("if (bean != null) { bean.traverse(visitor, ctx); }");
        }
        sw.println("}");
        // visitor.endVisitorReferenceProperty("foo", value, ctx);
        sw.println("visitor.endVisit%sProperty(\"%s\", %s, propertyContext);", visitMethod,
                method.getPropertyName(), visitVariable);
    }
    sw.outdent();
    sw.println("}");

    for (AutoBeanMethod method : referencedSetters) {
        JMethod jmethod = method.getMethod();
        assert jmethod.getParameters().length == 1;

        /*-
         * Setter setFooMethodReference(Object instance) {
         *   return instance.@com.example.Blah::setFoo(Lcom/example/Foo;);
         * }
         */
        sw.println("public static native %s %sMethodReference(Object instance) /*-{",
                ClientPropertyContext.Setter.class.getCanonicalName(), jmethod.getName());
        sw.indentln("return instance.@%s::%s(%s);", jmethod.getEnclosingType().getQualifiedSourceName(),
                jmethod.getName(), jmethod.getParameters()[0].getType().getJNISignature());
        sw.println("}-*/;");
    }
}

From source file:com.googlecode.mgwt.ui.server.util.MGWTCssResourceGenerator.java

License:Apache License

@Override
protected void writeEnsureInjected(SourceWriter sw) {
    if (!injectAtStart) {
        super.writeEnsureInjected(sw);
    } else {/*from www .j a  v a2  s  .  co  m*/
        sw.println("private boolean injected;");
        sw.println("public boolean ensureInjected() {");
        sw.indent();
        sw.println("if (!injected) {");
        sw.indentln("injected = true;");
        sw.indentln(StyleInjector.class.getName() + ".injectAtStart(getText());");
        sw.indentln("return true;");
        sw.println("}");
        sw.println("return false;");
        sw.outdent();
        sw.println("}");
    }
}

From source file:com.googlecode.mgwt.useragent.rebind.UserAgentPropertyGenerator.java

License:Apache License

/**
 * Writes out the JavaScript function body for determining the value of the
 * <code>user.agent</code> selection property. This method is used to create
 * the selection script and by {@link UserAgentGenerator} to assert at runtime
 * that the correct user agent permutation is executing.
 *//*from  www.j a  va 2s  . c  o  m*/
static void writeUserAgentPropertyJavaScript(SourceWriter body, SortedSet<String> possibleValues,
        String fallback) {

    // write preamble
    body.println("var ua = navigator.userAgent.toLowerCase();");
    body.println("var docMode = $doc.documentMode;");

    for (UserAgent userAgent : UserAgent.values()) {
        // write only selected user agents
        if (possibleValues.contains(userAgent.name())) {
            body.println("if ((function() { ");
            body.indentln(userAgent.predicateBlock);
            body.println("})()) return '%s';", userAgent.name());
        }
    }

    // default return
    if (fallback == null) {
        fallback = "unknown";
    }
    body.println("return '" + fallback + "';");
}

From source file:com.kk_electronic.gwt.rebind.FlexInjectorGenerator.java

License:Open Source License

private void writeFragment(SourceWriter sw, JClassType j) {
    sw.println("fragmentMap.put(" + j.getQualifiedSourceName() + ".class, new FlexInjector() {");
    sw.indent();//from w  ww .ja va2s.  com
    sw.println("@Override");
    sw.println("public <E> void create(Class<? extends E> type, AsyncCallback<E> callback) {");
    sw.indentln(
            "callback.onSuccess((E)injector.create$" + j.getQualifiedSourceName().replace('.', '$') + "());");
    sw.println("}");
    sw.outdent();
    sw.println("});");
}

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 ww w.j av  a2s  .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   ww w. ja va 2 s  .com*/

    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.sencha.gxt.data.rebind.ValueProviderCreator.java

License:sencha.com license

protected void appendGetterBody(SourceWriter sw, String objectName) throws UnableToCompleteException {
    String getter = getGetterExpression(objectName);
    if (getter == null) {
        if (readability == RequiredReadability.NEITHER || readability == RequiredReadability.SET) {
            // getter is not required, but log it if someone tries to call it
            getLogger().log(Type.DEBUG,
                    "Getter could not be found (and apparently not needed), writting a log message to indicate that this is probably an error.");
            sw.indentln("com.google.gwt.core.client.GWT.log(\"Getter was called on "
                    + supertypeToImplement.getName() + ", but no getter exists.\", new RuntimeException());");
            sw.indentln("return null;");
        } else {/*  w w  w  .  j  av a  2 s.c  o  m*/
            getLogger().log(Type.ERROR, "No getter can be found, unable to proceed");
            throw new UnableToCompleteException();
        }
    } else {
        sw.indentln("return %1$s;", getter);
    }
}

From source file:com.sencha.gxt.data.rebind.ValueProviderCreator.java

License:sencha.com license

protected void appendSetterBody(SourceWriter sw, String objectName, String valueName)
        throws UnableToCompleteException {
    String setter = getSetterExpression(objectName, valueName);
    if (setter == null) {
        if (readability == RequiredReadability.NEITHER || readability == RequiredReadability.GET) {
            // setter is not required, but log it if someone tries to call it
            getLogger().log(Type.DEBUG,
                    "Setter could not be found (and apparently not needed), writing a log message to indicate that this is probably an error.");
            sw.indentln("com.google.gwt.core.client.GWT.log(\"Setter was called on "
                    + supertypeToImplement.getName() + ", but no setter exists.\", new RuntimeException());");
        } else {//from  www  .  j a  va2 s  .com
            getLogger().log(Type.ERROR, "No setter can be found, unable to proceed");
            throw new UnableToCompleteException();
        }
    } else {
        sw.indentln("%1$s;", setter);
    }
}