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

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

Introduction

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

Prototype

void commit(TreeLogger logger);

Source Link

Usage

From source file:com.sencha.gxt.state.rebind.StateManagerGenerator.java

License:sencha.com license

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

    JClassType type = oracle.findType(typeName);
    JClassType stateMangerType = oracle.findType(Name.getSourceNameForClass(StateManager.class));
    if (type == null || type.isClass() == null || !type.isAssignableTo(stateMangerType)) {
        logger.log(Type.ERROR, "This generator only can function on StateManager subtypes");
        throw new UnableToCompleteException();
    }//from  w w  w.ja  v a2  s. co m

    String abf;
    try {
        abf = context.getPropertyOracle().getConfigurationProperty(STATE_MANAGER_ABF).getValues().get(0);
    } catch (BadPropertyValueException ex) {
        logger.log(Type.ERROR, "Could not read property for " + STATE_MANAGER_ABF, ex);
        throw new UnableToCompleteException();
    }

    JClassType abfType = oracle.findType(abf);
    if (abfType == null) {
        logger.log(Type.ERROR, "Cannot find type " + abf + " in gwt classpath");
        throw new UnableToCompleteException();
    }

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

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(typeName);
    factory.addImport(Name.getSourceNameForClass(GWT.class));

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

    sw.println("public %1$s getStateBeanFactory() {", abf);
    sw.indentln("return GWT.create(%1$s.class);", abf);
    sw.println("}");

    sw.commit(logger);

    return factory.getCreatedClassName();
}

From source file:com.smartgwt.rebind.AnnotationMetaBeanFactoryGenerator.java

License:Open Source License

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

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "AnnotationMetaFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.AnnotationMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter/*from   w  ww.  jav a  2s  . co m*/
                .println("// This class lovingly generated by " + this.getClass().getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();

        Set<JClassType> typesGenerated = new HashSet<JClassType>();

        // Collect the types ...
        for (JClassType classType : oracle.getTypes()) {
            BeanFactory.Generate annotation = classType.getAnnotation(BeanFactory.Generate.class);

            if (annotation != null) {
                TreeLogger annotationLogger = logger.branch(TreeLogger.DEBUG,
                        "Processing @BeanFactory.Generate annotation on " + classType.getQualifiedSourceName());

                Class[] value = annotation.value();
                if (value.length == 0) {
                    // No value supplied, so we use the class the annotation was applied to
                    if (!typesGenerated.contains(classType)) {
                        typesGenerated.add(classType);
                        generateFactory(classType, annotationLogger, context, sourceWriter);
                    }
                } else {
                    // Some values were supplied, so we use them, and not the class itself
                    for (Class klass : value) {
                        JClassType klassValue = oracle.findType(klass.getCanonicalName());
                        if (klassValue == null) {
                            annotationLogger.log(TreeLogger.ERROR,
                                    "Could not find " + klass.getName() + " in source classpath.");
                            throw new UnableToCompleteException();
                        } else {
                            if (!typesGenerated.contains(klassValue)) {
                                typesGenerated.add(klassValue);
                                generateFactory(klassValue, annotationLogger, context, sourceWriter);
                            }
                        }
                    }
                }
            }
        }

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

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.BeanValueType.java

License:Open Source License

public String generateFactory(TreeLogger logger, GeneratorContext context) {
    final String packageName = getFactoryPackage();
    final String factoryName = getSimpleFactoryName();
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, factoryName);

    composer.addImport(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName());
    composer.addImport(com.google.gwt.core.client.JavaScriptObject.class.getCanonicalName());

    // Import our valueType, but without the [] designation
    composer.addImport(getQualifiedTypeName().replace("[]", ""));

    composer.addImport(beanValueType.getQualifiedSourceName());
    composer.setSuperclass(beanValueType.getSimpleSourceName() + "<" + getSimpleGenericName() + ">");

    PrintWriter printWriter = context.tryCreate(logger, packageName, factoryName);
    if (printWriter != null) {
        SourceWriter source = composer.createSourceWriter(context, printWriter);

        source.println("// This class lovingly generated by com.smartgwt.rebind.BeanValueType\n");
        source.println("public static void registerValueType () {");

        source.indent();/*from   w w w  . j  a  va2s .  c om*/
        source.println("// We check first to see if it's already registered, to avoid\n"
                + "// constructing the singleton over and over again. This will\n"
                + "// be called multiple times as various BeanFactories initialize\n" + "// themselves.");
        source.println("if (BeanValueType.getBeanValueType(" + getSimpleValueTypeLiteral() + ") == null) {");

        source.indent();
        source.println("BeanValueType.registerBeanValueType(new " + getSimpleFactoryName() + "());");

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

        source.outdent();
        source.println("}\n");

        source.println("@Override public Class<" + getSimpleTypeName() + "> getValueType () {");
        source.indent();
        source.println("return " + getSimpleTypeName() + ".class;");
        source.outdent();
        source.println("}\n");

        source.println("@Override public boolean isAssignableFrom (Object value) {");
        source.indent();
        source.println("return value == null || value instanceof " + getSimpleTypeName() + ";");
        source.outdent();
        source.println("}");

        if (componentType != null) {
            source.println("\nprivate " + getSimpleTypeName() + " emptyArray = new "
                    + componentType.getSimpleSourceName() + "[0];");
            source.println("\n@Override public " + getSimpleTypeName() + " emptyArray () {");
            source.indent();
            source.println("return emptyArray;");
            source.outdent();
            source.println("}");
        }

        if (scClassName != null) {
            source.println("\n@Override public String getScClassName () {");
            source.indent();
            source.println("return \"" + scClassName + "\";");
            source.outdent();
            source.println("}");
        }

        // Try to write a newInstance function that takes a JavaScriptObject
        if (isAbstract) {
            // If the type is abstract, our only hope is if it has a static getOrCreateRef method
            if (hasGetOrCreateRef) {
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return " + getSimpleTypeName() + ".getOrCreateRef(jsObject);");
                source.outdent();
                source.println("}");
            }
        } else {
            if (jsObjConstructor != null) {
                // If it has the right kind of constructor, then use that
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return new " + getSimpleTypeName() + "(jsObject);");
                source.outdent();
                source.println("}");
            } else if (hasSetJavaScriptObject) {
                // Custom subclasses likely won't have the constructor, but may have a a setJavaScriptObject method
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println(getSimpleTypeName() + " value = new " + getSimpleTypeName() + "();");
                source.println("value.setJavaScriptObject(jsObject);");
                source.println("return value;");
                source.outdent();
                source.println("}");
            } else if (hasGetOrCreateRef) {
                // And may as well fall back to getOrCreateRef if it exists
                source.println("\n@Override public " + getSimpleTypeName()
                        + " newInstance (JavaScriptObject jsObject) {");
                source.indent();
                source.println("return " + getSimpleTypeName() + ".getOrCreateRef(jsObject);");
                source.outdent();
                source.println("}");
            }
        }

        source.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.BeanValueTypeFactoryGenerator.java

License:Open Source License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType metaFactoryType = typeOracle.findType(typeName);

    final String genPackageName = metaFactoryType.getPackage().getName();
    final String genClassName = metaFactoryType.getSimpleSourceName() + "Impl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(typeName);
    composer.addImport(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName());
    composer.addImport("com.smartgwt.client.bean.types.*");

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + BeanValueTypeFactoryGenerator.class.getCanonicalName() + "\n");

        StringBuilder functions = new StringBuilder();

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();/*from   w w  w  .ja  va 2 s .c o m*/

        JClassType beanValueTypeClass = typeOracle
                .findType(com.smartgwt.client.bean.BeanValueType.class.getCanonicalName()).isClass();

        // Iterate over the methods defined on the interface
        for (JMethod method : metaFactoryType.getMethods()) {
            if (method.getParameters().length != 0) {
                logger.log(Type.ERROR, typeName + "::" + method.getName() + " should have no parameters.");
                throw new UnableToCompleteException();
            }

            JParameterizedType returnType = method.getReturnType().isParameterized();
            if (returnType == null) {
                logger.log(Type.ERROR,
                        typeName + "::" + method.getName() + " has a non-parameterized return type.");
                throw new UnableToCompleteException();
            }

            if (returnType.getBaseType() != beanValueTypeClass) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " does not have BeanValueType<> as its return type.");
                throw new UnableToCompleteException();
            }

            JClassType[] typeArgs = returnType.getTypeArgs();
            if (typeArgs.length != 1) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " should have a return type with one parameterized type.");
                throw new UnableToCompleteException();
            }

            BeanValueType beanValueType = new BeanValueType(typeArgs[0], typeOracle);

            // Write the function to register the value type. Note that a side-effect
            // is that the factory for the value type is actually generated!
            beanValueType.writeRegisterValueType(sourceWriter, logger, context);

            // And we'll need to generate the function!
            functions.append("\n\n@Override public BeanValueType<" + beanValueType.getQualifiedTypeName() + "> "
                    + method.getName() + "() {\n  " + "return (BeanValueType<"
                    + beanValueType.getQualifiedTypeName() + ">) BeanValueType.getBeanValueType("
                    + beanValueType.getQualifiedValueTypeLiteral() + ");\n}");
        }

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

        sourceWriter.println(functions.toString());
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.CanvasMetaBeanFactoryGenerator.java

License:Open Source License

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

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "CanvasMetaBeanFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.CanvasMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + CanvasMetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();/*  w w w  . ja  v  a2 s .c  o  m*/

        for (JClassType classType : oracle.getTypes()) {
            if (classType.isAssignableTo(canvasType) && isEligibleForGeneration(classType)) {
                BeanClass beanClass = new BeanClass(classType);
                beanClass.generateFactory(logger, context);

                // We have to instantiate the factory to register it in the BeanFactory static API
                sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");
            }
        }

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

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.FormItemMetaBeanFactoryGenerator.java

License:Open Source License

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

    final String genPackageName = "com.smartgwt.client.bean";
    final String genClassName = "FormItemMetaBeanFactoryImpl";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(BeanFactory.FormItemMetaFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + FormItemMetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();//from  ww  w. j a v a2s.  c om

        for (JClassType classType : oracle.getTypes()) {
            if (classType.isAssignableTo(formItemType) && isEligibleForGeneration(classType)) {
                BeanClass beanClass = new BeanClass(classType);
                beanClass.generateFactory(logger, context);

                // We have to instantiate the factory to register it in the BeanFactory static API
                sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");
            }
        }

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

    return composer.getCreatedClassName();
}

From source file:com.smartgwt.rebind.MetaBeanFactoryGenerator.java

License:Open Source License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType metaFactoryType = typeOracle.findType(typeName);

    final String genPackageName = getFactoryPackage(metaFactoryType);
    final String genClassName = getSimpleFactoryName(metaFactoryType);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.addImplementedInterface(typeName);
    composer.addImport(com.smartgwt.client.bean.BeanFactory.class.getCanonicalName());

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("// This class lovingly generated by "
                + MetaBeanFactoryGenerator.class.getCanonicalName() + "\n");

        StringBuilder functions = new StringBuilder();

        // Our constructor ... will be called by GWT.create()
        sourceWriter.println(genClassName + " () {");
        sourceWriter.indent();// www .j  ava  2  s . c o m

        JClassType beanFactoryType = typeOracle.findType(BeanFactory.class.getCanonicalName()).isClass();
        JClassType baseWidgetType = typeOracle.findType(BaseWidget.class.getCanonicalName()).isClass();
        JClassType dataClassType = typeOracle.findType(DataClass.class.getCanonicalName()).isClass();

        // Iterate over the methods defined on the interface
        for (JMethod method : metaFactoryType.getMethods()) {
            if (method.getParameters().length != 0) {
                logger.log(Type.ERROR, typeName + "::" + method.getName() + " should have no parameters.");
                throw new UnableToCompleteException();
            }

            JParameterizedType returnType = method.getReturnType().isParameterized();
            if (returnType == null) {
                logger.log(Type.ERROR,
                        typeName + "::" + method.getName() + " has a non-parameterized return type.");
                throw new UnableToCompleteException();
            }

            if (returnType.getBaseType() != beanFactoryType) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " does not have BeanFactory<> as its return type.");
                throw new UnableToCompleteException();
            }

            JClassType[] typeArgs = returnType.getTypeArgs();
            if (typeArgs.length != 1) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + " should have a return type with one parameterized type.");
                throw new UnableToCompleteException();
            }

            JClassType beanClassType = typeArgs[0];
            if (!baseWidgetType.isAssignableFrom(beanClassType)
                    && !dataClassType.isAssignableFrom(beanClassType)) {
                logger.log(Type.ERROR, typeName + "::" + method.getName()
                        + ": for now, factories can only be created for Canvas or DataClass and subclasses.");
                throw new UnableToCompleteException();
            }

            BeanClass beanClass = new BeanClass(beanClassType);
            beanClass.generateFactory(logger, context);

            // We have to instantiate the factory to register it in the BeanFactory static API
            sourceWriter.println(beanClass.getQualifiedFactoryName() + ".create(false);");

            // And we'll need to generate the function!
            functions.append("\n\n@Override public BeanFactory<" + beanClassType.getQualifiedSourceName() + "> "
                    + method.getName() + "() {\n  " + "return (BeanFactory<"
                    + beanClassType.getQualifiedSourceName() + ">) BeanFactory.getFactory("
                    + beanClassType.getQualifiedSourceName() + ".class);\n}");
        }

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

        sourceWriter.println(functions.toString());
        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

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.ja  v a2s .  com*/
    }

    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.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 ww w .j  av  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.webrippers.gwt.dom.event.gwt.rebind.binder.DomEventBinderGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    try {/*from   www . ja v  a 2  s.  co m*/
        TypeOracle typeOracle = context.getTypeOracle();
        JClassType eventBinderType = typeOracle.getType(typeName);
        JClassType targetType = getTargetType(eventBinderType, typeOracle);

        SourceWriter writer = createSourceWriter(logger, context, eventBinderType, targetType);
        if (writer != null) {

            write_doBindEventHandlers(targetType, typeOracle, writer, logger);

            writer.commit(logger);
        }
        return getFullyQualifiedGeneratedClassName(eventBinderType);
    } catch (NotFoundException e) {
        logger.log(Type.ERROR, "Error generating " + typeName, e);
        throw new UnableToCompleteException();
    }
}