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:org.jboss.errai.workspaces.rebind.ResourceFactoryGenerator.java

License:Apache License

/**
 * Generate source code for new class. Class extends <code>HashMap</code>.
 * /*from w  ww .j a va 2s  .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 = context.tryCreate(logger, packageName, className);
    // print writer if null, source code has ALREADY been generated,

    if (printWriter == null)
        return;

    // init composer, set class properties, create source writer
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);

    composer.addImport("java.util.HashMap");
    composer.addImport("java.util.Map");
    composer.addImport("org.jboss.errai.workspaces.client.api.ResourceFactory");
    composer.addImport("com.google.gwt.core.client.GWT");
    composer.addImport("com.google.gwt.resources.client.ImageResource");

    composer.addImplementedInterface("org.jboss.errai.workspaces.client.api.ResourceFactory");

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

    MetaDataScanner scanner = ScannerSingleton.getOrCreateInstance();

    /**
     * Identify the default bundle (if exists, it's optional)
     */

    Set<Class<?>> bundles = scanner.getTypesAnnotatedWith(DefaultBundle.class);
    for (Class<?> clazz : bundles) {
        bundleClass = clazz.getAnnotation(DefaultBundle.class).value();
    }

    /**
     * Fetch icon mappings from LoadTool annotation This will be used to reference the icon though the ResourceFactory
     */
    Set<Class<?>> tools = scanner.getTypesAnnotatedWith(LoadTool.class);
    for (Class<?> tool : tools) {
        LoadTool lt = tool.getAnnotation(LoadTool.class);
        if (!"".equals(lt.icon()))
            tool2imageRes.put(lt.name(), lt.icon());

    }

    // generator constructor source code
    generateFactoryClass(context, logger, sourceWriter);

    // close generated class
    sourceWriter.outdent();
    sourceWriter.println("}");

    // commit generated class
    context.commit(logger, printWriter);
}

From source file:org.jboss.errai.workspaces.rebind.ResourceFactoryGenerator.java

License:Apache License

private void generateFactoryClass(GeneratorContext context, TreeLogger logger, SourceWriter sourceWriter) {

    sourceWriter.println("private Map<String,ImageResource> mapping = new HashMap<String,ImageResource>();");

    // start constructor source generation
    sourceWriter.println("public " + className + "() { ");
    sourceWriter.indent();//from   ww  w. j  av  a  2s  . c o m
    sourceWriter.println("super();");

    if (bundleClass != null) // optional

    {
        sourceWriter.println(bundleClass.getName() + " bundle = (" + bundleClass.getName() + ") GWT.create("
                + bundleClass.getName() + ".class);");
        for (String tool : tool2imageRes.keySet()) {
            sourceWriter.println("mapping.put(\"" + tool + "\", bundle." + tool2imageRes.get(tool) + "() );");
        }
        sourceWriter.outdent();
    } else {
        logger.log(TreeLogger.Type.WARN,
                "\"@DefaultBundle not found. Make sure the EntryPoint refers to a valid default resource bundle.\"");
    }

    sourceWriter.println("}");

    sourceWriter.println("public ImageResource createImage(String name) { ");
    sourceWriter.outdent();
    sourceWriter.println("    return mapping.get(name);");
    sourceWriter.outdent();
    sourceWriter.println("}");

}

From source file:org.jboss.errai.workspaces.rebind.WorkspaceLoaderBootstrapGenerator.java

License:Apache License

/**
 * Generate source code for new class. Class extends <code>HashMap</code>.
 * /*from  ww w  .j a  v a  2s  . 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 = context.tryCreate(logger, packageName, className);
    // print writer if null, source code has ALREADY been generated,

    if (printWriter == null)
        return;

    // init composer, set class properties, create source writer
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);

    composer.addImplementedInterface("org.jboss.errai.workspaces.client.framework.WorkspaceConfig");

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

    // generator constructor source code
    generateBootstrapClass(context, logger, sourceWriter);
    // close generated class
    sourceWriter.outdent();
    sourceWriter.println("}");

    // commit generated class
    context.commit(logger, printWriter);
}

From source file:org.jboss.errai.workspaces.rebind.WorkspaceLoaderBootstrapGenerator.java

License:Apache License

private void generateBootstrapClass(final GeneratorContext context, final TreeLogger logger,
        final SourceWriter sourceWriter) {
    ResourceBundle bundle;//from w  ww .  j ava  2 s .c om

    try {
        bundle = ResourceBundle.getBundle("org.jboss.errai.workspaces.rebind.WorkspaceModules");
    } catch (Exception e) {
        logger.log(TreeLogger.Type.ERROR, "can't find WorkspaceModules.properties in classpath");
        logger.log(TreeLogger.Type.ERROR, e.getMessage());
        throw new RuntimeException();
    }

    // start constructor source generation
    sourceWriter.println("public " + className + "() { ");
    sourceWriter.indent();
    sourceWriter.println("super();");
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.println(
            "public void configure(org.jboss.errai.workspaces.client.framework.ToolContainer workspace) { ");
    sourceWriter.outdent();

    // toolset profile (acts as whitelist). Used with BPM console atm
    final List<String> enabledTools = new ArrayList<String>();

    InputStream in = getClass().getClassLoader().getResourceAsStream(TOOLSET_PROFILE);

    if (in != null) {
        try {
            BufferedReader input = new BufferedReader(new InputStreamReader(in));
            try {
                String line = null;
                while ((line = input.readLine()) != null) {
                    // ignore comments and empty lines
                    if (line.equals("") || line.startsWith("#"))
                        continue;

                    enabledTools.add(line);
                }
            } finally {
                input.close();
            }
        } catch (IOException ex) {
            throw new RuntimeException("Error reading '" + TOOLSET_PROFILE + "'");
        }
    }

    for (Enumeration<String> keys = bundle.getKeys(); keys.hasMoreElements();) {
        String key = keys.nextElement();

        sourceWriter.println("new " + bundle.getString(key) + "().initModule(errai);");
    }

    final boolean applyFilter = in != null;
    MetaDataScanner scanner = ScannerSingleton.getOrCreateInstance();

    /**
     * LoadToolSet
     */
    Set<Class<?>> toolsets = scanner.getTypesAnnotatedWith(LoadToolSet.class);
    for (Class<?> toolSetClass : toolsets) {
        JClassType clazz = typeOracle.findType(toolSetClass.getName());
        MetaClass metaClass = MetaClassFactory.get(clazz);
        if ((!applyFilter || enabledTools.contains(clazz.getQualifiedSourceName()))) {
            sourceWriter.println(
                    "workspace.addToolSet(" + Stmt.newObject(metaClass).generate(Context.create()) + ");");
            logger.log(TreeLogger.Type.INFO, "Adding Errai Toolset: " + clazz.getQualifiedSourceName());
        }
    }

    /**
     * LoadTool
     */
    Set<Class<?>> tools = scanner.getTypesAnnotatedWith(LoadTool.class);
    for (Class<?> toolClass : tools) {
        JClassType clazz = typeOracle.findType(toolClass.getName());
        MetaClass metaClass = MetaClassFactory.get(clazz);

        if ((!applyFilter || enabledTools.contains(clazz.getQualifiedSourceName()))) {

            LoadTool loadTool = clazz.getAnnotation(LoadTool.class);

            logger.log(TreeLogger.Type.INFO, "Adding Errai Tool: " + clazz.getQualifiedSourceName());

            if (clazz.isAnnotationPresent(RequireRoles.class)) {
                RequireRoles requireRoles = clazz.getAnnotation(RequireRoles.class);

                StringBuilder rolesBuilder = new StringBuilder("new String[] {");
                String[] roles = requireRoles.value();

                for (int i = 0; i < roles.length; i++) {
                    rolesBuilder.append("\"").append(roles[i].trim()).append("\"");
                    if ((i + 1) < roles.length)
                        rolesBuilder.append(", ");
                }
                rolesBuilder.append("}");

                generateWidgetProvisioning(context, clazz.getQualifiedSourceName(), loadTool, rolesBuilder,
                        logger, sourceWriter);
            } else {
                generateWidgetProvisioning(context, clazz.getQualifiedSourceName(), loadTool, null, logger,
                        sourceWriter);

            }
        } else if (clazz.isAnnotationPresent(LoginComponent.class)) {
            sourceWriter.println("workspace.setLoginComponent(new " + clazz.getQualifiedSourceName() + "());");
        }
    }

    /**
     * Group order
     */
    Set<Class<?>> groupOrderClasses = scanner.getTypesAnnotatedWith(GroupOrder.class);
    for (Class<?> clazz : groupOrderClasses) {
        GroupOrder groupOrder = clazz.getAnnotation(GroupOrder.class);

        if ("".equals(groupOrder.value().trim()))
            return;

        String[] order = groupOrder.value().split(",");

        sourceWriter.print("workspace.setPreferredGroupOrdering(new String[] {");

        for (int i = 0; i < order.length; i++) {
            sourceWriter.print("\"");
            sourceWriter.print(order[i].trim());
            sourceWriter.print("\"");

            if (i + 1 < order.length) {
                sourceWriter.print(",");
            }
        }

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

    // wrap up
    sourceWriter.outdent();
    sourceWriter.println("}");
}

From source file:org.jboss.errai.workspaces.rebind.WorkspaceLoaderBootstrapGenerator.java

License:Apache License

public void generateWidgetProvisioning(final GeneratorContext context, String className,
        final LoadTool loadTool, final StringBuilder rolesBuilder, final TreeLogger logger,
        final SourceWriter writer) {
    MetaClass type;/*ww w  .  ja  v a 2s. c om*/
    MetaClass widgetType;
    try {
        type = MetaClassFactory.get(typeOracle.getType(className));
        widgetType = MetaClassFactory.get(typeOracle.getType(Widget.class.getName()));
    } catch (NotFoundException e) {
        throw new RuntimeException("error bootstrapping: " + className, e);
    }

    if (widgetType.isAssignableFrom(type)) {

        writer.println(WidgetProvider.class.getName() + " widgetProvider" + (++counter) + " = new "
                + WidgetProvider.class.getName() + "() {");
        writer.outdent();
        writer.println("public void provideWidget(" + ProvisioningCallback.class.getName() + " callback) {");
        writer.outdent();

        writer.println("callback.onSuccess(" + Stmt.newObject(type).generate(Context.create()) + ");");
        writer.outdent();
        writer.println("}");
        writer.outdent();
        writer.println("};");
    }

    writer.print("workspace.addTool(\"" + loadTool.group() + "\"," + " \"" + loadTool.name() + "\", \""
            + loadTool.icon() + "\", " + loadTool.multipleAllowed() + ", " + loadTool.priority() + ",  "
            + Stmt.newObject(type).generate(Context.create()));

    if (rolesBuilder == null) {
        writer.println(");");
    } else {
        writer.println(", " + rolesBuilder.toString() + ");");
    }
}

From source file:org.jrydberg.bindings.rebind.DataBindingGenerator.java

License:Apache License

public void generateImplClass(TreeLogger logger, GeneratorContext context, JClassType type,
        JClassType beanType) {/*w w  w.  j  av a2 s .  co  m*/
    String superType = "AbstractBinding<ST, " + beanType.getName() + ">";
    String className = type.getName() + "_IMPL";

    PrintWriter printWriter = context.tryCreate(logger, type.getPackage().getName(), className);
    if (printWriter == null) {
        return;
    }

    Set<Binding> bindings = findBindings(type);

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(
            type.getPackage().getName(), className + "<ST>");
    composerFactory.addImport("org.jrydberg.bindings.client.AbstractBinding");
    composerFactory.addImport("org.jrydberg.bindings.client.DataBinding");
    composerFactory.addImport("org.jrydberg.bindings.client.Property");
    composerFactory.addImport(type.getQualifiedSourceName());
    composerFactory.addImport(beanType.getQualifiedSourceName());
    composerFactory.addImport(HasValue.class.getName());
    for (Binding binding : bindings) {
        composerFactory.addImport(binding.type.getQualifiedSourceName());
        if (binding.nested) {
            composerFactory.addImport(binding.type.getQualifiedSourceName() + "_IMPL");
        }
    }

    composerFactory.setSuperclass(superType);
    composerFactory.addImplementedInterface(type.getName());

    SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);

    sourceWriter.println("public " + className + "(HasValue<ST> sourceBox) {");
    sourceWriter.println("  super(sourceBox);");
    sourceWriter.println("}");

    for (Binding binding : bindings) {
        PropertyDescription propDescr = findPropertyDescription(beanType, binding.name);

        if (!binding.nested) {
            // This should return a Property<type>
            sourceWriter.println("@Override");
            sourceWriter.println("public Property<" + binding.type.getName() + "> " + binding.name + "() {");
            sourceWriter.indent();

            sourceWriter.println("return new AbstractBinding<" + beanType.getName() + ","
                    + binding.type.getName() + ">(this) {");
            sourceWriter.indent();

            sourceWriter.println("@Override");
            sourceWriter.println("public String getPropertyName() {");
            sourceWriter.println("  return \"" + binding.name + "\";");
            sourceWriter.println("}");
            writeProperty(sourceWriter, binding.type, beanType, propDescr);
            sourceWriter.outdent();
            sourceWriter.println("};");
            sourceWriter.outdent();
            sourceWriter.println("}");
        } else {
            // This should return a Property<type>
            sourceWriter.println("@Override");
            sourceWriter.println("public " + binding.type.getName() + " " + binding.name + "() {");
            sourceWriter.indent();
            sourceWriter.println(
                    "return new " + binding.type.getName() + "_IMPL<" + beanType.getName() + ">(this) {");
            sourceWriter.indent();
            writeProperty(sourceWriter, binding.parameterType, beanType, propDescr);

            stubBindingMethods(sourceWriter, binding.parameterType.getName());
            // FIXME: do we need to overwrite the root-methods?

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

    }

    stubBindingMethods(sourceWriter, beanType.getName());

    sourceWriter.commit(null);
}

From source file:org.kjots.json.object.gwt.rebind.GwtJsonObjectFactoryGenerator.java

License:Apache License

/**
 * Generate the code for the type with the given name.
 *
 * @param logger The logger.//  w  w w .  j a v  a2 s  .c  o m
 * @param context The context.
 * @param typeName The type name.
 * @return The name of the generated  class.
 * @throws UnableToCompleteException
 */
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle typeOracle = context.getTypeOracle();

    JClassType typeClassType = typeOracle.findType(typeName);
    if (!typeClassType.getQualifiedBinaryName().equals(JsonObjectFactory.class.getName())) {
        logger.log(TreeLogger.ERROR, "This generator only supports " + JsonObjectFactory.class.getName(), null);

        throw new UnableToCompleteException();
    }

    JClassType implBaseClassType = typeOracle.findType(GwtJsonObjectFactoryImplBase.class.getName());

    String implPackage = implBaseClassType.getPackage().getName();
    String implClassName = "GwtJsonObjectFactoryImpl";

    PrintWriter printWriter = context.tryCreate(logger, implPackage, implClassName);
    if (printWriter != null) {
        ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(implPackage,
                implClassName);

        composerFactory.setSuperclass(implBaseClassType.getQualifiedSourceName());

        SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);

        sourceWriter.println("@SuppressWarnings(\"unchecked\")");
        sourceWriter.println("public " + implClassName + "() {");
        sourceWriter.indent();

        for (Map.Entry<String, String> entry : this.getJsonObjectImplClasses(logger, context).entrySet()) {
            this.writeJsonObjectInstantiator(sourceWriter, entry.getKey(), entry.getValue());
        }

        for (String jsonPropertyAdapterTypeName : this.getJsonPropertyAdapterClasses(logger, context)) {
            this.writeJsonPropertyAdapterInstantiator(sourceWriter, jsonPropertyAdapterTypeName);
        }

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

        sourceWriter.commit(logger);
    }

    return implPackage + "." + implClassName;
}

From source file:org.kjots.json.object.gwt.rebind.GwtJsonObjectFactoryGenerator.java

License:Apache License

/**
 * Write an instantiator for the given JSON object and implementation types.
 *
 * @param sourceWriter The source writer.
 * @param jsonObjectTypeName The name of the JSON object type.
 * @param jsonObjectImplTypeName The name of the JSON object implementation type.
 */// w  ww  .  jav a2 s  .c om
private void writeJsonObjectInstantiator(SourceWriter sourceWriter, String jsonObjectTypeName,
        String jsonObjectImplTypeName) {
    sourceWriter.println("this.registerJsonObjectInstantiator(" + jsonObjectTypeName
            + ".class, new JsonObjectInstantiator<" + jsonObjectTypeName + ">() {");
    sourceWriter.indent();
    sourceWriter.println("public final " + jsonObjectTypeName + " newInstance("
            + JavaScriptObject.class.getName() + " jsObject) {");
    sourceWriter.indent();
    sourceWriter
            .println("return new " + jsonObjectImplTypeName + "(" + jsonObjectTypeName + ".class, jsObject);");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.outdent();
    sourceWriter.println("});");
}

From source file:org.kjots.json.object.gwt.rebind.GwtJsonObjectFactoryGenerator.java

License:Apache License

/**
 * Write an instantiator for the given JSON property adapter type.
 *
 * @param sourceWriter The source writer.
 * @param jsonPropertyAdapterTypeName The name of the JSON property adapter type.
 */// www . j a  v a  2s  .  co  m
private void writeJsonPropertyAdapterInstantiator(SourceWriter sourceWriter,
        String jsonPropertyAdapterTypeName) {
    sourceWriter.println("this.registerJsonPropertyAdapterInstantiator(" + jsonPropertyAdapterTypeName
            + ".class, new JsonPropertyAdapterInstantiator<" + jsonPropertyAdapterTypeName + ">() {");
    sourceWriter.indent();
    sourceWriter.println("public final " + jsonPropertyAdapterTypeName + " newInstance() {");
    sourceWriter.indent();
    sourceWriter.println("return new " + jsonPropertyAdapterTypeName + "();");
    sourceWriter.outdent();
    sourceWriter.println("}");
    sourceWriter.outdent();
    sourceWriter.println("});");
}

From source file:org.kjots.json.object.gwt.rebind.GwtJsonObjectGenerator.java

License:Apache License

/**
 * Generate the code for the type with the given name.
 *
 * @param logger The logger./*  ww  w .  ja v a  2  s .c  om*/
 * @param context The context.
 * @param typeName The type name.
 * @return The name of the generated  class.
 * @throws UnableToCompleteException
 */
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    JClassType typeClassType = context.getTypeOracle().findType(typeName);

    JPackage typePackage = typeClassType.getPackage();
    if (typePackage == null) {
        logger.log(TreeLogger.ERROR, typeClassType.getQualifiedSourceName() + " is not in a package", null);

        throw new UnableToCompleteException();
    }

    if (typeClassType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, typeClassType.getQualifiedSourceName() + " is not an interface", null);

        throw new UnableToCompleteException();
    }

    JClassType[] implementedInterfaces = typeClassType.getImplementedInterfaces();
    if (implementedInterfaces == null || implementedInterfaces.length == 0) {
        logger.log(TreeLogger.ERROR,
                typeClassType.getQualifiedSourceName() + " must extend at least one interface", null);

        throw new UnableToCompleteException();
    }

    String superClassImplClassName;

    JClassType mainImplementedInterface = implementedInterfaces[0];
    if (mainImplementedInterface.getQualifiedBinaryName().equals(JsonObject.class.getName())) {
        superClassImplClassName = GwtJsonObjectImpl.class.getName();
    } else {
        superClassImplClassName = new GwtJsonObjectGenerator().generate(logger, context,
                mainImplementedInterface.getQualifiedSourceName());
    }

    String implPackage = typePackage.getName();
    String implClassName = typeClassType.getName().replace('.', '_') + "Impl";

    PrintWriter printWriter = context.tryCreate(logger, implPackage, implClassName);
    if (printWriter != null) {
        ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(implPackage,
                implClassName);

        composerFactory.setSuperclass(superClassImplClassName);
        composerFactory.addImplementedInterface(typeClassType.getParameterizedQualifiedSourceName());

        SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);

        sourceWriter.println("public " + implClassName + "(" + Class.class.getName() + "<? extends "
                + typeClassType.getQualifiedSourceName() + "> jsonObjectClass, "
                + JavaScriptObject.class.getName() + " jsObject) {");
        sourceWriter.indent();
        sourceWriter.println("super(jsonObjectClass, jsObject);");
        sourceWriter.outdent();
        sourceWriter.println("}");

        for (JMethod method : typeClassType.getMethods()) {
            sourceWriter.println();

            if (method.getAnnotation(JsonFunction.class) != null) {
                this.writeFunctionMethod(sourceWriter, logger, context, method,
                        method.getAnnotation(JsonFunction.class));
            } else if (method.getAnnotation(JsonException.class) != null) {
                this.writeExceptionMethod(sourceWriter, logger, context, method,
                        method.getAnnotation(JsonException.class));
            } else if (method.getAnnotation(JsonProperty.class) != null) {
                this.writePropertyMethod(sourceWriter, logger, context, method,
                        method.getAnnotation(JsonProperty.class));
            } else {
                logger.log(TreeLogger.ERROR, method.getName() + "() is not annotated with suitable annotation",
                        null);
            }
        }

        sourceWriter.commit(logger);
    }

    return implPackage + "." + implClassName;
}