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

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

Introduction

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

Prototype

void print(String s);

Source Link

Usage

From source file:org.rapla.rest.gwtjsonrpc.rebind.SerializerCreator.java

License:Apache License

private void generateEnumFromJson(final SourceWriter w) {
    w.print("public ");
    w.print(targetType.getQualifiedSourceName());
    w.println(" fromJson(Object in) {");
    w.indent();/*  w w  w .ja v a2  s.  c  o m*/
    w.print("return in != null");
    w.print(" ? " + targetType.getQualifiedSourceName() + ".valueOf((String)in)");
    w.print(" : null");
    w.println(";");
    w.outdent();
    w.println("}");
    w.println();
}

From source file:org.rapla.rest.gwtjsonrpc.rebind.SerializerCreator.java

License:Apache License

private void generatePrintJson(final SourceWriter w) {
    final JField[] fieldList = sortFields(targetType);
    w.print("protected int printJsonImpl(int fieldCount, StringBuilder sb, ");
    w.println("Object instance) {");
    w.indent();/*w  ww .  j av a 2  s.co m*/

    w.print("final ");
    w.print(targetType.getQualifiedSourceName());
    w.print(" src = (");
    w.print(targetType.getQualifiedSourceName());
    w.println(")instance;");

    if (needsSuperSerializer(targetType)) {
        w.print("fieldCount = super.printJsonImpl(fieldCount, sb, (");
        w.print(targetType.getSuperclass().getQualifiedSourceName());
        w.println(")src);");
    }

    final String docomma = "if (fieldCount++ > 0) sb.append(\",\");";
    for (final JField f : fieldList) {
        final String doget;
        if (f.isPrivate()) {
            doget = "objectGet_" + f.getName() + "(src)";
        } else {
            doget = "src." + f.getName();
        }

        final String doname = "sb.append(\"\\\"" + f.getName() + "\\\":\");";
        if (f.getType() == JPrimitiveType.CHAR || isBoxedCharacter(f.getType())) {
            w.println(docomma);
            w.println(doname);
            w.println("sb.append(\"\\\"\");");
            w.println("sb.append(" + JsonSerializer.class.getSimpleName() + ".escapeChar(" + doget + "));");
            w.println("sb.append(\"\\\"\");");
        } else if (isJsonString(f.getType())) {
            w.println("if (" + doget + " != null) {");
            w.indent();
            w.println(docomma);
            w.println(doname);
            w.println("sb.append(" + JsonSerializer.class.getSimpleName() + ".escapeString(" + doget + "));");
            w.outdent();
            w.println("}");
            w.println();
        } else if (f.getType().isPrimitive() != null) {
            w.println(docomma);
            w.println(doname);
            w.println("sb.append(" + doget + ");");
            w.println();
        } else if (isJsonPrimitive(f.getType()) || isBoxedPrimitive(f.getType())) {
            w.println("if (" + doget + " != null) {");
            w.println(docomma);
            w.println(doname);
            w.println("sb.append(" + doget + ");");
            w.println();
            w.println("}");
        } else {
            w.println("if (" + doget + " != null) {");
            w.indent();
            w.println(docomma);
            w.println(doname);
            if (needsTypeParameter(f.getType())) {
                w.print("ser_" + f.getName());
            } else {
                w.print(serializerFor(f.getType()) + ".INSTANCE");
            }
            w.println(".printJson(sb, " + doget + ");");
            w.outdent();
            w.println("}");
            w.println();
        }
    }

    w.println("return fieldCount;");
    w.outdent();
    w.println("}");
    w.println();
}

From source file:org.rapla.rest.gwtjsonrpc.rebind.SerializerCreator.java

License:Apache License

private void generateFromJson(final SourceWriter w) {
    w.print("public ");
    w.print(targetType.getQualifiedSourceName());
    w.println(" fromJson(Object in) {");
    w.indent();/*w ww. j a va2  s  .  c  om*/
    if (targetType.isAbstract()) {
        w.println("throw new UnsupportedOperationException();");
    } else {
        w.println("if (in == null) return null;");
        w.println("final JavaScriptObject jso = (JavaScriptObject)in;");
        w.print("final ");
        w.print(targetType.getQualifiedSourceName());
        w.print(" dst = new ");
        w.println(targetType.getQualifiedSourceName() + "();");
        w.println("fromJsonImpl(jso, dst);");
        w.println("return dst;");
    }
    w.outdent();
    w.println("}");
    w.println();

    w.print("protected void fromJsonImpl(JavaScriptObject jso,");
    w.print(targetType.getQualifiedSourceName());
    w.println(" dst) {");
    w.indent();

    if (needsSuperSerializer(targetType)) {
        w.print("super.fromJsonImpl(jso, (");
        w.print(targetType.getSuperclass().getQualifiedSourceName());
        w.println(")dst);");
    }

    for (final JField f : sortFields(targetType)) {
        final String doget = "jsonGet_" + f.getName() + "(jso)";
        final String doset0, doset1;

        if (f.isPrivate()) {
            doset0 = "objectSet_" + f.getName() + "(dst, ";
            doset1 = ")";
        } else {
            doset0 = "dst." + f.getName() + " = ";
            doset1 = "";
        }

        JType type = f.getType();
        if (type.isArray() != null) {
            final JType ct = type.isArray().getComponentType();
            w.println("if (" + doget + " != null) {");
            w.indent();

            w.print("final ");
            w.print(ct.getQualifiedSourceName());
            w.print("[] tmp = new ");
            w.print(ct.getQualifiedSourceName());
            w.print("[");
            w.print(ObjectArraySerializer.class.getName());
            w.print(".size(" + doget + ")");
            w.println("];");

            w.println("ser_" + f.getName() + ".fromJson(" + doget + ", tmp);");

            w.print(doset0);
            w.print("tmp");
            w.print(doset1);
            w.println(";");

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

        } else if (isJsonPrimitive(type)) {
            w.print(doset0);
            w.print(doget);
            w.print(doset1);
            w.println(";");

        } else if (isBoxedPrimitive(type)) {
            w.print(doset0);
            w.print("( " + doget + " != null) ? ");
            //w.print("new " + type.getQualifiedSourceName() + "(");
            w.print(doget);
            //w.print(")");
            w.print(":null");
            w.print(doset1);
            w.println(";");

        } else {
            w.print(doset0);
            if (needsTypeParameter(type)) {
                w.print("ser_" + f.getName());
            } else {
                String serializerFor = serializerFor(type);
                w.print(serializerFor + ".INSTANCE");
            }
            w.print(".fromJson(" + doget + ")");
            w.print(doset1);
            w.println(";");
        }
    }

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

From source file:org.rstudio.core.rebind.command.MenuEmitter.java

License:Open Source License

private void emitMenu(SourceWriter writer, Element el) throws UnableToCompleteException {
    for (Node n = el.getFirstChild(); n != null; n = n.getNextSibling()) {
        if (n.getNodeType() != Node.ELEMENT_NODE)
            continue;

        Element child = (Element) n;

        if (child.getTagName().equals("cmd")) {
            String cmdId = child.getAttribute("refid");
            writer.print("callback.addCommand(");
            writer.print("\"" + Generator.escape(cmdId) + "\", ");
            writer.println("this.cmds." + cmdId + "());");
        } else if (child.getTagName().equals("separator")) {
            writer.println("callback.addSeparator();");
        } else if (child.getTagName().equals("menu")) {
            String label = child.getAttribute("label");
            writer.println("callback.beginMenu(\"" + Generator.escape(label) + "\");");
            emitMenu(writer, child);/*from  ww w.j  av  a  2 s  .  c  o  m*/
            writer.println("callback.endMenu();");
        } else if (child.getTagName().equals("dynamic")) {
            String dynamicClass = child.getAttribute("class");
            writer.println("new " + dynamicClass + "().execute(callback);");
        } else {
            logger_.log(TreeLogger.Type.ERROR, "Unexpected tag " + el.getTagName() + " in menu");
            throw new UnableToCompleteException();
        }
    }
}

From source file:org.rstudio.core.rebind.JavaScriptSerializerGenerator.java

License:Open Source License

private void printSerializers(List<JClassType> classes, SourceWriter w) {
    // print the method that dispatches to the appropriate serializer
    w.println("public <T> JavaScriptObject serialize(T source)");
    w.println("{");
    w.indent();//from  w w  w . j  a v a  2  s  . c om
    for (JClassType classType : classes) {
        if (classType.isAbstract())
            continue;
        w.println();
        w.println("if (source.getClass().getName() == " + classType.getQualifiedSourceName()
                + ".class.getName())");
        w.println("{");
        w.indent();
        w.println("return serializeJso((" + classType.getQualifiedSourceName() + ") source);");
        w.outdent();
        w.println("}");
        w.println();
    }
    w.println("return null;");
    w.outdent();
    w.println("}");
    // print individual serializers
    for (JClassType classType : classes) {
        w.print("private final native JavaScriptObject serializeJso(");
        w.println(classType.getQualifiedSourceName() + " source) /*-{");
        w.indent();
        w.println("return {");
        w.indent();
        w.println("\"class_name\":\"" + classType.getQualifiedSourceName() + "\",");
        w.println("\"class_data\": {");
        w.indent();
        JField[] fields = classType.getFields();
        for (int i = 0; i < fields.length; i++) {
            JField field = fields[i];
            if (!field.isStatic()) {
                w.print("\"" + field.getName() + "\": ");
                if (isAnnotatedSerializable(field)) {
                    w.print("this.@" + genPackageName + "." + genClassName + "::serializeJso(L");
                    w.print(field.getType().getQualifiedSourceName().replace(".", "/"));
                    w.print(";)(");
                }
                w.println("source.@" + classType.getQualifiedSourceName() + "::" + field.getName());
                if (isAnnotatedSerializable(field)) {
                    w.print(")");
                }
                if (i < (fields.length - 1))
                    w.print(", ");
                w.println();
            }
        }
        w.outdent();
        w.println("}");
        w.outdent();
        w.println("};");
        w.outdent();
        w.println("}-*/;");
        w.println();
    }
}

From source file:org.rstudio.core.rebind.JavaScriptSerializerGenerator.java

License:Open Source License

private void printDeserializers(List<JClassType> classes, SourceWriter w) {
    w.println("private final native String classFromJso(" + "JavaScriptObject jso) /*-{");
    w.indent();//  w w  w .j a  va2  s  . c  o m
    w.println("return jso.class_name;");
    w.outdent();
    w.println("}-*/;");
    w.println();

    // print the method that dispatches to the appropriate deserializer
    w.println("public <T> T deserialize (JavaScriptObject jso)");
    w.println("{");
    w.indent();
    for (JClassType classType : classes) {
        // ignore abstract classes
        if (classType.isAbstract())
            continue;

        // determine class name from string
        w.println();
        w.println("if (classFromJso(jso) == \"" + classType.getQualifiedSourceName() + "\")");
        w.println("{");
        w.indent();
        w.println(classType.getQualifiedSourceName() + " ret = new " + classType.getQualifiedSourceName()
                + "();");
        w.println("deserializeJso(ret, jso);");
        w.println("return (T) ret;");
        w.outdent();
        w.println("}");
        w.println();
    }
    w.println("return null;");
    w.outdent();
    w.println("}");

    // emit individual deserializer methods (overloads)
    for (JClassType classType : classes) {
        if (classType.isAbstract())
            continue;
        w.println();
        w.println("private final native void deserializeJso(" + classType.getQualifiedSourceName() + " dest, "
                + "JavaScriptObject source) /*-{");
        w.indent();
        for (JField field : classType.getFields()) {
            if (!field.isStatic()) {
                w.print("dest.@" + classType.getQualifiedSourceName() + "::");
                w.print(field.getName() + " = ");
                if (isAnnotatedSerializable(field)) {
                    w.print("this.@" + genPackageName + "." + genClassName + "::deserialize(");
                    w.print("Lcom/google/gwt/core/client/JavaScriptObject;)(");
                }
                w.print("source.class_data[\"" + field.getName() + "\"]");
                if (isAnnotatedSerializable(field))
                    w.print(")");
                w.println(";");
            }
        }
        w.outdent();
        w.println("}-*/;");
    }
}

From source file:org.senchalabs.gwt.gwtdriver.SeExporterGenerator.java

License:Apache License

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

    JClassType jso = oracle.findType(Name.getSourceNameForClass(JavaScriptObject.class));

    JClassType toGenerate = oracle.findType(typeName).isClass();

    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }/*from   ww  w .ja  v a  2s  . c o  m*/

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(typeName);
    SourceWriter sw = factory.createSourceWriter(context, pw);

    List<String> exportedTypes;
    try {
        exportedTypes = context.getPropertyOracle().getConfigurationProperty(SELENIUM_METHODS).getValues();
    } catch (BadPropertyValueException e) {
        logger.log(TreeLogger.Type.ERROR,
                "Can't find any config property for " + SELENIUM_METHODS + " declared", e);
        throw new UnableToCompleteException();
    }
    sw.println("protected void exportRegisteredTypes() {");
    sw.indent();
    //for each type set up in a config property,
    for (String exportedType : exportedTypes) {
        JClassType toExport = oracle.findType(exportedType);
        if (toExport == null) {
            logger.log(TreeLogger.Type.ERROR,
                    "Cannot find " + exportedType + " be sure it is a valid GWT type");
            throw new UnableToCompleteException();
        }
        MethodsFor refersToType = toExport.getAnnotation(MethodsFor.class);
        if (refersToType == null) {
            logger.log(Type.ERROR, "Type " + exportedType
                    + " is declared as having webdriver methods, but has no @MethodsFor annotation");
            throw new UnableToCompleteException();
        }
        //verify a default ctor - if not, methods must be static
        boolean requireStatic = toExport.getConstructors().length != 0
                && toExport.findConstructor(new JType[] {}) == null;
        if (requireStatic) {
            logger.log(Type.INFO, "No default constructor found, all marked methods must be static");
        }
        TreeLogger typeLogger = logger.branch(TreeLogger.Type.DEBUG, "Exporting methods in " + exportedType);
        //iterate through the methods
        for (JMethod m : toExport.getInheritableMethods()) {
            Method refersToMethod = m.getAnnotation(Method.class);
            if (refersToMethod == null) {
                continue;
            }
            TreeLogger methodLogger = typeLogger.branch(Type.DEBUG, "Examining " + m.getName());
            if (requireStatic && !m.isStatic()) {
                typeLogger.log(Type.ERROR, "No default constructor found for " + exportedType
                        + ", can't export instance method" + m.getName());
                typeLogger.log(Type.ERROR,
                        "Either mark the method as static, or ensure there is a default constructor.");
                throw new UnableToCompleteException();
            }
            //verify that the method matches exactly one method in the webdriver side
            //TODO make this a little faster
            String matchingMethod = null;
            for (java.lang.reflect.Method exportableMethod : refersToType.value().getMethods()) {
                if (refersToMethod.value().equals(exportableMethod.getName())) {
                    if (matchingMethod != null) {
                        methodLogger.log(Type.ERROR,
                                "Multiple methods found that match " + refersToMethod.value());
                        throw new UnableToCompleteException();
                    }
                    matchingMethod = refersToMethod.value();
                }
            }
            if (matchingMethod == null) {
                methodLogger.log(Type.ERROR, "Can't find a method that matches " + refersToMethod.value());
                throw new UnableToCompleteException();
            }

            //emit a registerFunction call wrapping it
            sw.println("registerFunction(\"%1$s\", \"%2$s\", new %3$s() {",
                    escape(refersToType.value().getName()), escape(matchingMethod),
                    Name.getSourceNameForClass(Function.class));
            sw.indent();
            sw.println("public Object apply(%1$s<?> args) {", Name.getSourceNameForClass(JsArray.class));
            sw.indent();
            JType retType = m.getReturnType();
            if (retType.isPrimitive() != null) {
                switch (retType.isPrimitive()) {
                case VOID:
                    //do nothing
                    break;
                case INT:
                case DOUBLE:
                case BOOLEAN:
                    sw.print("return \"\" + ");
                    break;
                default:
                    methodLogger.log(Type.ERROR, "Can't return primitive " + retType + " from exported method");
                    throw new UnableToCompleteException();
                }
            } else if (retType.isClass() != null && retType.getQualifiedSourceName().equals("java.lang.String")
                    || ((retType.isClass() != null) && retType.isClass().isAssignableTo(jso))
                    || ((retType.isInterface() != null)
                            && oracle.getSingleJsoImplInterfaces().contains(retType))) {
                sw.print("return ");
            } else {
                methodLogger.log(Type.ERROR,
                        "Can't return non-jso, non-supported primitive " + retType + " from exported method");
                throw new UnableToCompleteException();
            }
            if (m.isStatic()) {
                sw.print(exportedType);
            } else {
                sw.print("%1$s.<%2$s>create(%2$s.class)", GWT.class.getName(), exportedType);
            }
            sw.print(".%1$s(", matchingMethod);
            //iterate through the arguments
            //verify the arg type is legal
            JType[] erasedParameterTypes = m.getErasedParameterTypes();
            for (int i = 0; i < erasedParameterTypes.length; i++) {
                JType type = erasedParameterTypes[i];

                if (type.isPrimitive() != null || type.getQualifiedSourceName().equals("java.lang.String")) {
                    //cast uglyness
                    sw.print("args.<%2$s>cast().get(%1$d)", i, getJsArray(type));
                } else if (type.isClass() != null && type.isClass().isAssignableTo(jso)) {
                    //normal array plus cast() trickery
                    sw.print("args.get(%1$d).<%2$s>cast()", i, type.getQualifiedSourceName());
                } else if (type.isInterface() != null
                        && oracle.getSingleJsoImplInterfaces().contains(type.isInterface())) {
                    //single jso cast thing
                    sw.print("args.get(%1$d).<%2$s>cast()", i,
                            oracle.getSingleJsoImpl(type.isInterface()).getQualifiedSourceName());
                } else {//TODO goktug's magic new jsinterface
                    methodLogger.log(Type.ERROR, "Can't handle argument of type " + type);
                    throw new UnableToCompleteException();
                }
                if (i != erasedParameterTypes.length - 1) {
                    sw.println(",");
                }
            }
            sw.println(");");

            if (m.getReturnType() == JPrimitiveType.VOID) {
                sw.println("return null;");
            }

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

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:org.sprintapi.hyperdata.gwt.ArrayAdapterGenerator.java

License:Apache License

private void composeSetMethod(SourceWriter sourceWriter, JArrayType parameterizedType) {
    sourceWriter.print(
            "public void set(java.lang.Object array, int dimension, int index, java.lang.Object value) throws org.sprintapi.hyperdata.gwt.client.AdapterException {");

    sourceWriter.print("   if (dimension == 0) {");
    sourceWriter.print("       ((" + parameterizedType.getLeafType().getQualifiedSourceName()
            + "[])array)[index] = (" + parameterizedType.getLeafType().getQualifiedSourceName() + ")value;");
    String suffix = "";
    for (int i = 0; i < parameterizedType.getRank(); i++) {
        suffix += "[]";
        sourceWriter.print("   } else if (dimension == " + (i + 1) + ") {");
        sourceWriter.print("       ((" + parameterizedType.getLeafType().getQualifiedSourceName() + "[]"
                + suffix + ")array)[index] = (" + parameterizedType.getLeafType().getQualifiedSourceName()
                + suffix + ")value;");
    }// w  w w.ja  va  2 s.c  o  m
    sourceWriter.print("   }");
    sourceWriter.print("}");

    Object o = new Integer[10][];

    ((Integer[][]) o)[0] = new Integer[4];

}

From source file:org.sprintapi.hyperdata.gwt.ArrayAdapterGenerator.java

License:Apache License

private void composeGetMethod(SourceWriter sourceWriter, JClassType parameterizedType) {
    sourceWriter.print(
            "public java.lang.Object get(java.lang.Object object, int dim, int index) throws org.sprintapi.hyperdata.gwt.client.AdapterException {");

    //        if (parameterizedType.getMethods() != null) {
    //           int count = 0;
    //           for (JMethod method : parameterizedType.getMethods()) {
    //              if (method.isAnnotationPresent(Transient.class)) {
    //                 continue;
    //              }
    //              if (method.getName().startsWith("get")) {
    //                 if (count > 0) {
    //                    sourceWriter.print(" else ");
    //                 }
    //                 sourceWriter.print("name = java.lang.Character.toUpperCase(name.charAt(0)) + name.substring(1);");
    //                 sourceWriter.print("if (\"" + method.getName().substring("get".length()) + "\".equals(name)) {");
    //                 //TODO check the return type
    //                 //TODO isPrimitive
    //                 sourceWriter.print("  return object." + method.getName() + "();");
    //                 sourceWriter.print("}"); 
    //                 count += 1;
    //              }
    //           }
    //        }/*from ww  w  .  j  av  a 2  s .  co m*/
    sourceWriter.print(" return null;");
    sourceWriter.print("}");
}

From source file:org.sprintapi.hyperdata.gwt.ArrayAdapterGenerator.java

License:Apache License

private void composeGetArrayClassMethod(SourceWriter sourceWriter, JArrayType parameterizedType) {
    sourceWriter.print("public java.lang.Class<?> getArrayClass(int dimension) {");
    sourceWriter.print("   if (dimension == 0) {");
    sourceWriter.print("      return " + parameterizedType.getLeafType().getQualifiedSourceName() + ".class;");

    String suffix = "";
    for (int i = 0; i < parameterizedType.getRank(); i++) {
        suffix += "[]";
        sourceWriter.print("   } else if (dimension == " + (i + 1) + ") {");
        sourceWriter.print("      return " + parameterizedType.getLeafType().getQualifiedSourceName() + suffix
                + ".class;");
    }/*from ww  w.  j  av a2 s  . c o m*/

    sourceWriter.print("   }");
    sourceWriter.print("  return null;");
    sourceWriter.print("}");
}