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:de.knightsoftnet.validators.rebind.GwtReflectGetterGenerator.java

License:Apache License

@Override
public final String generate(final TreeLogger plogger, final GeneratorContext pcontext, final String ptypeName)
        throws UnableToCompleteException {
    try {//from  ww  w. j a v  a  2s .co  m
        plogger.log(TreeLogger.DEBUG, "Start generating for " + ptypeName + ".");

        final JClassType classType = pcontext.getTypeOracle().getType(ptypeName);
        final TypeOracle typeOracle = pcontext.getTypeOracle();
        assert typeOracle != null;
        final JClassType reflectorType = this.findType(plogger, typeOracle, ptypeName);

        // here you would retrieve the metadata based on typeName for this class
        final SourceWriter src = this.getSourceWriter(classType, pcontext, plogger);

        // generator is called more then once in a build, with second call, we don't get
        // a writer and needn't generate the class once again
        if (src != null) {
            final Class<?>[] classes = this.getBeans(plogger, reflectorType);

            src.println("@Override");
            src.println("public final Object getProperty(final Object pbean, final String pname)"
                    + " throws NoSuchMethodException, ReflectiveOperationException {");

            src.println("  if (pbean == null) {");
            src.println("    throw new NoSuchMethodException(\"A null object has no getters\");");
            src.println("  }");
            src.println("  if (pname == null) {");
            src.println("    throw new NoSuchMethodException(\"No method to get property for null\");");
            src.println("  }");
            src.println(StringUtils.EMPTY);

            for (final Class<?> clazz : classes) {
                final String className = clazz.getName();
                plogger.log(TreeLogger.DEBUG, "Generating getter reflections for class " + className);

                // Describe the bean properties
                final PropertyDescriptor[] properties = PropertyUtils.getPropertyDescriptors(clazz);

                src.println("  if (pbean.getClass() == " + className + ".class) {");
                src.println("    switch (pname) {");

                // for all getters generate a case and return entry
                for (final PropertyDescriptor property : properties) {

                    final Method readMethod = property.getReadMethod();
                    final String name = property.getName();
                    if (readMethod == null) {
                        continue; // If the property cannot be read
                    }
                    plogger.log(TreeLogger.DEBUG, "Add getter for property " + name);

                    // Invoke the getter on the bean
                    src.println("      case \"" + name + "\":");
                    src.println("        return ((" + className + ") pbean)." + readMethod.getName() + "();");
                }

                src.println("      default:");
                src.println("        throw new NoSuchMethodException(\"Class " + className
                        + " has no getter for porperty \" + pname);");
                src.println("    }");
                src.println("  }");
            }
            src.println("  throw new ReflectiveOperationException(\"Class \" + "
                    + "pbean.getClass().getName() + \" is not reflected\");");
            src.println("}");

            plogger.log(TreeLogger.DEBUG, "End of generating reached");

            src.commit(plogger);
        }
        return this.getClassPackage(classType) + "." + this.getClassName(classType);
    } catch (final NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:de.swm.commons.mobile.generator.OsDetectionGenerator.java

License:Apache License

/**
 * {@inheritDoc}//from  w  w  w  .jav a2  s . c  o m
 */
@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {

    // get the property oracle
    PropertyOracle propertyOracle = context.getPropertyOracle();
    SelectionProperty property = null;
    try {
        // get mgwt.os variable
        property = propertyOracle.getSelectionProperty(logger, "swmmmobile.os");
    } catch (BadPropertyValueException e) {
        // if we can`t find it die
        logger.log(TreeLogger.ERROR, "can not resolve mgwt.os variable", e);
        throw new UnableToCompleteException();
    }

    JClassType classType = null;

    try {
        // get the type we are looking for
        classType = context.getTypeOracle().getType(typeName);
    } catch (NotFoundException e) {
        // if we can`t get it die
        logger.log(TreeLogger.ERROR, "can not find type: '" + typeName + "'", e);
        throw new UnableToCompleteException();
    }

    // get value of mmobile.os
    String mmobileProperty = property.getCurrentValue();
    // get the package name
    String packageName = classType.getPackage().getName();
    // build name for implementation class
    String simpleName = classType.getSimpleSourceName() + "_" + property.getCurrentValue();
    // combine package name and simple name to full qualified
    String fullName = packageName + "." + simpleName;

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
    composer.addImplementedInterface(typeName);
    composer.addImport(typeName);

    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);

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

    // start writing the implementation
    SourceWriter writer = composer.createSourceWriter(context, printWriter);

    writer.println("public boolean isAndroid() {");
    writer.println("return isAndroidTablet() || isAndroidPhone();");
    writer.println("}");

    writer.println("public boolean isIPhone() {");
    writer.println(
            "return " + mmobileProperty.equals("iphone") + " || " + mmobileProperty.equals("retina") + ";");
    writer.println("}");

    writer.println("public boolean isIPad() {");
    writer.println("return " + mmobileProperty.equals("ipad") + ";");
    writer.println("}");

    writer.println("public boolean isIOs() {");
    writer.println("return isIPhone() || isIPad();");
    writer.println("}");

    writer.println("public boolean isDesktop() {");
    writer.println("return " + mmobileProperty.equals("desktop") + ";");
    writer.println("}");

    writer.println("public boolean isBlackBerry() {");
    writer.println("return " + mmobileProperty.equals("blackberry") + ";");
    writer.println("}");

    writer.println("public boolean isTablet() {");
    writer.println("return isDesktop() || isIPad() || isAndroidTablet();");
    writer.println("}");

    writer.println("public boolean isPhone() {");
    writer.println("return isIPhone() || isAndroidPhone() || isBlackBerry();");
    writer.println("}");

    writer.println("public boolean isAndroidTablet() {");
    writer.println("return " + mmobileProperty.equals("android_tablet") + ";");
    writer.println("}");

    writer.println("public boolean isAndroidPhone() {");
    writer.println("return " + mmobileProperty.equals("android") + ";");
    writer.println("}");

    writer.println("public boolean isRetina() {");
    writer.println("return " + mmobileProperty.equals("retina") + ";");
    writer.println("}");

    writer.commit(logger);

    return fullName;

}

From source file:eml.studio.client.ui.binding.TextBinderGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String requestedClass)
        throws UnableToCompleteException {

    TypeOracle typeOracle = context.getTypeOracle();

    JClassType objectType = typeOracle.findType(requestedClass);
    if (objectType == null) {
        logger.log(TreeLogger.ERROR, "Could not find type: " + requestedClass);
        throw new UnableToCompleteException();
    }//from   ww w  .j a  v  a 2  s.  c o m

    implTypeName = objectType.getSimpleSourceName() + "Impl";

    implPackageName = objectType.getPackage().getName();

    JClassType[] implementedTypes = objectType.getImplementedInterfaces();

    // Can only implement one interface
    if (implementedTypes == null || implementedTypes.length != 1
            || !implementedTypes[0].getQualifiedSourceName().equals(TextBinder.class.getName())) {
        logger.log(TreeLogger.ERROR, "The type: " + requestedClass + " Must implement only one interface: "
                + TextBinder.class.getName());
        throw new UnableToCompleteException();
    }

    // Get parameterized type
    JParameterizedType parameterType = implementedTypes[0].isParameterized();
    if (parameterType == null) {
        logger.log(TreeLogger.ERROR, "The type: " + requestedClass
                + " Must implement only one parameterized interface: " + TextBinder.class.getName());
        throw new UnableToCompleteException();
    }

    if (parameterType.getTypeArgs() == null

            || parameterType.getTypeArgs().length != 2) {
        logger.log(TreeLogger.ERROR,
                "The type: " + requestedClass + " Must implement two parameterized interface: "
                        + TextBinder.class.getName() + " with two Parameter");
        throw new UnableToCompleteException();

    }

    parameterizedType1 = parameterType.getTypeArgs()[0];
    parameterizedType2 = parameterType.getTypeArgs()[1];
    // logger.log(TreeLogger.INFO ,
    // parameterizedType2.getParameterizedQualifiedSourceName() +"\n"
    // + parameterizedType2.getQualifiedSourceName());

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(implPackageName,
            implTypeName);

    composerFactory.addImport(Map.class.getCanonicalName());
    composerFactory.addImport(List.class.getCanonicalName());
    // composerFactory.addImport(Field.class.getCanonicalName());
    composerFactory.addImplementedInterface(objectType.getQualifiedSourceName());

    PrintWriter printWriter = context.tryCreate(logger, implPackageName, implTypeName);
    if (printWriter != null) {

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

        composeBindMethod(logger, sourceWriter);
        composeSyncMethod(logger, sourceWriter);
        sourceWriter.commit(logger);

    }
    return implPackageName + "." + implTypeName;
}

From source file:fi.jasoft.draganddrop.configurations.DragAndDropConfigurationManagerGenerator.java

License:Apache License

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

    TypeOracle typeOracle = context.getTypeOracle();
    JClassType functionType = typeOracle.findType(typeName);
    assert DragAndDropConfigurationManager.class.equals(functionType.getClass());

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(IMPL_PACKAGE_NAME,
            IMPL_TYPE_NAME);// w  w w. j  a v  a  2  s .  c  om

    composerFactory.addImport(DragAndDropConfigurationManager.class.getCanonicalName());
    composerFactory.addImplementedInterface(DragAndDropConfigurationManager.class.getName());

    composerFactory.addImport(Map.class.getCanonicalName());
    composerFactory.addImport(HashMap.class.getCanonicalName());
    composerFactory.addImport(AbstractDragAndDropConfiguration.class.getCanonicalName());
    composerFactory.addImport(ComponentConnector.class.getCanonicalName());

    // Get all connectors and configurations
    List<JClassType> connectors = new ArrayList<JClassType>();
    List<JClassType> configurations = new ArrayList<JClassType>();
    for (JClassType type : typeOracle.getTypes()) {
        if (type.getAnnotation(Connect.class) != null) {
            connectors.add(type);
        }
        if (type.getAnnotation(DragAndDropConfiguration.class) != null) {
            configurations.add(type);
        }
    }

    // Map connector to configuration
    Map<JClassType, JClassType> connectorToConfigurationMap = new HashMap<JClassType, JClassType>();
    for (JClassType connectorType : connectors) {
        Connect connect = connectorType.getAnnotation(Connect.class);
        for (JClassType confType : configurations) {
            DragAndDropConfiguration conf = confType.getAnnotation(DragAndDropConfiguration.class);
            Class<?> dropHandler = conf.value();
            DragAndDropHandler ddHandler = dropHandler.getAnnotation(DragAndDropHandler.class);
            if (connect.value() == ddHandler.value()) {
                connectorToConfigurationMap.put(connectorType, confType);
                composerFactory.addImport(confType.getQualifiedSourceName());
            }
        }
    }

    PrintWriter printWriter = context.tryCreate(logger, IMPL_PACKAGE_NAME, IMPL_TYPE_NAME);

    if (printWriter != null) {
        SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);

        sourceWriter.println("@Override");
        sourceWriter.println(
                "public Map<String, AbstractDragAndDropConfiguration<? extends ComponentConnector>> getConfigurations(){");
        sourceWriter.indent();
        sourceWriter.println(
                "Map<String, AbstractDragAndDropConfiguration<? extends ComponentConnector>> configurations = new HashMap<String, AbstractDragAndDropConfiguration<? extends ComponentConnector>>();");

        for (Entry<JClassType, JClassType> e : connectorToConfigurationMap.entrySet()) {
            sourceWriter.println("configurations.put(\"" + e.getKey().getQualifiedSourceName() + "\", new "
                    + e.getValue().getSimpleSourceName() + "());");
        }

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

        sourceWriter.commit(logger);
    }

    return IMPL_PACKAGE_NAME + "." + IMPL_TYPE_NAME;
}

From source file:forplay.rebind.AutoClientBundleGenerator.java

License:Apache License

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

    JClassType userType;//from  w ww  .j a  va  2  s .c  o m
    try {
        userType = typeOracle.getType(typeName);
    } catch (NotFoundException e) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type: " + typeName, e);
        throw new UnableToCompleteException();
    }
    String packageName = userType.getPackage().getName();
    String className = userType.getName();
    className = className.replace('.', '_');

    if (userType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, userType.getQualifiedSourceName() + " is not an interface", null);
        throw new UnableToCompleteException();
    }

    ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
            className + "Impl");
    composerFactory.addImplementedInterface(userType.getQualifiedSourceName());

    composerFactory.addImport(ClientBundleWithLookup.class.getName());
    composerFactory.addImport(DataResource.class.getName());
    composerFactory.addImport(GWT.class.getName());
    composerFactory.addImport(ImageResource.class.getName());
    composerFactory.addImport(ResourcePrototype.class.getName());
    composerFactory.addImport(TextResource.class.getName());

    File warDirectory = getWarDirectory(logger);
    Asserts.check(warDirectory.isDirectory());

    File classesDirectory = new File(warDirectory, WEB_INF_CLASSES);
    Asserts.check(classesDirectory.isDirectory());

    File resourcesDirectory = new File(classesDirectory, packageName.replace('.', '/'));
    Asserts.check(resourcesDirectory.isDirectory());

    String baseClassesPath = classesDirectory.getPath();
    logger.log(TreeLogger.DEBUG, "baseClassesPath: " + baseClassesPath);

    Set<File> files = preferMp3(getFiles(resourcesDirectory, fileFilter));
    Set<String> methodNames = new HashSet<String>();

    PrintWriter pw = context.tryCreate(logger, packageName, className + "Impl");
    if (pw != null) {
        SourceWriter sw = composerFactory.createSourceWriter(context, pw);

        // write out jump methods

        sw.println("public ResourcePrototype[] getResources() {");
        sw.indent();
        sw.println("return MyBundle.INSTANCE.getResources();");
        sw.outdent();
        sw.println("}");

        sw.println("public ResourcePrototype getResource(String name) {");
        sw.indent();
        sw.println("return MyBundle.INSTANCE.getResource(name);");
        sw.outdent();
        sw.println("}");

        // write out static ClientBundle interface

        sw.println("static interface MyBundle extends ClientBundleWithLookup {");
        sw.indent();
        sw.println("MyBundle INSTANCE = GWT.create(MyBundle.class);");

        for (File file : files) {
            String filepath = file.getPath();
            String relativePath = filepath.replace(baseClassesPath, "").replace('\\', '/').replaceFirst("^/",
                    "");
            String filename = file.getName();
            String contentType = getContentType(logger, file);
            String methodName = stripExtension(filename);

            if (!isValidMethodName(methodName)) {
                logger.log(TreeLogger.WARN,
                        "Skipping invalid method name (" + methodName + ") due to: " + relativePath);
                continue;
            }
            if (!methodNames.add(methodName)) {
                logger.log(TreeLogger.WARN, "Skipping duplicate method name due to: " + relativePath);
                continue;
            }

            logger.log(TreeLogger.DEBUG, "Generating method for: " + relativePath);

            Class<? extends ResourcePrototype> returnType = getResourcePrototype(contentType);

            // generate method
            sw.println();

            if (returnType == DataResource.class) {
                if (contentType.startsWith("audio/")) {
                    // Prevent the use of data URLs, which Flash won't play
                    sw.println("@DataResource.DoNotEmbed");
                } else {
                    // Specify an explicit MIME type, for use in the data URL
                    sw.println("@DataResource.MimeType(\"" + contentType + "\")");
                }
            }

            sw.println("@Source(\"" + relativePath + "\")");

            sw.println(returnType.getName() + " " + methodName + "();");
        }

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

        sw.commit(logger);
    }
    return composerFactory.getCreatedClassName();
}

From source file:fr.putnami.pwt.core.inject.rebind.base.AbstractInjectorCreator.java

License:Open Source License

public String create(TreeLogger logger, GeneratorContext context) {
    PrintWriter writer = context.tryCreate(logger, this.packageName, this.proxyName);
    if (writer == null) {
        return this.proxyQualifiedName;
    }/*from  w  w w  .  j a  v  a2  s .  com*/

    SourceWriter srcWriter = this.getSourceWriter(writer, context);
    srcWriter.indent();

    this.doCreate(logger, context, srcWriter);

    srcWriter.outdent();
    srcWriter.commit(logger);

    return this.proxyQualifiedName;
}

From source file:fr.putnami.pwt.core.model.rebind.ModelCreator.java

License:Open Source License

public String create(TreeLogger logger, GeneratorContext context) {
    PrintWriter printWriter = this.getPrintWriter(logger, context, this.proxyModelQualifiedName);
    if (printWriter == null) {
        return this.proxyModelQualifiedName;
    }// w  ww. jav  a  2  s.  co  m

    JField[] fields = this.beanType.getFields();
    JMethod[] methods = this.beanType.getMethods();

    this.parentType = this.beanType.getSuperclass();
    this.imports.add(this.parentType);

    this.listPublicFields(fields);
    this.listGetters(methods);
    this.listSetters(methods);

    this.createSubModels(logger, context);

    SourceWriter srcWriter = this.getSourceWriter(printWriter, context);

    srcWriter.indent();
    srcWriter.println();
    this.generateSingleton(logger, srcWriter);
    srcWriter.println();
    srcWriter.println();
    this.generateStaticInitializer(logger, srcWriter);
    srcWriter.println();
    this.generateConstructor(logger, srcWriter);
    srcWriter.println();
    this.generateCreate(logger, srcWriter);
    srcWriter.println();
    this.generateInternalSet(logger, srcWriter);
    srcWriter.println();
    this.generateInternalGet(logger, srcWriter);

    srcWriter.outdent();

    srcWriter.commit(logger);
    return this.proxyModelQualifiedName;
}

From source file:fr.putnami.pwt.core.mvp.rebind.ProxyViewCreator.java

License:Open Source License

public String create(TreeLogger logger, GeneratorContext context) {
    PrintWriter printWriter = context.tryCreate(logger, this.packageName, this.viewProxySimpleName);
    if (printWriter == null) {
        return this.viewProxyQualifiedName;
    }//from  w  w w .  java2s  .c  om

    SourceWriter srcWriter = this.getSourceWriter(printWriter, context);

    srcWriter.indent();
    this.generateProxy(logger, srcWriter);
    srcWriter.println();
    this.generateTokenPrefixes(logger, srcWriter);
    srcWriter.println();
    if (this.placeTokenizerClass == null) {
        this.generateInternalTokenizer(logger, srcWriter);
    } else {
        this.generateDelegateTokenizer(logger, srcWriter);
    }
    this.generateActivityFactory(logger, srcWriter);
    srcWriter.outdent();

    srcWriter.commit(logger);
    return this.viewProxyQualifiedName;
}

From source file:fr.putnami.pwt.core.service.rebind.ServiceBinderCreator.java

License:Open Source License

public String create(TreeLogger logger, GeneratorContext context)
        throws UnableToCompleteException, NotFoundException {
    PrintWriter printWriter = this.getPrintWriter(logger, context);
    if (printWriter == null) {
        return this.proxyModelQualifiedName;
    }//  w  ww.  j a v a  2 s  .co m

    this.serializerTypeName = this.createSerializer(logger, context);
    this.collectImports();

    SourceWriter srcWriter = this.getSourceWriter(printWriter, context);

    srcWriter.indent();
    srcWriter.println();
    this.generateSerializer(srcWriter);
    srcWriter.println();
    this.generateServiceImplementation(logger, srcWriter);
    this.generateServiceImplementationWithCallback(logger, srcWriter);

    srcWriter.outdent();
    srcWriter.commit(logger);
    return this.proxyModelQualifiedName;
}

From source file:fr.putnami.pwt.core.widget.rebind.UiBinderLocalizedCreator.java

License:Open Source License

public String create(TreeLogger logger, GeneratorContext context) {
    Resource templateResource = this.getTemplateResource(context);
    if (templateResource == null) {
        throw new NullPointerException("no template found");
    }/*from  w ww .j  a  v  a2 s .  c  o  m*/
    this.binderProxySimpleName = this.targetType.getSimpleSourceName() + "_"
            + this.binderType.getSimpleSourceName() + UiBinderLocalizedCreator.PROXY_SUFFIX;
    if (this.locale != null) {
        this.binderProxySimpleName += "_" + this.locale.toString();
    }
    this.binderProxyQualifiedName = this.targetType.getPackage().getName() + "." + this.binderProxySimpleName;

    PrintWriter printWriter = this.getPrintWriter(logger, context, this.binderProxyQualifiedName);
    if (printWriter == null) {
        return this.binderProxyQualifiedName;
    }

    SourceWriter srcWriter = this.getSourceWriter(printWriter, context);

    srcWriter.println();
    srcWriter.indent();
    this.generateProxy(logger, srcWriter);
    srcWriter.println();
    srcWriter.outdent();

    srcWriter.commit(logger);

    return this.binderProxyQualifiedName;
}