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);

Source Link

Usage

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

License:Apache License

@Override
public void writeGetterBody(TreeLogger logger, SourceWriter w, String beanVariable) {
    String value = String.format("%s.@%s::%s()()", beanVariable, getBeanType().getQualifiedSourceName(),
            getter);/*  w ww  .j a  v a2s. c o  m*/
    w.print("return ");
    w.print(boxValue(value));
    w.println(";");
}

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

License:Open Source License

/**
 * Generate source code for WidgetMapImpl
 * /* 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.terminal.gwt.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.terminal.gwt.widgetsetutils.AcceptCriteriaFactoryGenerator.java

License:Open Source License

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

    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

/**
 * Generate source code for WidgetMapImpl
 * /*from  w ww  . j  a  v  a2 s.c om*/
 * @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 Vaadin components in classpath to generate WidgetMapImpl.java ...");
    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.addImport("java.util.HashMap");
    composer.addImport("com.google.gwt.core.client.RunAsyncCallback");
    composer.setSuperclass("com.vaadin.terminal.gwt.client.WidgetMap");
    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

    Collection<Class<? extends Paintable>> paintablesHavingWidgetAnnotation = getUsedPaintables();

    validatePaintables(logger, context, paintablesHavingWidgetAnnotation);

    // generator constructor source code
    generateImplementationDetector(sourceWriter, paintablesHavingWidgetAnnotation);
    generateInstantiatorMethod(sourceWriter, paintablesHavingWidgetAnnotation);
    // 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.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 w  ww.  j ava2  s  .  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

/**
 * //w w w.  jav a  2  s .co 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.villagechief.gwt.hogan.server.HoganGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Build a new class, that implements a "paintScreen" method
    JClassType classType;/*from w  w w. j  a v  a  2s  .com*/

    try {
        String name = typeName + "Generated";
        classType = context.getTypeOracle().getType(typeName);
        SourceWriter src = getSourceWriter(classType, context, logger);
        if (src == null)
            return name;

        // fetch the template;
        // TODO: make this name configurable some how?
        String templateResource = "/" + typeName.replace(".", "/") + ".html";
        InputStream templateStream = getClass().getResourceAsStream(templateResource);
        if (templateStream == null) {
            logger.log(TreeLogger.ERROR, "Template not found: " + templateResource);
            throw new UnableToCompleteException();
        }
        InputStreamReader streamReader = new InputStreamReader(templateStream);
        StringBuilder sb = new StringBuilder();
        char[] cbuf = new char[1024];
        int len;
        while ((len = streamReader.read(cbuf)) >= 0) {
            sb.append(cbuf, 0, len);
        }

        ScriptEngineManager engineMgr = new ScriptEngineManager();
        ScriptEngine engine = engineMgr.getEngineByName("ECMAScript");
        if (engine == null) {
            logger.log(TreeLogger.ERROR, "ECMAScript scripting engine not defined");
            throw new UnableToCompleteException();
        }
        InputStream hoganInputStream = HoganGenerator.class.getResourceAsStream("hogan.js");
        if (hoganInputStream == null) {
            logger.log(TreeLogger.ERROR, "hogan.js is missing");
            throw new UnableToCompleteException();
        }
        Reader hoganReader = new InputStreamReader(hoganInputStream);
        Reader templatesReader = new StringReader("Hogan.compile(data, {asString: true});");

        ScriptContext scriptContext = new SimpleScriptContext();
        Bindings b = scriptContext.getBindings(ScriptContext.ENGINE_SCOPE);
        b.put("data", sb.toString());

        engine.eval(hoganReader, scriptContext);
        String template = (String) engine.eval(templatesReader, scriptContext);

        src.println("@Override");
        src.println("protected void onLoad() {");
        src.println("   JSONObject data = new JSONObject();");
        src.println("   Map<String, Object> params = new HashMap<String, Object>();");
        src.println("   for ( Entry<String, Object> e : getParameters().entrySet() ){");
        src.println("      JSONValue bean = null;");
        src.println("      if ( e.getValue() instanceof JSONValue )");
        src.println("         bean = (JSONValue)e.getValue();");
        src.println("      else if ( e.getValue() instanceof AutoBean<?> )");
        src.println(
                "         bean = (JSONValue)JSONParser.parseStrict(AutoBeanCodex.encode((AutoBean<?>)e.getValue()).getPayload());");
        src.println("      data.put(e.getKey(), bean);");
        src.println("   }");
        src.println("   render(getElement(), data.getJavaScriptObject());");
        src.println("   super.onLoad();");
        src.println("}");
        src.println("");
        src.println("static native void render(Object el, JavaScriptObject params) /*-{");
        src.println("  var t = new $wnd.HoganTemplate();");
        src.println("  t.r = " + template + ";");
        src.println("  el.innerHTML = t.render(params);");
        src.println("}-*/;");

        src.commit(logger);

        System.out.println("Generating for: " + typeName);
        return name;

    } catch (Throwable e) {
        logger.log(TreeLogger.ERROR, e.getMessage());
        e.printStackTrace(System.err);
        throw new UnableToCompleteException();
    }
}

From source file:com.xclinical.mdr.server.gwt.FactoryGenerator.java

License:Apache License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    TypeOracle typeOracle = context.getTypeOracle();

    JClassType clazz = typeOracle.findType(typeName);

    if (clazz == null) {
        logger.log(TreeLogger.ERROR, "The type '" + typeName + "' was not found");
        throw new UnableToCompleteException();
    }/*  w w w  .  j  a  v a 2 s  . c  o  m*/

    logger.log(TreeLogger.DEBUG, "Generating source for " + clazz.getQualifiedSourceName());

    String packageName = clazz.getPackage().getName();
    String simpleName = clazz.getSimpleSourceName() + IMPL_POSTFIX;
    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);

    // If the printWriter is null here, this may indicate the class is already existing.
    // Don't know if it is a good idea to imply WE have generated it though.
    if (printWriter != null) {
        ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
        composer.addImport("java.util.HashMap");
        composer.addImplementedInterface("ObjectFactory");
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

        sourceWriter.println("private static HashMap<String, ObjectCreator> factories;");
        sourceWriter.println("private static HashMap<String, Object> singletons;");
        sourceWriter.println("static {");
        sourceWriter.println("  factories = new HashMap<String, ObjectCreator>();");
        sourceWriter.println("  singletons = new HashMap<String, Object>();");

        // Add an implementation of ObjectCreator for every Instantiable.
        for (JClassType type : typeOracle.getTypes()) {
            Instantiable instantiable;
            if ((instantiable = type.getAnnotation(Instantiable.class)) != null) {
                String targetName = instantiable.value();
                if (targetName.length() == 0)
                    targetName = type.getQualifiedSourceName();
                sourceWriter.println("factories.put(\"" + targetName + "\", new ObjectCreator() {");
                sourceWriter.println("   public Object newInstance() {");
                sourceWriter.println("      return new " + type.getQualifiedSourceName() + "();");
                sourceWriter.println("   }});");

                if (type.getAnnotation(Singleton.class) != null) {
                    sourceWriter.println("singletons.put(\"" + targetName + "\", new "
                            + type.getQualifiedSourceName() + "());");
                }
            }
        }

        // End static {
        sourceWriter.println("}");

        // Add an implementation for ObjectFactory.newInstance(String) that forwards
        // to the mappings.
        sourceWriter.println("public Object newInstance(String className) throws ReflectException {");
        sourceWriter.println("   ObjectCreator c = factories.get(className);");
        sourceWriter.println("  if (c == null) throw new ReflectException(className);");
        sourceWriter.println("  return c.newInstance();");
        sourceWriter.println("}");

        // Add an implementation for ObjectFactory.getInstance(String)
        sourceWriter.println("public Object getInstance(String className) throws ReflectException {");
        sourceWriter.println("   Object obj = singletons.get(className);");
        sourceWriter.println("   if (obj == null) {");
        sourceWriter.println("     ObjectCreator c = factories.get(className);");
        sourceWriter.println("    if (c == null) throw new ReflectException(className);");
        sourceWriter.println("    obj = c.newInstance();");
        sourceWriter.println("    singletons.put(className, obj);");
        sourceWriter.println("  }");
        sourceWriter.println("  return obj;");
        sourceWriter.println("}");

        sourceWriter.commit(logger);

        logger.log(TreeLogger.DEBUG, "Done generating source for " + clazz.getQualifiedSourceName());
    }

    return clazz.getQualifiedSourceName() + IMPL_POSTFIX;
}

From source file:cz.muni.ucn.opsi.wui.gwt.rebind.beanModel.BeanModelGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    oracle = context.getTypeOracle();//from  w  w w .ja va  2  s.c o  m
    beanModelMarkerType = oracle.findType(BeanModelMarker.class.getName());
    beanModelTagType = oracle.findType(BeanModelTag.class.getName());

    try {
        // final all beans and bean markers
        beans = new ArrayList<JClassType>();
        JClassType[] types = oracle.getTypes();
        for (JClassType type : types) {
            if (isBeanMarker(type)) {
                beans.add(getMarkerBean(type));
            } else if (isBean(type)) {
                beans.add(type);
            }
        }

        final String genPackageName = BeanModelLookup.class.getPackage().getName();
        final String genClassName = "BeanModelLookupImpl";

        ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName,
                genClassName);
        composer.setSuperclass(BeanModelLookup.class.getCanonicalName());
        composer.addImport(BeanModelFactory.class.getName());
        composer.addImport(Map.class.getName());
        composer.addImport(FastMap.class.getName());

        PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

        if (pw != null) {
            SourceWriter sw = composer.createSourceWriter(context, pw);

            sw.println("private Map<String, BeanModelFactory> m;");

            sw.println("public BeanModelFactory getFactory(String n) {");
            sw.indent();
            //        sw.println("String n = b.getName();");
            sw.println("if (m == null) {");
            sw.indentln("m = new FastMap<BeanModelFactory>();");
            sw.println("}");
            sw.println("if (m.get(n) == null) {");
            sw.indent();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < beans.size(); i++) {
                JClassType bean = beans.get(i);
                String name = createBean(bean, logger, context);
                String factory = createFactory(bean, name, logger, context);

                if (i > 0) {
                    sw.print(" else ");
                }
                sw.println("if (" + bean.getQualifiedSourceName() + ".CLASS_NAME.equals(n)) {");
                sw.indentln("m" + i + "();");

                sb.append("private void m" + i + "() {\n");
                sb.append(
                        "  m.put(" + bean.getQualifiedSourceName() + ".CLASS_NAME, new " + factory + "());\n");
                sb.append("}\n");

                sw.print("}");
            }
            sw.outdent();
            sw.println("}");
            sw.println("return m.get(n);");
            sw.outdent();
            sw.println("}");

            sw.println(sb.toString());
            sw.commit(logger);
        }

        return composer.getCreatedClassName();

    } catch (Exception e) {
        logger.log(TreeLogger.ERROR, "Class " + typeName + " not found.", e);
        throw new UnableToCompleteException();
    }

}

From source file:cz.muni.ucn.opsi.wui.gwt.rebind.beanModel.BeanModelGenerator.java

License:Open Source License

protected String createFactory(JClassType bean, String beanModelName, TreeLogger logger,
        GeneratorContext context) throws Exception {
    final String genPackageName = BeanModelLookup.class.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_") + "_Factory";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModelFactory.class.getCanonicalName());
    composer.addImport(BeanModelE.class.getCanonicalName());
    composer.addImport(BeanModel.class.getCanonicalName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        SourceWriter sw = composer.createSourceWriter(context, pw);
        sw.println("public BeanModelE newInstance() {");
        sw.println("return new " + beanModelName + "();");
        sw.println("}");
        sw.commit(logger);//from  ww  w.  j a  va2s .c o m
    }
    return composer.getCreatedClassName();
}