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: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.// 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 {
    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;
}

From source file:org.lirazs.gbackbone.generator.ReflectionGenerator.java

License:Apache License

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

    JClassType instantiableType = oracle.findType(Reflectable.class.getName());

    List<JClassType> clazzes = new ArrayList<JClassType>();

    PropertyOracle propertyOracle = context.getPropertyOracle();

    for (JClassType classType : oracle.getTypes()) {
        if (!classType.equals(instantiableType) && classType.isAssignableTo(instantiableType))
            clazzes.add(classType);/*from   w  w w  .j  av a 2 s.com*/
    }

    final String genPackageName = "org.lirazs.gbackbone.client.generator";
    final String genClassName = "ReflectionImpl";

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

    composer.addImport("org.lirazs.gbackbone.client.generator.*");
    composer.addImport("org.lirazs.gbackbone.client.core.data.Options");
    composer.addImport("com.google.gwt.json.client.JSONObject");

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

    if (printWriter != null) {
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("ReflectionImpl( ) {");
        sourceWriter.println("}");

        printFactoryMethod(clazzes, sourceWriter);
        printJSONFactoryMethod(clazzes, sourceWriter);
        printArrayFactoryMethod(clazzes, sourceWriter);

        sourceWriter.commit(logger);
    }

    return composer.getCreatedClassName();
}

From source file:org.metawidget.gwt.generator.widgetprocessor.binding.simple.SimpleBindingProcessorAdapterGenerator.java

License:LGPL

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName) {

    // Lookup the type

    mTypeOracle = context.getTypeOracle();
    JClassType classType;//from   ww  w.  j  a v  a  2 s  .  c o  m

    try {
        classType = mTypeOracle.getType(typeName);
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }

    String packageName = classType.getPackage().getName();
    String sourceClassName = classType.getSimpleSourceName();
    String bindingClassName = sourceClassName + "BindingAdapter";
    PrintWriter printWriter = context.tryCreate(logger, packageName, bindingClassName);

    // Already generated?

    String qualifiedBindingClassName = packageName + StringUtils.SEPARATOR_DOT_CHAR + bindingClassName;

    if (printWriter == null) {
        return qualifiedBindingClassName;
    }

    // Start the BindingAdapter subclass

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, bindingClassName);
    composer.addImplementedInterface(
            SimpleBindingProcessorAdapter.class.getName() + "<" + classType.getQualifiedSourceName() + ">");
    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);

    if (sourceWriter != null) {
        String variableName = VARIABLE_NAME_PREFIX + sourceClassName;
        sourceWriter.println();
        sourceWriter.println("// Public methods");

        // getProperty method

        sourceWriter.println();
        sourceWriter.println("public Object getProperty( " + classType.getQualifiedSourceName() + " "
                + variableName + ", String... names ) {");
        sourceWriter.indent();
        writeMethod(sourceWriter, classType, variableName, WRITE_GETTER);
        sourceWriter.outdent();
        sourceWriter.println("}");

        // getPropertyType method

        sourceWriter.println();
        sourceWriter.println("public Class<?> getPropertyType( " + classType.getQualifiedSourceName() + " "
                + variableName + ", String... names ) {");
        sourceWriter.indent();
        writeMethod(sourceWriter, classType, variableName, WRITE_TYPE_GETTER);
        sourceWriter.outdent();
        sourceWriter.println("}");

        // setProperty method

        sourceWriter.println();
        sourceWriter.println("public void setProperty( " + classType.getQualifiedSourceName() + " "
                + variableName + ", Object value, String... names ) {");
        sourceWriter.indent();
        writeMethod(sourceWriter, classType, variableName, WRITE_SETTER);
        sourceWriter.outdent();
        sourceWriter.println("}");

        // invokeAction method

        sourceWriter.println();
        sourceWriter.println("public void invokeAction( " + classType.getQualifiedSourceName() + " "
                + variableName + ", String... names ) {");
        sourceWriter.indent();
        writeMethod(sourceWriter, classType, variableName, WRITE_ACTION);
        sourceWriter.outdent();
        sourceWriter.println("}");

        // End the BindingAdapter subclass

        sourceWriter.commit(logger);
    }

    return qualifiedBindingClassName;
}

From source file:org.nuxeo.ecm.platform.gwt.rebind.JSourceWriter.java

License:Open Source License

public void commit(TreeLogger logger) {
    for (String imp : imports) {
        composer.addImport(imp);//from  w  ww. jav  a 2 s  .co m
    }
    for (String intfName : interfaces) {
        composer.addImplementedInterface(intfName);
    }
    SourceWriter sw = composer.createSourceWriter(context, printWriter);
    // only to debug
    //        System.out.println("----------------------------------------------");
    //        System.out.println(toString());
    //        System.out.println("----------------------------------------------");
    sw.print(toString());
    sw.commit(logger);
}

From source file:org.parallax3d.parallax.platforms.gwt.generator.PreloaderBundleGenerator.java

License:Apache License

private String createDummyClass(TreeLogger logger, GeneratorContext context) {
    String packageName = "org.parallax3d.parallax.platforms.gwt.preloader";
    String className = "PreloaderBundleImpl";
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.addImplementedInterface(packageName + ".PreloaderBundle");
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);
    if (printWriter == null) {
        return packageName + "." + className;
    }/*from w  w  w .  j  av  a2 s . co m*/
    SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
    sourceWriter.commit(logger);
    return packageName + "." + className;
}

From source file:org.rapla.rest.gwtjsonrpc.rebind.ProxyCreator.java

License:Apache License

String create(final TreeLogger logger, final GeneratorContext context) throws UnableToCompleteException {
    serializerCreator = new SerializerCreator(context);
    deserializerCreator = new ResultDeserializerCreator(context, serializerCreator);
    futureResultClassName = FutureResultImpl.class.getName();
    //final TypeOracle typeOracle = context.getTypeOracle();
    //try {/*from  w  ww.j  a va2s.  co  m*/
    //asyncCallbackClass = typeOracle.getType(AsyncCallback.class.getName());
    //String futureResultInterfaceName = FutureResult.class.getName();
    //futureResultInterface = typeOracle.getType(futureResultInterfaceName);
    //      futureResultClass = typeOracle.getType(futureResultClassName);
    //    } catch (NotFoundException e) {
    //      logger.log(TreeLogger.ERROR, null, e);
    //      throw new UnableToCompleteException();
    //    }
    checkMethods(logger, context);

    final SourceWriter srcWriter = getSourceWriter(logger, context);
    if (srcWriter == null) {
        return getProxyQualifiedName();
    }

    generateProxyConstructor(logger, srcWriter);
    generateProxyCallCreator(logger, srcWriter);
    generateProxyMethods(logger, srcWriter);
    srcWriter.commit(logger);

    return getProxyQualifiedName();
}

From source file:org.rapla.rest.gwtjsonrpc.rebind.ResultDeserializerCreator.java

License:Apache License

void create(TreeLogger logger, JArrayType targetType) {
    this.targetType = targetType;
    this.componentType = targetType.getComponentType();

    if (componentType.isPrimitive() != null || SerializerCreator.isBoxedPrimitive(componentType)) {
        logger.log(TreeLogger.DEBUG, "No need to create array deserializer for primitive array " + targetType);
        return;//from   ww  w  .ja  v  a 2  s. c  o m
    }

    if (deserializerFor(targetType) != null) {
        return;
    }

    logger.log(TreeLogger.DEBUG, "Creating result deserializer for " + targetType.getSimpleSourceName());
    final SourceWriter srcWriter = getSourceWriter(logger, context);
    if (srcWriter == null) {
        return;
    }
    final String dsn = getDeserializerQualifiedName(targetType);
    generatedDeserializers.put(targetType.getQualifiedSourceName(), dsn);

    generateSingleton(srcWriter);
    generateInstanceMembers(srcWriter);
    generateFromResult(srcWriter);

    srcWriter.commit(logger);
}

From source file:org.rapla.rest.gwtjsonrpc.rebind.SerializerCreator.java

License:Apache License

String create(final JClassType targetType, final TreeLogger logger) throws UnableToCompleteException {
    if (targetType.isParameterized() != null || targetType.isArray() != null) {
        ensureSerializersForTypeParameters(logger, targetType);
    }/* w w w  . j  a  v a 2  s.  c  o m*/
    String sClassName = serializerFor(targetType);
    if (sClassName != null) {
        return sClassName;
    }

    checkCanSerialize(logger, targetType, true);
    recursivelyCreateSerializers(logger, targetType);

    this.targetType = targetType;
    final SourceWriter srcWriter = getSourceWriter(logger, context);
    final String sn = getSerializerQualifiedName(targetType);
    if (!generatedSerializers.containsKey(targetType.getQualifiedSourceName())) {
        generatedSerializers.put(targetType.getQualifiedSourceName(), sn);
    }
    if (srcWriter == null) {
        return sn;
    }

    if (!targetType.isAbstract()) {
        generateSingleton(srcWriter);
    }
    if (targetType.isEnum() != null) {
        generateEnumFromJson(srcWriter);
    } else {
        generateInstanceMembers(srcWriter);
        generatePrintJson(srcWriter);
        generateFromJson(srcWriter);
        generateGetSets(srcWriter);
    }

    srcWriter.commit(logger);
    return sn;
}

From source file:org.rstudio.core.rebind.JavaScriptSerializerGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    List<JClassType> classes = new ArrayList<JClassType>();

    // locate all the types annotated with JavaScriptSerializable
    for (JClassType classType : oracle.getTypes()) {
        if (isAnnotatedSerializable(classType))
            classes.add(classType);/* w  w w.j a v a  2 s.c  o m*/
    }

    ClassSourceFileComposerFactory sourceFile = new ClassSourceFileComposerFactory(genPackageName,
            genClassName);
    sourceFile.addImplementedInterface(JavaScriptSerializer.class.getCanonicalName());
    sourceFile.addImport("com.google.gwt.core.client.JavaScriptObject");
    sourceFile.addImport("org.rstudio.core.client.js.JsObject;");

    PrintWriter printWriter = context.tryCreate(logger, genPackageName, genClassName);
    if (printWriter != null) {
        SourceWriter sourceWriter = sourceFile.createSourceWriter(context, printWriter);
        sourceWriter.println(genClassName + "() {");
        sourceWriter.println("}");

        printSerializers(classes, sourceWriter);
        printDeserializers(classes, sourceWriter);

        sourceWriter.commit(logger);
    }
    return sourceFile.getCreatedClassName();
}

From source file:org.senchalabs.gwt.gwtdriver.SeExporterGenerator.java

License:Apache License

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

    JClassType jso = oracle.findType(Name.getSourceNameForClass(JavaScriptObject.class));

    JClassType toGenerate = oracle.findType(typeName).isClass();

    String packageName = toGenerate.getPackage().getName();
    String simpleSourceName = toGenerate.getName().replace('.', '_') + "Impl";
    PrintWriter pw = context.tryCreate(logger, packageName, simpleSourceName);
    if (pw == null) {
        return packageName + "." + simpleSourceName;
    }//  ww  w  .j  a va 2 s  .co m

    ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, simpleSourceName);
    factory.setSuperclass(typeName);
    SourceWriter sw = factory.createSourceWriter(context, pw);

    List<String> exportedTypes;
    try {
        exportedTypes = context.getPropertyOracle().getConfigurationProperty(SELENIUM_METHODS).getValues();
    } catch (BadPropertyValueException e) {
        logger.log(TreeLogger.Type.ERROR,
                "Can't find any config property for " + SELENIUM_METHODS + " declared", e);
        throw new UnableToCompleteException();
    }
    sw.println("protected void exportRegisteredTypes() {");
    sw.indent();
    //for each type set up in a config property,
    for (String exportedType : exportedTypes) {
        JClassType toExport = oracle.findType(exportedType);
        if (toExport == null) {
            logger.log(TreeLogger.Type.ERROR,
                    "Cannot find " + exportedType + " be sure it is a valid GWT type");
            throw new UnableToCompleteException();
        }
        MethodsFor refersToType = toExport.getAnnotation(MethodsFor.class);
        if (refersToType == null) {
            logger.log(Type.ERROR, "Type " + exportedType
                    + " is declared as having webdriver methods, but has no @MethodsFor annotation");
            throw new UnableToCompleteException();
        }
        //verify a default ctor - if not, methods must be static
        boolean requireStatic = toExport.getConstructors().length != 0
                && toExport.findConstructor(new JType[] {}) == null;
        if (requireStatic) {
            logger.log(Type.INFO, "No default constructor found, all marked methods must be static");
        }
        TreeLogger typeLogger = logger.branch(TreeLogger.Type.DEBUG, "Exporting methods in " + exportedType);
        //iterate through the methods
        for (JMethod m : toExport.getInheritableMethods()) {
            Method refersToMethod = m.getAnnotation(Method.class);
            if (refersToMethod == null) {
                continue;
            }
            TreeLogger methodLogger = typeLogger.branch(Type.DEBUG, "Examining " + m.getName());
            if (requireStatic && !m.isStatic()) {
                typeLogger.log(Type.ERROR, "No default constructor found for " + exportedType
                        + ", can't export instance method" + m.getName());
                typeLogger.log(Type.ERROR,
                        "Either mark the method as static, or ensure there is a default constructor.");
                throw new UnableToCompleteException();
            }
            //verify that the method matches exactly one method in the webdriver side
            //TODO make this a little faster
            String matchingMethod = null;
            for (java.lang.reflect.Method exportableMethod : refersToType.value().getMethods()) {
                if (refersToMethod.value().equals(exportableMethod.getName())) {
                    if (matchingMethod != null) {
                        methodLogger.log(Type.ERROR,
                                "Multiple methods found that match " + refersToMethod.value());
                        throw new UnableToCompleteException();
                    }
                    matchingMethod = refersToMethod.value();
                }
            }
            if (matchingMethod == null) {
                methodLogger.log(Type.ERROR, "Can't find a method that matches " + refersToMethod.value());
                throw new UnableToCompleteException();
            }

            //emit a registerFunction call wrapping it
            sw.println("registerFunction(\"%1$s\", \"%2$s\", new %3$s() {",
                    escape(refersToType.value().getName()), escape(matchingMethod),
                    Name.getSourceNameForClass(Function.class));
            sw.indent();
            sw.println("public Object apply(%1$s<?> args) {", Name.getSourceNameForClass(JsArray.class));
            sw.indent();
            JType retType = m.getReturnType();
            if (retType.isPrimitive() != null) {
                switch (retType.isPrimitive()) {
                case VOID:
                    //do nothing
                    break;
                case INT:
                case DOUBLE:
                case BOOLEAN:
                    sw.print("return \"\" + ");
                    break;
                default:
                    methodLogger.log(Type.ERROR, "Can't return primitive " + retType + " from exported method");
                    throw new UnableToCompleteException();
                }
            } else if (retType.isClass() != null && retType.getQualifiedSourceName().equals("java.lang.String")
                    || ((retType.isClass() != null) && retType.isClass().isAssignableTo(jso))
                    || ((retType.isInterface() != null)
                            && oracle.getSingleJsoImplInterfaces().contains(retType))) {
                sw.print("return ");
            } else {
                methodLogger.log(Type.ERROR,
                        "Can't return non-jso, non-supported primitive " + retType + " from exported method");
                throw new UnableToCompleteException();
            }
            if (m.isStatic()) {
                sw.print(exportedType);
            } else {
                sw.print("%1$s.<%2$s>create(%2$s.class)", GWT.class.getName(), exportedType);
            }
            sw.print(".%1$s(", matchingMethod);
            //iterate through the arguments
            //verify the arg type is legal
            JType[] erasedParameterTypes = m.getErasedParameterTypes();
            for (int i = 0; i < erasedParameterTypes.length; i++) {
                JType type = erasedParameterTypes[i];

                if (type.isPrimitive() != null || type.getQualifiedSourceName().equals("java.lang.String")) {
                    //cast uglyness
                    sw.print("args.<%2$s>cast().get(%1$d)", i, getJsArray(type));
                } else if (type.isClass() != null && type.isClass().isAssignableTo(jso)) {
                    //normal array plus cast() trickery
                    sw.print("args.get(%1$d).<%2$s>cast()", i, type.getQualifiedSourceName());
                } else if (type.isInterface() != null
                        && oracle.getSingleJsoImplInterfaces().contains(type.isInterface())) {
                    //single jso cast thing
                    sw.print("args.get(%1$d).<%2$s>cast()", i,
                            oracle.getSingleJsoImpl(type.isInterface()).getQualifiedSourceName());
                } else {//TODO goktug's magic new jsinterface
                    methodLogger.log(Type.ERROR, "Can't handle argument of type " + type);
                    throw new UnableToCompleteException();
                }
                if (i != erasedParameterTypes.length - 1) {
                    sw.println(",");
                }
            }
            sw.println(");");

            if (m.getReturnType() == JPrimitiveType.VOID) {
                sw.println("return null;");
            }

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

    sw.commit(logger);

    return factory.getCreatedClassName();
}