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

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

Introduction

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

Prototype

void println(String s, Object... args);

Source Link

Document

Emit a printf-style string.

Usage

From source file:com.colinalworth.celltable.columns.rebind.ColumnsGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    //this.logger = logger;
    this.context = context;

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

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

    ColumnSetModel columnSet = new ColumnSetModel(toGenerate, context, logger, names);

    //public class X implements X {
    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.addImplementedInterface(typeName);

    factory.addImport(Name.getSourceNameForClass(GWT.class));
    factory.addImport(Name.getSourceNameForClass(CellTable.class));
    factory.addImport(Name.getSourceNameForClass(HasDataFlushableEditor.class));
    factory.addImport(Name.getSourceNameForClass(Column.class));
    factory.addImport(Name.getSourceNameForClass(HasHorizontalAlignment.class));
    factory.addImport(Name.getSourceNameForClass(HasVerticalAlignment.class));
    factory.addImport(Name.getSourceNameForClass(FieldUpdater.class));
    factory.addImport(columnSet.getBeanName());

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

    //wire up the factory, if any
    if (columnSet.hasFactory()) {
        names.add("factory");
        sw.println("private %1$s factory;", columnSet.getFactoryClassName());
        sw.println("public void setFactory(%1$s factory) {", columnSet.getFactoryClassName());
        sw.indent();
        sw.println(
                "assert factory != null && this.factory == null : \"Factory cannot be reset, and factory cannot be set as null\";");
        sw.println("this.factory = factory;");
        sw.outdent();
        sw.println("}");
    }

    // generate column methods
    for (ColumnModel c : columnSet.getColumnModels()) {
        // make the field 
        // TODO: no sense in building multiple copies, right?
        sw.println("private %1$s %2$s;", c.getCellClassName(), c.getCellFieldName());

        sw.println("private Column<%1$s,%2$s> %3$s;", columnSet.getBeanName(), c.getCellDataTypeName(),
                c.getColumnFieldName());
        sw.println();

        // make the method: public MyCell myDataMember() {
        //sw.println("@Override");//jdk 5 doesnt like this
        sw.println("public %1$s %2$s() {", c.getCellClassName(), c.getMethodName());
        sw.indent();
        sw.println("if (%s == null) {", c.getCellFieldName());
        sw.indent();

        //create the cell
        sw.println("%1$s = %2$s;", c.getCellFieldName(), c.getCellCreateExpression());

        //create the column - probably should be done later in the case of using HasDataFlushableEditor
        sw.println("%1$s = new Column<%2$s,%3$s> (%4$s) {", c.getColumnFieldName(), columnSet.getBeanName(),
                c.getCellDataTypeName(), c.getCellFieldName());
        sw.indent();

        sw.println("@Override");
        sw.println("public %1$s getValue(%2$s bean) {", c.getCellDataTypeName(), columnSet.getBeanName());
        sw.indent();
        sw.println("return %1$s;", c.getGetterInModel("bean"));
        sw.outdent();
        sw.println("}");

        sw.outdent();// end anon Column class
        sw.println("};");

        // Refactor at least this part out, in anticipation of a proper link to the Editor framework
        // TODO this is done by replacement right now, fix that.
        if (c.isEditable()) {
            if (!c.hasCustomFieldUpdater()) {
                sw.println("%1$s.setFieldUpdater(new FieldUpdater<%2$s,%3$s>() {", c.getColumnFieldName(),
                        columnSet.getBeanName(), c.getCellDataTypeName());
                sw.indent();

                sw.println("public void update(int index, %1$s object, %2$s value) {", columnSet.getBeanName(),
                        c.getCellDataTypeName());
                sw.indent();
                sw.println("%1$s;", c.getSetterInModel("object", "value"));
                sw.outdent();
                sw.println("}");

                sw.outdent();// end anon FieldUpdater class
                sw.println("});");
            } else {
                sw.println("%1$s.setFieldUpdater(GWT.<%2$s>create(%2$s.class));", c.getColumnFieldName(),
                        c.getFieldUpdaterType().getQualifiedSourceName());
            }
        }
        sw.println("%1$s.setHorizontalAlignment(%2$s);", c.getColumnFieldName(), c.getHorizontalAlignment());
        sw.println("%1$s.setVerticalAlignment(%2$s);", c.getColumnFieldName(), c.getVerticalAlignment());

        if (supportsSortable()) {
            sw.println("%1$s.setSortable(%2$s);", c.getColumnFieldName(), c.isSortable());
        } else {
            if (c.isSortable()) {
                logger.log(Type.WARN,
                        "Your version of GWT does not appear to support Column.setSortable, compilation may fail.");
            }
        }
        //end column creation/setup

        sw.outdent();
        sw.println("}");// end column/cell creation
        sw.println("return %s;", c.getCellFieldName());
        sw.outdent();
        sw.println("}");
    }

    // generate configure methods

    // simple overload
    sw.println("public final void configure(CellTable<%1$s> table) {", columnSet.getBeanName());
    sw.indent();
    sw.println("configure(table, null);");
    sw.outdent();
    sw.println("}");

    // actual heavy-lifting one
    sw.println("public final void configure(CellTable<%1$s> table, HasDataFlushableEditor<%1$s> ed) {",
            columnSet.getBeanName());
    sw.indent();
    if (columnSet.hasFactory()) {
        sw.println(
                "assert factory != null : \"setFactory() must be called before configure() can be called.\";");
    }
    for (ColumnModel c : columnSet.getColumnModels()) {
        //wire up the cell and column
        sw.println("%1$s();", c.getMethodName());

        if (c.isEditable() && !c.hasCustomFieldUpdater()) {
            // if there is an editor, replace the FieldUpdater
            sw.println("if (ed != null) {");
            sw.indent();
            sw.println("final FieldUpdater<%1$s, %2$s> wrapped = %3$s.getFieldUpdater();",
                    columnSet.getBeanName(), c.getCellDataTypeName(), c.getColumnFieldName());
            sw.println("%1$s.setFieldUpdater(ed.new PendingFieldUpdateChange<%2$s>(){", c.getColumnFieldName(),
                    c.getCellDataTypeName());
            sw.indent();
            sw.println("public void commit(int index, %1$s object, %2$s value) {", columnSet.getBeanName(),
                    c.getCellDataTypeName());
            sw.indent();
            sw.println("wrapped.update(index, object, value);");
            sw.outdent();
            sw.println("}");
            sw.outdent();
            sw.println("});");
            sw.outdent();
            sw.println("}");
        }

        // attach the column
        sw.println("table.addColumn(%1$s, %2$s);", c.getColumnFieldName(), c.getHeaderValue());
    }
    sw.outdent();
    sw.println("}");

    sw.println("public String[] getPaths() {");
    sw.indent();
    sw.println("return %1$s;", columnSet.getPaths());
    sw.outdent();
    sw.println("}");

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.colinalworth.gwt.websockets.rebind.ServerBuilderGenerator.java

License:Apache License

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

    if (toGenerate == null) {
        logger.log(Type.ERROR, "Error generating " + typeName
                + ", either not an interface, or cannot be reached from client code.");
        throw new UnableToCompleteException();
    }/*  w w  w. j a v  a2 s . co  m*/
    JClassType serverBuilderType = oracle.findType(ServerBuilder.class.getName());
    JClassType serverImplType = ModelUtils.findParameterizationOf(serverBuilderType, toGenerate)[0];

    // Build an impl so we can call it ourselves
    ServerCreator creator = new ServerCreator(serverImplType);
    creator.create(logger, context);

    String packageName = toGenerate.getPackage().getName();
    String simpleName = toGenerate.getName().replace('.', '_') + "_Impl";

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

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleName);
    factory.setSuperclass(Name.getSourceNameForClass(ServerBuilderImpl.class) + "<"
            + serverImplType.getQualifiedSourceName() + ">");
    factory.addImplementedInterface(typeName);

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

    RemoteServiceRelativePath path = serverImplType.getAnnotation(RemoteServiceRelativePath.class);
    if (path != null) {
        sw.println("public %1$s() {", simpleName);
        sw.indentln("setPath(\"%1$s\");", path.value());
        sw.println("}");
    }

    sw.println();
    // start method
    sw.println("public %1$s start() {", serverImplType.getQualifiedSourceName());
    sw.indent();
    sw.println("String url = getUrl();");
    sw.println("if (url == null) {");
    sw.indentln("return new %1$s(getErrorHandler());", creator.getQualifiedSourceName());
    sw.println("} else {");
    sw.indentln("return new %1$s(getErrorHandler(), url);", creator.getQualifiedSourceName());
    sw.println("}");

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

    sw.commit(logger);

    return factory.getCreatedClassName();

}

From source file:com.colinalworth.gwt.websockets.rebind.ServerCreator.java

License:Apache License

/**
 * Writes out the method to use to invoke a server call. Mostly derived from RPC's way of building proxy methods
 *
 * @param logger/*  w  w w.  j  ava2  s .  c  o m*/
 * @param context
 * @param sw
 * @param m
 */
private void printServerMethodBody(TreeLogger logger, GeneratorContext context, SourceWriter sw, JMethod m) {
    sw.println("%1$s {", m.getReadableDeclaration(false, true, true, true, true));
    sw.indent();

    sw.print("__sendMessage(\"%1$s\"", m.getName());
    StringBuilder sb = new StringBuilder();
    String callback = "null";
    JParameter[] parameters = m.getParameters();
    for (int i = 0; i < parameters.length; i++) {
        JParameter param = parameters[i];
        if (i + 1 == parameters.length && param.getType().isInterface() != null
                && param.getType().isInterface().getQualifiedSourceName().equals(Callback.class.getName())) {
            callback = param.getName();
        } else {
            sb.append(",\n").append(param.getName());
        }
    }
    sw.print(",");
    sw.println(callback);
    sw.print(sb.toString());
    sw.println(");");

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

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

License:Apache License

/**
 * Writes the source for getMethods() the given target class to the given writer.
 *///ww w.  j  av  a 2s  .c o m
void writeGetMethods(JClassType target, SourceWriter writer) throws UnableToCompleteException {
    String targetType = target.getQualifiedSourceName();
    writer.println("public List<EventHandlerMethod<%s, ?>> getMethods() {", targetType);
    writer.indent();

    // Write a list that we will add all handlers to before returning
    writer.println("List<%1$s> methods = new LinkedList<%1$s>();",
            String.format("EventHandlerMethod<%s, ?>", targetType));

    // Iterate over each method in the target, looking for methods annotated with @Subscribe
    for (JMethod method : target.getInheritableMethods()) {
        if (method.getAnnotation(Subscribe.class) == null) {
            continue;
        }
        checkValidity(target, method);

        // Generate a list of types that should be handled by this method. Normally, this is a single
        // type equal to the method's first argument. If the argument in a MultiEvent, this list of
        // types comes from the @EventTypes annotation on the parameter.
        final List<String> paramTypes = new LinkedList<String>();
        final boolean isMultiEvent;
        if (getFirstParameterType(method).equals(MultiEvent.class.getCanonicalName())) {
            isMultiEvent = true;
            for (Class<?> type : method.getParameters()[0].getAnnotation(EventTypes.class).value()) {
                paramTypes.add(type.getCanonicalName());
            }
        } else {
            isMultiEvent = false;
            paramTypes.add(getFirstParameterType(method));
        }

        // Add an implementation of EventHandlerMethod to the list for each type this method handles
        for (String paramType : paramTypes) {
            writer.println("methods.add(new EventHandlerMethod<%s, %s>() {", targetType, paramType);
            writer.indent();
            {
                // Implement invoke() by calling the method, first checking filters if provided
                writer.println("public void invoke(%s instance, %s arg) {", targetType, paramType);
                String invocation = String.format(
                        isMultiEvent ? "instance.%s(new MultiEvent(arg));" : "instance.%s(arg);",
                        method.getName());
                if (method.getAnnotation(When.class) != null) {
                    writer.indentln("if (%s) { %s }", getFilter(method), invocation);
                } else {
                    writer.indentln(invocation);
                }
                writer.println("}");

                // Implement acceptsArgument using instanceof
                writer.println("public boolean acceptsArgument(Object arg) {");
                writer.indentln("return arg instanceof %s;", paramType);
                writer.println("}");

                // Implement getDispatchOrder as the inverse of the method's priority
                writer.println("public int getDispatchOrder() {");
                writer.indentln("return %d;",
                        method.getAnnotation(WithPriority.class) != null
                                ? -method.getAnnotation(WithPriority.class).value()
                                : 0);
                writer.println("}");
            }
            writer.outdent();
            writer.println("});");
        }
    }

    // Return the list of EventHandlerMethods
    writer.println("return methods;");
    writer.outdent();
    writer.println("}");
}

From source file:com.gafactory.core.rebind.LabelProviderCreator.java

License:sencha.com license

@Override
protected void create(SourceWriter sw) throws UnableToCompleteException {
    sw.println("public static final %1$s INSTANCE = new %1$s();", getSimpleName());

    // @Override/*from   ww w.  j  ava2 s.c  om*/
    sw.println("public String getLabel(%1$s item) {", getObjectTypeName());

    // if the value is string, just return a getter for the value
    sw.indentln("return %1$s;", getGetterExpression("item"));

    // else toString() it, or String.valueOf() if it is a primitive

    sw.println("}");
}

From source file:com.gafactory.core.rebind.ModelKeyProviderCreator.java

License:sencha.com license

@Override
protected void create(SourceWriter sw) throws UnableToCompleteException {
    sw.println("public static final %1$s INSTANCE = new %1$s();", getSimpleName());

    // @Override/*from w  w w. ja v  a2  s.com*/
    sw.println("public String getKey(%1$s item) {", getObjectTypeName());

    // if the value is string, just return a getter for the value
    sw.indentln("return \"\" + %1$s;", getGetterExpression("item"));

    // else toString() it, or String.valueOf() if it is a primitive

    sw.println("}");
}

From source file:com.gafactory.core.rebind.ValueProviderCreator.java

License:sencha.com license

@Override
protected void create(SourceWriter sw) throws UnableToCompleteException {
    sw.println("public static final %1$s INSTANCE = new %1$s();", getSimpleName());
    // @Override/*from  w ww  . ja v a2  s  .co  m*/
    sw.println("public %1$s getValue(%2$s object) {", getValueTypeName(), getObjectTypeName());
    String getter = getGetterExpression("object");
    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 {
            getLogger().log(Type.ERROR, "No getter can be found, unable to proceed");
            throw new UnableToCompleteException();
        }
    } else {
        sw.indentln("return %1$s;", getter);
    }
    sw.println("}");

    // @Override
    sw.println("public void setValue(%1$s object, %2$s value) {", getObjectTypeName(), getValueTypeName());
    String setter = getSetterExpression("object", "value");
    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 {
            getLogger().log(Type.ERROR, "No setter can be found, unable to proceed");
            throw new UnableToCompleteException();
        }
    } else {
        sw.indentln("%1$s;", setter);
    }
    sw.println("}");

    // @Override
    sw.println("public String getPath() {");
    StringBuilder sb = new StringBuilder();
    boolean first = true;
    for (String p : path) {
        if (!first) {
            sb.append(".");
        }
        sb.append(p);

        first = false;
    }
    sw.indentln("return \"%1$s\";", sb.toString());
    sw.println("}");
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksControlGenerator.java

License:Apache License

private void printFactoryMethod(SourceWriter out, JMethod methodToImplement, JClassType mockControlInterface,
        String classToCreate) {/*  ww w.j av a  2s. c om*/
    out.println("%s {", methodToImplement.getReadableDeclaration(false, false, false, false, true));
    out.indent();
    if (isNiceMock(methodToImplement, mockControlInterface)) {
        out.print("return this.setToNice(new %s(", classToCreate);
        printMatchingParameters(out, methodToImplement);
        out.println(").__mockInit(this));");
    } else {
        out.print("return new %s(", classToCreate);
        printMatchingParameters(out, methodToImplement);
        out.println(").__mockInit(this);");
    }
    out.outdent();
    out.println("}");
}

From source file:com.google.gwt.testing.easygwtmock.rebind.MocksGenerator.java

License:Apache License

/**
 * Generates and prints the actual mock versions of the methods.
 *///from  w ww.java  2 s  .  c  om
private void printMockMethods(SourceWriter sourceWriter, List<JMethod> methodsToMock, String newClassName) {
    int methodNo = 0;
    for (JMethod method : methodsToMock) {
        sourceWriter.println("%s {", method.getReadableDeclaration(false, true, false, false, true));
        sourceWriter.indent();
        printMockMethodBody(sourceWriter, method, methodNo++, newClassName);
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.println();
    }
}

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

License:Apache License

/**
 * For interfaces that consist of nothing more than getters and setters,
 * create a map-based implementation that will allow the AutoBean's internal
 * state to be easily consumed.//from   www . ja  v a  2s. co  m
 */
private void writeCreateSimpleBean(SourceWriter sw, AutoBeanType type) {
    sw.println("@Override protected %s createSimplePeer() {", type.getPeerType().getQualifiedSourceName());
    sw.indent();
    // return new FooIntf() {
    sw.println("return new %s() {", type.getPeerType().getQualifiedSourceName());
    sw.indent();
    sw.println("private final %s data = %s.this.data;", Splittable.class.getCanonicalName(),
            type.getQualifiedSourceName());
    for (AutoBeanMethod method : type.getMethods()) {
        JMethod jmethod = method.getMethod();
        JType returnType = jmethod.getReturnType();
        sw.println("public %s {", getBaseMethodDeclaration(jmethod));
        sw.indent();
        switch (method.getAction()) {
        case GET: {
            String castType;
            if (returnType.isPrimitive() != null) {
                castType = returnType.isPrimitive().getQualifiedBoxedSourceName();
                // Boolean toReturn = Other.this.getOrReify("foo");
                sw.println("%s toReturn = %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(),
                        method.getPropertyName());
                // return toReturn == null ? false : toReturn;
                sw.println("return toReturn == null ? %s : toReturn;",
                        returnType.isPrimitive().getUninitializedFieldExpression());
            } else if (returnType
                    .equals(context.getTypeOracle().findType(Splittable.class.getCanonicalName()))) {
                sw.println("return data.isNull(\"%1$s\") ? null : data.get(\"%1$s\");",
                        method.getPropertyName());
            } else {
                // return (ReturnType) Outer.this.getOrReify(\"foo\");
                castType = ModelUtils.getQualifiedBaseSourceName(returnType);
                sw.println("return (%s) %s.this.getOrReify(\"%s\");", castType, type.getSimpleSourceName(),
                        method.getPropertyName());
            }
        }
            break;
        case SET:
        case SET_BUILDER: {
            JParameter param = jmethod.getParameters()[0];
            // Other.this.setProperty("foo", parameter);
            sw.println("%s.this.setProperty(\"%s\", %s);", type.getSimpleSourceName(), method.getPropertyName(),
                    param.getName());
            if (JBeanMethod.SET_BUILDER.equals(method.getAction())) {
                sw.println("return this;");
            }
            break;
        }
        case CALL:
            // return com.example.Owner.staticMethod(Outer.this, param,
            // param);
            JMethod staticImpl = method.getStaticImpl();
            if (!returnType.equals(JPrimitiveType.VOID)) {
                sw.print("return ");
            }
            sw.print("%s.%s(%s.this", staticImpl.getEnclosingType().getQualifiedSourceName(),
                    staticImpl.getName(), type.getSimpleSourceName());
            for (JParameter param : jmethod.getParameters()) {
                sw.print(", %s", param.getName());
            }
            sw.println(");");
            break;
        default:
            throw new RuntimeException();
        }
        sw.outdent();
        sw.println("}");
    }
    sw.outdent();
    sw.println("};");
    sw.outdent();
    sw.println("}");
}