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

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

Introduction

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

Prototype

void indent();

Source Link

Usage

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;/*from  w w w .j  a v  a 2  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) {/*from   www  .ja  v a 2 s.  c om*/
    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;");
}

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

License:Apache License

@Override
protected void printSerializerBody(TreeLogger logger, SourceWriter w, String value,
        String applicationConnection) {
    JType componentType = arrayType.getComponentType();

    w.println(JsonArray.class.getName() + " values = " + Json.class.getName() + ".createArray();");
    // JPrimitiveType primitive = componentType.isPrimitive();
    w.println("for (int i = 0; i < " + value + ".length; i++) {");
    w.indent();
    w.print("values.set(i, ");
    w.print(JsonEncoder.class.getName() + ".encode(" + value + "[i],");
    ConnectorBundleLoaderFactory.writeTypeCreator(w, componentType);
    w.print(", " + applicationConnection + ")");
    w.println(");");
    w.outdent();/*from w w w.j  av a  2  s.  c  om*/
    w.println("}");
    w.println("return values;");
}

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

License:Apache License

@Override
protected void printDeserializerBody(TreeLogger logger, SourceWriter w, String type, String jsonValue,
        String connection) {//from w w w.  j  av a2  s  .  c  om
    w.println("String enumIdentifier = " + jsonValue + ".asString();");
    for (JEnumConstant e : enumType.getEnumConstants()) {
        w.println("if (\"" + e.getName() + "\".equals(enumIdentifier)) {");
        w.indent();
        w.println("return " + enumType.getQualifiedSourceName() + "." + e.getName() + ";");
        w.outdent();
        w.println("}");
    }
    w.println("return null;");
}

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

License:Apache License

@Override
public void writeSerializerInstantiator(TreeLogger logger, SourceWriter w) throws UnableToCompleteException {

    w.print("return new ");
    w.print(JSONSerializer.class.getCanonicalName());
    w.print("<");
    w.print(type.getQualifiedSourceName());
    w.println(">() {");
    w.indent();

    writeSerializerBody(logger, w);//from   w  ww .  ja va 2  s. c om

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

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

License:Apache License

protected void writeSerializerBody(TreeLogger logger, SourceWriter w) {
    String qualifiedSourceName = type.getQualifiedSourceName();
    w.println("public " + JsonValue.class.getName() + " serialize(" + qualifiedSourceName + " value, "
            + ApplicationConnection.class.getName() + " connection) {");
    w.indent();
    // MouseEventDetails castedValue = (MouseEventDetails) value;
    w.println(qualifiedSourceName + " castedValue = (" + qualifiedSourceName + ") value;");

    printSerializerBody(logger, w, "castedValue", "connection");

    // End of serializer method
    w.outdent();/*  w  ww.  j  a va2s .  co  m*/
    w.println("}");

    // Deserializer
    // T deserialize(Type type, JSONValue jsonValue, ApplicationConnection
    // connection);
    w.println("public " + qualifiedSourceName + " deserialize(Type type, " + JsonValue.class.getName()
            + " jsonValue, " + ApplicationConnection.class.getName() + " connection) {");
    w.indent();

    printDeserializerBody(logger, w, "type", "jsonValue", "connection");

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

From source file:com.vaadin.terminal.gwt.widgetsetutils.AcceptCriteriaFactoryGenerator.java

License:Open Source License

private void generateInstantiatorMethod(SourceWriter sourceWriter, GeneratorContext context,
        TreeLogger logger) {/* ww  w . j a  va  2s.c om*/

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

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

    Collection<Class<? extends AcceptCriterion>> clientSideVerifiableCriterion = ClassPathExplorer
            .getCriterion();

    for (Class<? extends AcceptCriterion> class1 : clientSideVerifiableCriterion) {
        logger.log(Type.INFO, "creating mapping for " + class1.getCanonicalName());
        String canonicalName = class1.getCanonicalName();
        Class<? extends VAcceptCriterion> clientClass = class1.getAnnotation(ClientCriterion.class).value();
        sourceWriter.print("if (\"");
        sourceWriter.print(canonicalName);
        sourceWriter.print("\" == name) return GWT.create(");
        sourceWriter.print(clientClass.getCanonicalName());
        sourceWriter.println(".class );");
        sourceWriter.print("else ");
    }

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

From source file:com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator.java

License:Open Source License

private void generateInstantiatorMethod(SourceWriter sourceWriter,
        Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation) {

    Collection<Class<?>> deferredWidgets = new LinkedList<Class<?>>();

    // TODO detect if it would be noticably faster to instantiate with a
    // lookup with index than with the hashmap

    sourceWriter.println("public void ensureInstantiator(Class<? extends Paintable> classType) {");
    sourceWriter.println("if(!instmap.containsKey(classType)){");
    boolean first = true;

    ArrayList<Class<? extends Paintable>> lazyLoadedWidgets = new ArrayList<Class<? extends Paintable>>();

    HashSet<Class<? extends com.vaadin.terminal.gwt.client.Paintable>> widgetsWithInstantiator = new HashSet<Class<? extends com.vaadin.terminal.gwt.client.Paintable>>();

    for (Class<? extends Paintable> class1 : paintablesHavingWidgetAnnotation) {
        ClientWidget annotation = class1.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> clientClass = annotation.value();
        if (widgetsWithInstantiator.contains(clientClass)) {
            continue;
        }/*from   www. j a v a2s. co  m*/
        if (clientClass == VView.class) {
            // VView's are not instantiated by widgetset
            continue;
        }
        if (!first) {
            sourceWriter.print(" else ");
        } else {
            first = false;
        }
        sourceWriter.print("if( classType == " + clientClass.getName() + ".class) {");

        String instantiator = "new WidgetInstantiator() {\n public Paintable get() {\n return GWT.create("
                + clientClass.getName() + ".class );\n}\n}\n";

        LoadStyle loadStyle = getLoadStyle(class1);

        if (loadStyle != LoadStyle.EAGER) {
            sourceWriter.print("ApplicationConfiguration.startWidgetLoading();\n" + "GWT.runAsync( \n"
                    + "new WidgetLoader() { void addInstantiator() {instmap.put(" + clientClass.getName()
                    + ".class," + instantiator + ");}});\n");
            lazyLoadedWidgets.add(class1);

            if (loadStyle == LoadStyle.DEFERRED) {
                deferredWidgets.add(class1);
            }

        } else {
            // widget implementation in initially loaded js script
            sourceWriter.print("instmap.put(");
            sourceWriter.print(clientClass.getName());
            sourceWriter.print(".class, ");
            sourceWriter.print(instantiator);
            sourceWriter.print(");");
        }
        sourceWriter.print("}");
        widgetsWithInstantiator.add(clientClass);
    }

    sourceWriter.println("}");

    sourceWriter.println("}");

    sourceWriter.println("public Class<? extends Paintable>[] getDeferredLoadedWidgets() {");

    sourceWriter.println("return new Class[] {");
    first = true;
    for (Class<?> class2 : deferredWidgets) {
        if (!first) {
            sourceWriter.println(",");
        }
        first = false;
        ClientWidget annotation = class2.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> value = annotation.value();
        sourceWriter.print(value.getName() + ".class");
    }

    sourceWriter.println("};");
    sourceWriter.println("}");

    // in constructor add a "thread" that lazyly loads lazy loaded widgets
    // if communication to server idles

    // TODO an array of lazy loaded widgets

    // TODO an index of last ensured widget in array

    sourceWriter.println("public Paintable instantiate(Class<? extends Paintable> classType) {");
    sourceWriter.indent();
    sourceWriter.println("Paintable p = super.instantiate(classType); if(p!= null) return p;");
    sourceWriter.println("return instmap.get(classType).get();");

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

}

From source file:com.vaadin.terminal.gwt.widgetsetutils.WidgetMapGenerator.java

License:Open Source License

/**
 * //from  ww  w.  j av a  2  s  .  c o m
 * @param sourceWriter
 *            Source writer to output source code
 * @param paintablesHavingWidgetAnnotation
 */
private void generateImplementationDetector(SourceWriter sourceWriter,
        Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation) {
    sourceWriter.println("public Class<? extends Paintable> "
            + "getImplementationByServerSideClassName(String fullyQualifiedName) {");
    sourceWriter.indent();
    sourceWriter.println("fullyQualifiedName = fullyQualifiedName.intern();");

    for (Class<? extends Paintable> class1 : paintablesHavingWidgetAnnotation) {
        ClientWidget annotation = class1.getAnnotation(ClientWidget.class);
        Class<? extends com.vaadin.terminal.gwt.client.Paintable> clientClass = annotation.value();
        sourceWriter.print("if ( fullyQualifiedName == \"");
        sourceWriter.print(class1.getName());
        sourceWriter.print("\" ) { ensureInstantiator(" + clientClass.getName() + ".class); return ");
        sourceWriter.print(clientClass.getName());
        sourceWriter.println(".class;}");
        sourceWriter.print("else ");
    }
    sourceWriter.println("return com.vaadin.terminal.gwt.client.ui.VUnknownComponent.class;");
    sourceWriter.outdent();
    sourceWriter.println("}");

}

From source file:com.webrippers.gwt.dom.event.gwt.rebind.binder.DomEventBinderGenerator.java

License:Apache License

private void write_doBindEventHandlers(JClassType target, TypeOracle typeOracle, SourceWriter writer,
        TreeLogger logger) {/*w  w  w  .j  a v  a  2s.  c om*/
    writer.println(
            "protected List<HandlerRegistration> doBindEventHandlers(final %s target, IsWidget isWidget) {",
            target.getQualifiedSourceName());
    writer.indent();
    writer.println("List<HandlerRegistration> registrations = new LinkedList<HandlerRegistration>();");

    for (JMethod method : target.getMethods()) {
        DomEventHandler annotation = method.getAnnotation(DomEventHandler.class);
        if (annotation != null) {
            if (method.getParameters().length != 1)
                break;

            JType paramJType = method.getParameters()[0].getType();
            String paramTypeQualifiedSourceName = paramJType.getQualifiedSourceName();

            JClassType paramJClassType = typeOracle.findType(paramTypeQualifiedSourceName);

            if (!paramJClassType.isAssignableTo(typeOracle.findType(DomEvent.class.getCanonicalName())))
                break;

            JGenericType domEventJGenericType = typeOracle.findType(DomEvent.class.getCanonicalName())
                    .isGenericType();
            JParameterizedType paramJParameterizedType = paramJClassType
                    .asParameterizationOf(domEventJGenericType);

            JClassType handlerJClassType = paramJParameterizedType.getTypeArgs()[0];

            writer.println("registrations.add(isWidget.asWidget().addDomHandler(new "
                    + paramJParameterizedType.getTypeArgs()[0].getParameterizedQualifiedSourceName() + "() {");
            writer.indent();
            writer.println(handlerJClassType.getOverridableMethods()[0].getReadableDeclaration(false, false,
                    false, false, true) + " {");
            writer.indent();
            if (annotation.value().length > 0) {
                writer.println("Element targetElement = Element.as(event.getNativeEvent().getEventTarget());");
                if (annotation.value()[0].startsWith("!")) {
                    writer.println("if (targetElement != target." + annotation.value()[0].substring(1) + ") {");
                } else {
                    writer.println("if (targetElement == target." + annotation.value()[0] + ") {");
                }
                writer.indent();
                writer.println("target." + method.getName() + "(event);");
                writer.outdent();
                writer.println("}");
            } else {
                writer.println("target." + method.getName() + "(event);");
            }
            writer.outdent();
            writer.println("}");
            writer.outdent();
            writer.println("}, " + paramTypeQualifiedSourceName + ".getType()));");
        }
    }

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