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.totsp.gwittir.rebind.beans.IntrospectorGenerator.java

License:Open Source License

private void writeMethod(TreeLogger logger, MethodWrapper method, SourceWriter writer) {
    JType ptype = this.resolveType(method.getDeclaringType());

    writer.println("new Method(){ ");
    writer.indent();/*w  ww .  j a  va 2 s.c om*/
    writer.println("public String getName() {");
    writer.indentln("return \"" + method.getBaseMethod().getName() + "\";");
    writer.println(" }");
    writer.println("public Object invoke( Object target, Object[] args ) throws Exception {");
    writer.indent();
    writer.println(ptype.getQualifiedSourceName() + " casted =");
    writer.println("(" + ptype.getQualifiedSourceName() + ") target;");
    logger.log(TreeLogger.SPAM, "Method: " + method.getBaseMethod().getName() + " "
            + method.getBaseMethod().getReturnType().getQualifiedSourceName(), null);

    if (!(method.getBaseMethod().getReturnType().isPrimitive() == JPrimitiveType.VOID)) {
        writer.print("return ");
    }

    JType type = this.resolveType(method.getBaseMethod().getReturnType());

    boolean boxed = this.box(type, writer);
    writer.print("casted." + method.getBaseMethod().getName() + "(");

    if (method.getBaseMethod().getParameters() != null) {
        for (int j = 0; j < method.getBaseMethod().getParameters().length; j++) {
            JType arg = this.resolveType(method.getBaseMethod().getParameters()[j].getType());

            this.unbox(arg, "args[" + j + "]", writer);

            if (j != (method.getBaseMethod().getParameters().length - 1)) {
                writer.print(", ");
            }
        }
    }

    writer.print(")");

    if (boxed) {
        writer.print(")");
    }

    writer.println(";");

    if (method.getBaseMethod().getReturnType().getQualifiedSourceName().equals("void")) {
        writer.println("return null;");
    }

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

From source file:com.totsp.gwittir.rebind.beans.IntrospectorGenerator.java

License:Open Source License

private void writeResolver(List introspectables, SourceWriter writer) {
    writer.println("public Class resolveClass(Object object){");
    writer.indent();/*w ww . j  av  a2s. co m*/

    for (Iterator it = introspectables.iterator(); it.hasNext();) {
        BeanResolver type = (BeanResolver) it.next();
        writer.println("if( object instanceof " + type.getType().getQualifiedSourceName() + " ) return "
                + type.getType().getQualifiedSourceName() + ".class;");
    }

    writer.println("throw new RuntimeException( \"Object \"+object+\"could not be resolved.\" );");
    writer.outdent();
    writer.println("}");
}

From source file:com.totsp.gwittir.serial.json.rebind.JSONCodecGenerator.java

License:Open Source License

public void writeReader(SourceWriter writer, RProperty prop) {
    if (prop.getWriteMethod() == null) {
        return;/* w w w .  ja v a  2  s .  c om*/
    }

    JSONField field = prop.getReadMethod() == null ? null
            : prop.getReadMethod().getBaseMethod().getAnnotation(JSONField.class);
    JSONOmit omit = prop.getReadMethod() == null ? null
            : prop.getReadMethod().getBaseMethod().getAnnotation(JSONOmit.class);
    System.out.println(prop.getName() + " omit " + omit + " field " + field);
    if (omit != null) {
        return;
    }

    String fieldName = (field == null) ? prop.getName() : field.value();

    try {
        writer.println("if(root.containsKey(\"" + fieldName + "\")){");

        if (prop.getType().isPrimitive() == null) {
            writer.println("if(root.get(\"" + fieldName + "\").isNull() != null) {");
            writer.println(this.setterPrefix(prop) + "null);");
            writer.println("} else {");
        }

        if (prop.getType().isArray() != null) {
            JArrayType arrayType = prop.getType().isArray();
            JType paramType = arrayType.getComponentType();
            writer.println("JSONArray array = root.get(\"" + fieldName + "\").isArray();");
            writer.println(paramType.getQualifiedSourceName() + "[] value = new "
                    + paramType.getQualifiedSourceName() + "[ array.size() ];");
            writer.println("for(int i=0; i<array.size(); i++){");
            writer.indent();

            writer.println(" value[i] = " + this.fromType(paramType, "array.get(i)") + ";");

            writer.outdent();
            writer.println("}"); //endfor
            writer.println(this.setterPrefix(prop) + " value );");
        } else if (prop.getType() instanceof JClassType
                && ((JClassType) prop.getType()).isAssignableTo(this.collectionType)) {
            // get the parameter type
            JClassType propType = (JClassType) prop.getType();
            JType paramType = propType.asParameterizationOf((JGenericType) this.collectionType)
                    .getTypeArgs()[0];
            writer.println("JSONArray array = root.get(\"" + fieldName + "\").isArray();");
            writer.println(propType.getParameterizedQualifiedSourceName() + " col = "
                    + this.newCollectionExpression(propType) + ";");
            writer.println("for(int i=0; i<array.size(); i++){");
            writer.indent();

            writer.println(" col.add(" + this.fromType(paramType, "array.get(i)") + ");");

            writer.outdent();
            writer.println("}"); //endfor
            writer.println(this.setterPrefix(prop) + " col );");
        } else {
            writer.println(
                    setterPrefix(prop) + fromType(prop.getType(), "root.get(\"" + fieldName + "\")") + ");");
        }

        if (prop.getType().isPrimitive() == null) {
            writer.println("}"); //end null else
        }

        writer.println("}"); //end contains key
    } catch (Exception e) {
        System.out.println("Exception on prop " + prop);
        throw new RuntimeException(e);
    }
}

From source file:com.totsp.gwittir.serial.json.rebind.JSONCodecGenerator.java

License:Open Source License

private void writeDeserializer(SourceWriter writer, BeanResolver r) {
    writer.println("public " + r.toString() + " deserialize(String data) throws SerializationException { ");
    writer.indent();//from   w  w w. j a v  a2 s . co m
    writer.println("try {");
    writer.indent();
    writer.println("JSONObject root = JSONParser.parse(data).isObject(); ");
    writer.println(" return this.deserializeFromJSONObject(root);");
    writer.println("} catch (Exception e) { ");
    writer.indent();
    writer.println("throw new SerializationException(e);");
    writer.outdent();
    writer.println("}");
    writer.println("}");

    writer.println("public " + r.toString()
            + " deserializeFromJSONObject(JSONObject root) throws SerializationException {");
    writer.indent();
    writer.println(" if(root == null) return null;");
    writer.println("try {");
    writer.indent();

    writer.println(r.getType().getQualifiedSourceName() + " destination = new "
            + r.getType().getQualifiedSourceName() + "();");

    for (RProperty p : r.getProperties().values()) {
        if (p.getWriteMethod() != null) {
            writeReader(writer, p);
        }
    }

    writer.println(" return destination;");
    writer.outdent();
    writer.println("} catch (Exception e) { ");
    writer.indent();
    writer.println("throw new SerializationException(e);");
    writer.outdent();
    writer.println("}");
    writer.outdent();
    writer.println("}");
}

From source file:com.totsp.gwittir.serial.json.rebind.JSONCodecGenerator.java

License:Open Source License

private void writeSerializer(SourceWriter writer, BeanResolver r) {
    writer.println("public JSONObject serializeToJSONObject( " + r.getType().getQualifiedSourceName()
            + " source ) throws SerializationException { ");
    writer.indent();/*from w w  w.  j  av a 2  s. c o  m*/
    writer.println(" JSONObject destination = new JSONObject();");

    for (RProperty prop : r.getProperties().values()) {
        if (prop.getName().equals("class") || prop.getReadMethod() == null) {
            continue;
        }

        JSONField field = prop.getReadMethod().getBaseMethod().getAnnotation(JSONField.class);
        JSONOmit omit = prop.getReadMethod().getBaseMethod().getAnnotation(JSONOmit.class);
        System.out.println(" ws \t " + prop.getName() + " "
                + prop.getReadMethod().getBaseMethod().getEnclosingType()
                + prop.getReadMethod().getBaseMethod().getReadableDeclaration() + " " + omit + " " + field);
        if (omit != null) {
            continue;
        }

        String fieldName = (field == null) ? prop.getName() : field.value();

        if (prop.getReadMethod() != null) {
            JClassType classType = prop.getType().isClassOrInterface();
            JArrayType arrayType = prop.getType().isArray();
            System.out.println(prop.getName() + "  ArrayType " + arrayType + " :: "
                    + ((arrayType == null ? "" : "" + arrayType.getComponentType())));
            if ((classType != null) && (classType.isAssignableTo(this.collectionType)) || arrayType != null) {
                JType subType = (arrayType != null) ? arrayType.getComponentType()
                        : classType.asParameterizationOf(this.collectionType.isGenericType()).getTypeArgs()[0];
                writer.println();
                writer.println(
                        " if( source." + prop.getReadMethod().getBaseMethod().getName() + "() == null ){");
                writer.println("destination.put(\"" + fieldName + "\", JSONNull.getInstance());");
                writer.println(" } else { ");
                writer.println("int i=0; JSONArray value = new JSONArray();");
                writer.println("for( " + subType.getQualifiedSourceName() + " o : source."
                        + prop.getReadMethod().getBaseMethod().getName() + "()){");
                writer.println("   value.set(i++, " + toType(subType, " o ") + ");");
                writer.println("}");
                writer.println("destination.put(\"" + fieldName + "\", value);"); //TODO JSONField
                writer.println("}");
            } else {
                writer.print("destination.put( \"" + fieldName + "\", "); //TODO JSONField
                writer.print(toType(prop.getType(),
                        " source." + prop.getReadMethod().getBaseMethod().getName() + "() ") + ");");
            }
        }
    }

    writer.outdent();
    writer.println("return destination;");
    writer.println("}");

    writer.println("public String serialize(" + r.getType().getQualifiedSourceName()
            + " source ) throws SerializationException { ");
    writer.println("   return serializeToJSONObject(source).toString();");
    writer.println("}");
}

From source file:com.tyf.gwtphp.linker.PHPRPCLinker.java

License:Open Source License

private void writeArray(SourceWriter src, String[] params) {
    src.indent();/*  w w  w .j a  v a 2s .c o m*/
    for (String p : params) {
        src.println("array('type' => '%s'),", p);
    }
    src.outdent();
}

From source file:com.vaadin.server.widgetsetutils.AcceptCriteriaFactoryGenerator.java

License:Apache License

/**
 * Generate source code for WidgetMapImpl
 * //from   w w w .  ja v  a 2s.co  m
 * @param logger
 *            Logger object
 * @param context
 *            Generator context
 */
private void generateClass(TreeLogger logger, GeneratorContext context) {
    // get print writer that receives the source code
    PrintWriter printWriter = null;
    printWriter = context.tryCreate(logger, packageName, className);
    // print writer if null, source code has ALREADY been generated,
    // return (WidgetMap is equal to all permutations atm)
    if (printWriter == null) {
        return;
    }
    logger.log(Type.INFO, "Detecting available criteria ...");
    Date date = new Date();

    // init composer, set class properties, create source writer
    ClassSourceFileComposerFactory composer = null;
    composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.addImport("com.google.gwt.core.client.GWT");
    composer.setSuperclass("com.vaadin.client.ui.dd.VAcceptCriterionFactory");
    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

    // generator constructor source code
    generateInstantiatorMethod(sourceWriter, context, logger);
    // close generated class
    sourceWriter.outdent();
    sourceWriter.println("}");
    // commit generated class
    context.commit(logger, printWriter);
    logger.log(Type.INFO, "Done. (" + (new Date().getTime() - date.getTime()) / 1000 + "seconds)");

}

From source file:com.vaadin.server.widgetsetutils.AcceptCriteriaFactoryGenerator.java

License:Apache License

private void generateInstantiatorMethod(SourceWriter sourceWriter, GeneratorContext context,
        TreeLogger logger) {//w w  w .j  av a 2  s. c o m

    sourceWriter.println("public VAcceptCriterion get(String name) {");
    sourceWriter.indent();

    sourceWriter.println("name = name.intern();");

    JClassType criteriaType = context.getTypeOracle().findType(VAcceptCriterion.class.getName());
    JClassType[] subtypes = criteriaType.getSubtypes();
    Arrays.sort(subtypes, ConnectorBundle.jClassComparator);
    for (JClassType clientClass : subtypes) {
        AcceptCriterion annotation = clientClass.getAnnotation(AcceptCriterion.class);
        if (annotation != null) {
            String clientClassName = clientClass.getQualifiedSourceName();
            Class<?> serverClass = clientClass.getAnnotation(AcceptCriterion.class).value();
            String serverClassName = serverClass.getCanonicalName();
            logger.log(Type.INFO, "creating mapping for " + serverClassName);
            sourceWriter.print("if (\"");
            sourceWriter.print(serverClassName);
            sourceWriter.print("\" == name) return GWT.create(");
            sourceWriter.print(clientClassName);
            sourceWriter.println(".class );");
            sourceWriter.print("else ");
        }
    }

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

From source file:com.vaadin.server.widgetsetutils.ConnectorBundleLoaderFactory.java

License:Apache License

private void generateClass(TreeLogger logger, GeneratorContext context, String packageName, String className,
        String requestedType) throws Exception {
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);
    if (printWriter == null) {
        return;// w  w  w. j a v  a2  s .c  o m
    }

    List<CValUiInfo> cvalInfos = null;
    try {
        if (cvalChecker != null) {
            cvalInfos = cvalChecker.run();
            // Don't run twice
            cvalChecker = null;
        }
    } catch (InvalidCvalException e) {
        System.err.println("\n\n\n\n" + CvalChecker.LINE);
        for (String line : e.getMessage().split("\n")) {
            System.err.println(line);
        }
        System.err.println(CvalChecker.LINE + "\n\n\n\n");
        System.exit(1);
        throw new UnableToCompleteException();
    }

    List<ConnectorBundle> bundles = buildBundles(logger, context.getTypeOracle());

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.setSuperclass(requestedType);

    SourceWriter w = composer.createSourceWriter(context, printWriter);

    w.println("public void init() {");
    w.indent();

    for (ConnectorBundle bundle : bundles) {
        detectBadProperties(bundle, logger);

        String name = bundle.getName();
        boolean isEager = name.equals(ConnectorBundleLoader.EAGER_BUNDLE_NAME);

        w.print("addAsyncBlockLoader(new AsyncBundleLoader(\"");
        w.print(escape(name));
        w.print("\", ");

        w.print("new String[] {");
        for (Entry<JClassType, Set<String>> entry : bundle.getIdentifiers().entrySet()) {
            Set<String> identifiers = entry.getValue();
            for (String id : identifiers) {
                w.print("\"");
                w.print(escape(id));
                w.print("\",");
            }
        }
        w.println("}) {");
        w.indent();

        w.print("protected void load(final ");
        w.print(TypeDataStore.class.getName());
        w.println(" store) {");
        w.indent();

        if (!isEager) {
            w.print(GWT.class.getName());
            w.print(".runAsync(");
        }

        w.println("new %s() {", RunAsyncCallback.class.getName());
        w.indent();

        w.println("public void onSuccess() {");
        w.indent();

        w.println("load();");
        w.println("%s.get().setLoaded(getName());", ConnectorBundleLoader.class.getName());

        // Close onSuccess method
        w.outdent();
        w.println("}");

        w.println("private void load() {");
        w.indent();

        String loadNativeJsBundle = "loadJsBundle";
        printBundleData(logger, w, bundle, loadNativeJsBundle);

        // Close load method
        w.outdent();
        w.println("}");

        // Separate method for loading native JS stuff (e.g. callbacks)
        String loadNativeJsMethodName = "loadNativeJs";
        // To support fields of type long (#13692)
        w.println("@com.google.gwt.core.client.UnsafeNativeLong");
        w.println("private native void %s(%s store) /*-{", loadNativeJsMethodName,
                TypeDataStore.class.getName());
        w.indent();
        List<String> jsMethodNames = printJsBundleData(logger, w, bundle, loadNativeJsMethodName);

        w.outdent();
        w.println("}-*/;");

        // Call all generated native method inside one Java method to avoid
        // refercences inside native methods to each other
        w.println("private void %s(%s store) {", loadNativeJsBundle, TypeDataStore.class.getName());
        w.indent();
        printLoadJsBundleData(w, loadNativeJsBundle, jsMethodNames);
        w.outdent();
        w.println("}");

        // onFailure method declaration starts
        w.println("public void onFailure(Throwable reason) {");
        w.indent();

        w.println("%s.get().setLoadFailure(getName(), reason);", ConnectorBundleLoader.class.getName());

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

        // Close new RunAsyncCallback() {}
        w.outdent();
        w.print("}");

        if (isEager) {
            w.println(".onSuccess();");
        } else {
            w.println(");");
        }

        // Close load method
        w.outdent();
        w.println("}");

        // Close add(new ...
        w.outdent();
        w.println("});");
    }

    if (cvalInfos != null && !cvalInfos.isEmpty()) {
        w.println("{");
        for (CValUiInfo c : cvalInfos) {
            if ("evaluation".equals(c.type)) {
                w.println("cvals.add(new CValUiInfo(\"" + c.product + "\", \"" + c.version + "\", \""
                        + c.widgetset + "\", null));");
            }
        }
        w.println("}");
    }

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

    w.commit(logger);
}

From source file:com.vaadin.server.widgetsetutils.metadata.ArraySerializer.java

License:Apache License

@Override
protected void printDeserializerBody(TreeLogger logger, SourceWriter w, String type, String jsonValue,
        String connection) {//www . j a v  a2s  . co  m
    JType leafType = arrayType.getLeafType();
    int rank = arrayType.getRank();

    w.println(JsonArray.class.getName() + " jsonArray = (" + JsonArray.class.getName() + ")" + jsonValue + ";");

    // Type value = new Type[jsonArray.size()][][];
    w.print(arrayType.getQualifiedSourceName() + " value = new " + leafType.getQualifiedSourceName()
            + "[jsonArray.length()]");
    for (int i = 1; i < rank; i++) {
        w.print("[]");
    }
    w.println(";");

    w.println("for(int i = 0 ; i < value.length; i++) {");
    w.indent();

    JType componentType = arrayType.getComponentType();

    w.print("value[i] = (" + ConnectorBundleLoaderFactory.getBoxedTypeName(componentType) + ") "
            + JsonDecoder.class.getName() + ".decodeValue(");
    ConnectorBundleLoaderFactory.writeTypeCreator(w, componentType);
    w.print(", jsonArray.get(i), null, " + connection + ")");

    w.println(";");

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

    w.println("return value;");
}