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:net.sf.mmm.util.nls.impl.rebind.NlsBundleGeneratorGwtI18n.java

License:Apache License

/**
 * This method generates the GWT-i18n-interface for the NLS-bundle.
 *
 * @param bundleClass is the {@link JClassType class} of the {@link net.sf.mmm.util.nls.api.NlsBundle} to
 *        generate./*from www  . j av  a  2 s  . c  om*/
 * @param logger is the {@link TreeLogger}.
 * @param context is the {@link GeneratorContext}.
 * @return the name of the generated class.
 */
@SuppressWarnings({ "rawtypes" })
private String generateBundleInterface(JClassType bundleClass, TreeLogger logger, GeneratorContext context) {

    Class bundleJavaClass;
    String bundleName = bundleClass.getQualifiedSourceName();
    try {
        bundleJavaClass = Class.forName(bundleName);
    } catch (ClassNotFoundException e) {
        throw new TypeNotFoundException(bundleName);
    }
    @SuppressWarnings("unchecked")
    ClassName bundleClassName = NlsBundleHelper.getInstance().getQualifiedLocation(bundleJavaClass);
    String packageName = bundleClassName.getPackageName();
    String simpleName = bundleClassName.getSimpleName();
    if (bundleClassName.getName().equals(bundleName)) {
        logger.log(TreeLogger.ERROR, getClass().getSimpleName() + ": Illegal NlsBundle '" + bundleName
                + "' - has to end with suffix 'Root'. Localization will not work!");
        simpleName = simpleName + "_Interface";
    }
    logger.log(TreeLogger.INFO, getClass().getSimpleName() + ": Generating " + simpleName);
    ClassSourceFileComposerFactory sourceComposerFactory = new ClassSourceFileComposerFactory(packageName,
            simpleName);
    sourceComposerFactory.makeInterface();
    // import statements
    sourceComposerFactory.addImport(Constants.class.getName());
    sourceComposerFactory.addImport(Generate.class.getCanonicalName());

    sourceComposerFactory.addImplementedInterface(Constants.class.getSimpleName());

    // @Generate annotation
    StringBuilder annotationBuffer = new StringBuilder();
    annotationBuffer.append("@");
    annotationBuffer.append(Generate.class.getSimpleName());
    annotationBuffer.append("(format = \"");
    annotationBuffer.append(PropertiesFormat.class.getName());
    annotationBuffer.append("\")");

    sourceComposerFactory.addAnnotationDeclaration(annotationBuffer.toString());

    PrintWriter writer = context.tryCreate(logger, packageName, simpleName);
    if (writer != null) {
        SourceWriter sourceWriter = sourceComposerFactory.createSourceWriter(context, writer);

        // generate methods for fields of bundle
        for (JMethod method : bundleClass.getOverridableMethods()) {
            JType returnType = method.getReturnType();
            if (!isLookupMethod(method)) {
                if (!NlsMessage.class.getName().equals(returnType.getQualifiedSourceName())) {
                    throw new IllegalCaseException(returnType.getQualifiedSourceName());
                }
                NlsBundleMessage messageAnnotation = method.getAnnotation(NlsBundleMessage.class);
                if (messageAnnotation != null) {
                    String message = messageAnnotation.value();
                    // generate message annotation
                    sourceWriter.print("@DefaultStringValue(\"");
                    sourceWriter.print(escape(message));
                    sourceWriter.println("\")");
                }

                NlsBundleKey keyAnnotation = method.getAnnotation(NlsBundleKey.class);
                if (keyAnnotation != null) {
                    // generate key annotation
                    sourceWriter.print("@Key(\"");
                    sourceWriter.print(escape(keyAnnotation.value()));
                    sourceWriter.println("\")");
                }
                // generate method
                sourceWriter.print("String ");
                sourceWriter.print(method.getName());
                sourceWriter.println("();");

                sourceWriter.println();
            }

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

From source file:net.zschech.gwt.comet.rebind.CometSerializerGenerator.java

License:Apache License

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

    TypeOracle typeOracle = context.getTypeOracle();

    // Create the CometSerializer impl
    String packageName = "comet";
    String className = typeName.replace('.', '_') + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    if (printWriter != null) {

        try {//from   ww w .j av  a 2s.  c om
            JClassType type = typeOracle.getType(typeName);
            SerialTypes annotation = type.getAnnotation(SerialTypes.class);
            if (annotation == null) {
                logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
                throw new UnableToCompleteException();
            }

            SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger,
                    context.getPropertyOracle(), context);
            SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(
                    logger, context.getPropertyOracle(), context);

            for (Class<? extends Serializable> serializable : annotation.value()) {
                int rank = 0;
                if (serializable.isArray()) {
                    while (serializable.isArray()) {
                        serializable = (Class<? extends Serializable>) serializable.getComponentType();
                        rank++;
                    }
                }

                JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
                while (rank > 0) {
                    resolvedType = typeOracle.getArrayType(resolvedType);
                    rank--;
                }

                typesSentToBrowserBuilder.addRootType(logger, resolvedType);
            }

            OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
            writer.write("====================================\n");
            writer.write("Types potentially sent from browser:\n");
            writer.write("====================================\n\n");
            writer.flush();

            typesSentToBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);

            writer.write("===================================\n");
            writer.write("Types potentially sent from server:\n");
            writer.write("===================================\n\n");
            writer.flush();
            typesSentFromBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);

            writer.close();

            if (pathInfo != null) {
                context.commitResource(logger, pathInfo).setPrivate(true);
            }

            // Create the serializer
            String modifiedTypeName = typeName.replace('.', '_') + "Serializer";
            TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser,
                    typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
            String realize = tsc.realize(logger);

            // Create the CometSerializer impl
            ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
                    className);

            composerFactory.addImport(Serializer.class.getName());
            composerFactory.addImport(SerialMode.class.getName());

            composerFactory.setSuperclass(typeName);
            // TODO is the SERIALIZER required for DE RPC?
            SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
            sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
            sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
            sourceWriter
                    .print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
            sourceWriter.commit(logger);

            if (annotation.mode() == SerialMode.DE_RPC) {
                RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
                for (JType t : typesSentToBrowser.getSerializableTypes()) {
                    if (!(t instanceof JClassType)) {
                        continue;
                    }
                    JField[] serializableFields = SerializationUtils
                            .getSerializableFields(context.getTypeOracle(), (JClassType) t);

                    List<String> names = Lists.create();
                    for (int i = 0, j = serializableFields.length; i < j; i++) {
                        names = Lists.add(names, serializableFields[i].getName());
                    }

                    data.setFields(SerializationUtils.getRpcTypeName(t), names);
                }

                context.commitArtifact(logger, data);
            }
        } catch (NotFoundException e) {
            logger.log(TreeLogger.ERROR, "", e);
            throw new UnableToCompleteException();
        }
    }

    return new RebindResult(RebindMode.USE_PARTIAL_CACHED, packageName + '.' + className);
}

From source file:org.atmosphere.extensions.gwtwrapper.rebind.SerializerGenerator.java

License:Apache License

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

    TypeOracle typeOracle = context.getTypeOracle();

    // Create the CometSerializer impl
    String packageName = "comet";
    String className = typeName.replace('.', '_') + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    if (printWriter != null) {

        try {//from  w  w  w  .ja  v  a  2 s  .  c  o  m
            JClassType type = typeOracle.getType(typeName);
            GwtSerialTypes annotation = type.getAnnotation(GwtSerialTypes.class);
            if (annotation == null) {
                logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
                throw new UnableToCompleteException();
            }

            SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger,
                    context.getPropertyOracle(), context);
            SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(
                    logger, context.getPropertyOracle(), context);

            List<Class<?>> serializableTypes = new ArrayList();
            Collections.addAll(serializableTypes, annotation.value());
            for (Class<?> serializable : serializableTypes) {
                int rank = 0;
                if (serializable.isArray()) {
                    while (serializable.isArray()) {
                        serializable = (Class<?>) serializable.getComponentType();
                        rank++;
                    }
                }

                JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
                while (rank > 0) {
                    resolvedType = typeOracle.getArrayType(resolvedType);
                    rank--;
                }

                typesSentToBrowserBuilder.addRootType(logger, resolvedType);
                typesSentFromBrowserBuilder.addRootType(logger, resolvedType);
            }

            // Create a resource file to receive all of the serialization information
            // computed by STOB and mark it as private so it does not end up in the
            // output.
            OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
            writer.write("====================================\n");
            writer.write("Types potentially sent from server:\n");
            writer.write("====================================\n\n");
            writer.flush();

            typesSentToBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);

            writer.write("===================================\n");
            writer.write("Types potentially sent from browser:\n");
            writer.write("===================================\n\n");
            writer.flush();
            typesSentFromBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);

            writer.close();

            if (pathInfo != null) {
                context.commitResource(logger, pathInfo).setPrivate(true);
            }

            // Create the serializer
            final String modifiedTypeName = typeName.replace('.', '_');
            TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser,
                    typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
            String realize = tsc.realize(logger);

            // Create the CometSerializer impl
            ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
                    className);

            composerFactory.addImport(Serializer.class.getName());
            composerFactory.addImport(SerializationException.class.getName());
            composerFactory.addImport(Serializable.class.getName());

            composerFactory.setSuperclass(typeName);
            // TODO is the SERIALIZER required for DE RPC?
            SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
            sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
            sourceWriter.print("protected Serializer getRPCSerializer() {return SERIALIZER;}");
            sourceWriter.commit(logger);

        } catch (NotFoundException e) {
            logger.log(TreeLogger.ERROR, "", e);
            throw new UnableToCompleteException();
        }
    }

    return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, packageName + '.' + className);
}

From source file:org.atmosphere.gwt.rebind.SerializerGenerator.java

License:Apache License

@Override
public RebindResult generateIncrementally(TreeLogger logger, GeneratorContextExt context, String typeName)
        throws UnableToCompleteException {

    TypeOracle typeOracle = context.getTypeOracle();

    // Create the CometSerializer impl
    String packageName = "comet";
    String className = typeName.replace('.', '_') + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    if (printWriter != null) {

        try {/*w w w.j  av  a 2  s . co m*/
            JClassType type = typeOracle.getType(typeName);
            SerialTypes annotation = type.getAnnotation(SerialTypes.class);
            if (annotation == null) {
                logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
                throw new UnableToCompleteException();
            }

            SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger,
                    context.getPropertyOracle(), context);
            SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(
                    logger, context.getPropertyOracle(), context);

            for (Class<? extends Serializable> serializable : annotation.value()) {
                int rank = 0;
                if (serializable.isArray()) {
                    while (serializable.isArray()) {
                        serializable = (Class<? extends Serializable>) serializable.getComponentType();
                        rank++;
                    }
                }

                JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
                while (rank > 0) {
                    resolvedType = typeOracle.getArrayType(resolvedType);
                    rank--;
                }

                typesSentToBrowserBuilder.addRootType(logger, resolvedType);
                typesSentFromBrowserBuilder.addRootType(logger, resolvedType);
            }

            // Create a resource file to receive all of the serialization information
            // computed by STOB and mark it as private so it does not end up in the
            // output.
            OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
            writer.write("====================================\n");
            writer.write("Types potentially sent from server:\n");
            writer.write("====================================\n\n");
            writer.flush();

            typesSentToBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);

            writer.write("===================================\n");
            writer.write("Types potentially sent from browser:\n");
            writer.write("===================================\n\n");
            writer.flush();
            typesSentFromBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);

            writer.close();

            if (pathInfo != null) {
                context.commitResource(logger, pathInfo).setPrivate(true);
            }

            // Create the serializer
            final String modifiedTypeName = typeName.replace('.', '_');
            TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser,
                    typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
            String realize = tsc.realize(logger);

            // Create the CometSerializer impl
            ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
                    className);

            composerFactory.addImport(Serializer.class.getName());
            composerFactory.addImport(SerialMode.class.getName());

            composerFactory.setSuperclass(typeName);
            // TODO is the SERIALIZER required for DE RPC?
            SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
            sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
            sourceWriter.print("protected Serializer getSerializer() {return SERIALIZER;}");
            sourceWriter
                    .print("public SerialMode getMode() {return SerialMode." + annotation.mode().name() + ";}");
            sourceWriter.print("public SerialMode getPushMode() {return SerialMode."
                    + annotation.pushmode().name() + ";}");
            sourceWriter.commit(logger);

            if (annotation.mode() == SerialMode.DE_RPC) {
                RpcDataArtifact data = new RpcDataArtifact(type.getQualifiedSourceName());
                for (JType t : typesSentToBrowser.getSerializableTypes()) {
                    if (!(t instanceof JClassType)) {
                        continue;
                    }
                    JField[] serializableFields = SerializationUtils
                            .getSerializableFields(context.getTypeOracle(), (JClassType) t);

                    List<String> names = Lists.create();
                    for (int i = 0, j = serializableFields.length; i < j; i++) {
                        names = Lists.add(names, serializableFields[i].getName());
                    }

                    data.setFields(SerializationUtils.getRpcTypeName(t), names);
                }

                context.commitArtifact(logger, data);
            }
        } catch (NotFoundException e) {
            logger.log(TreeLogger.ERROR, "", e);
            throw new UnableToCompleteException();
        }
    }

    return new RebindResult(RebindStatus.USE_PARTIAL_CACHED, packageName + '.' + className);
}

From source file:org.atmosphere.gwt20.rebind.SerializerGenerator.java

License:Apache License

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

    TypeOracle typeOracle = context.getTypeOracle();

    // Create the CometSerializer impl
    String packageName = "comet";
    String className = typeName.replace('.', '_') + "Impl";
    PrintWriter printWriter = context.tryCreate(logger, packageName, className);

    if (printWriter != null) {

        try {/*w  w w  . j a v a 2  s.co  m*/
            JClassType type = typeOracle.getType(typeName);
            GwtRpcSerialTypes annotation = type.getAnnotation(GwtRpcSerialTypes.class);
            if (annotation == null) {
                logger.log(TreeLogger.ERROR, "No SerialTypes annotation on CometSerializer type: " + typeName);
                throw new UnableToCompleteException();
            }

            SerializableTypeOracleBuilder typesSentToBrowserBuilder = new SerializableTypeOracleBuilder(logger,
                    context.getPropertyOracle(), context);
            SerializableTypeOracleBuilder typesSentFromBrowserBuilder = new SerializableTypeOracleBuilder(
                    logger, context.getPropertyOracle(), context);

            List<Class<?>> serializableTypes = new ArrayList();
            Collections.addAll(serializableTypes, annotation.value());
            for (Class<?> serializable : serializableTypes) {
                int rank = 0;
                if (serializable.isArray()) {
                    while (serializable.isArray()) {
                        serializable = (Class<?>) serializable.getComponentType();
                        rank++;
                    }
                }

                JType resolvedType = typeOracle.getType(serializable.getCanonicalName());
                while (rank > 0) {
                    resolvedType = typeOracle.getArrayType(resolvedType);
                    rank--;
                }

                typesSentToBrowserBuilder.addRootType(logger, resolvedType);
                typesSentFromBrowserBuilder.addRootType(logger, resolvedType);
            }

            // Create a resource file to receive all of the serialization information
            // computed by STOB and mark it as private so it does not end up in the
            // output.
            OutputStream pathInfo = context.tryCreateResource(logger, typeName + ".rpc.log");
            PrintWriter writer = new PrintWriter(new OutputStreamWriter(pathInfo));
            writer.write("====================================\n");
            writer.write("Types potentially sent from server:\n");
            writer.write("====================================\n\n");
            writer.flush();

            typesSentToBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentToBrowser = typesSentToBrowserBuilder.build(logger);

            writer.write("===================================\n");
            writer.write("Types potentially sent from browser:\n");
            writer.write("===================================\n\n");
            writer.flush();
            typesSentFromBrowserBuilder.setLogOutputWriter(writer);
            SerializableTypeOracle typesSentFromBrowser = typesSentFromBrowserBuilder.build(logger);

            writer.close();

            if (pathInfo != null) {
                context.commitResource(logger, pathInfo).setPrivate(true);
            }

            // Create the serializer
            final String modifiedTypeName = typeName.replace('.', '_');
            TypeSerializerCreator tsc = new TypeSerializerCreator(logger, typesSentFromBrowser,
                    typesSentToBrowser, context, "comet." + modifiedTypeName, modifiedTypeName);
            String realize = tsc.realize(logger);

            // Create the CometSerializer impl
            ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(packageName,
                    className);

            composerFactory.addImport(Serializer.class.getName());
            composerFactory.addImport(SerializationException.class.getName());
            composerFactory.addImport(Serializable.class.getName());

            composerFactory.setSuperclass(typeName);
            SourceWriter sourceWriter = composerFactory.createSourceWriter(context, printWriter);
            sourceWriter.print("private Serializer SERIALIZER = new " + realize + "();");
            sourceWriter.print("protected Serializer getRPCSerializer() {return SERIALIZER;}");
            sourceWriter.commit(logger);

        } catch (NotFoundException e) {
            logger.log(TreeLogger.ERROR, "", e);
            throw new UnableToCompleteException();
        }
    }

    return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, packageName + '.' + className);
}

From source file:org.broadleafcommerce.openadmin.generator.FactoryGenerator.java

License:Apache License

public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    logger.log(TreeLogger.INFO, "Generating source for " + typeName, null);
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType clazz = typeOracle.findType(typeName);
    if (clazz == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }/*w  w  w  .  j av  a  2 s  .  c o  m*/
    try {
        logger.log(TreeLogger.INFO, "Generating source for " + clazz.getQualifiedSourceName(), null);
        JClassType[] reflectableTypes = { typeOracle.getType(INSTANTIABLE_TYPE) };
        JClassType[] validatorTypes = { typeOracle.getType(VALIDATOR_TYPE) };
        SourceWriter sourceWriter = getSourceWriter(clazz, context, logger);
        if (sourceWriter != null) {
            sourceWriter.println("public java.lang.Object newInstance(String className) {");
            for (JClassType validatorType : validatorTypes) {
                JClassType[] types = typeOracle.getTypes();
                int count = 0;
                for (int i = 0; i < types.length; i++) {
                    if (types[i].isInterface() == null && !types[i].isAbstract()
                            && types[i].isAssignableTo(validatorType)) {
                        logger.log(TreeLogger.INFO,
                                "Emitting instantiation code for: " + types[i].getQualifiedSourceName(), null);
                        if (count == 0) {
                            sourceWriter.println(
                                    "   if(\"" + types[i].getQualifiedSourceName() + "\".equals(className)) {"
                                            + " return new " + types[i].getQualifiedSourceName() + "();" + "}");
                        } else {
                            sourceWriter.println("   else if(\"" + types[i].getQualifiedSourceName()
                                    + "\".equals(className)) {" + " return new "
                                    + types[i].getQualifiedSourceName() + "();" + "}");
                        }
                        count++;
                    }
                }
            }
            sourceWriter.println("return null;");
            sourceWriter.println("}");
            sourceWriter.println(
                    "public void createAsync(final String className, final AsyncClient asyncClient) {");
            for (JClassType reflectableType : reflectableTypes) {
                JClassType[] types = typeOracle.getTypes();
                int count = 0;
                for (int i = 0; i < types.length; i++) {
                    if (types[i].isInterface() == null && !types[i].isAbstract()
                            && types[i].isAssignableTo(reflectableType)) {
                        logger.log(TreeLogger.INFO,
                                "Emitting async instantiation code for: " + types[i].getQualifiedSourceName(),
                                null);
                        if (count == 0) {
                            sourceWriter.println("   if(\"" + types[i].getQualifiedSourceName()
                                    + "\".equals(className)) {"
                                    + "com.google.gwt.core.client.GWT.runAsync(new com.google.gwt.core.client.RunAsyncCallback() {"
                                    + "public void onFailure(Throwable err) {" + "asyncClient.onUnavailable();"
                                    + "}" + "public void onSuccess() {" + "asyncClient.onSuccess(new "
                                    + types[i].getQualifiedSourceName() + "());" + "}});}");
                        } else {
                            sourceWriter.println("   else if(\"" + types[i].getQualifiedSourceName()
                                    + "\".equals(className)) {"
                                    + "com.google.gwt.core.client.GWT.runAsync(new com.google.gwt.core.client.RunAsyncCallback() {"
                                    + "public void onFailure(Throwable err) {" + "asyncClient.onUnavailable();"
                                    + "}" + "public void onSuccess() {" + "asyncClient.onSuccess(new "
                                    + types[i].getQualifiedSourceName() + "());" + "}});}");
                        }
                        count++;
                    }
                }
            }
            sourceWriter.println("}");
            sourceWriter.commit(logger);
            logger.log(TreeLogger.INFO, "Done Generating source for " + clazz.getName(), null);
        }
        return clazz.getQualifiedSourceName() + "Wrapper";
    } catch (NotFoundException e) {
        e.printStackTrace();
        throw new UnableToCompleteException();
    }
}

From source file:org.broadleafcommerce.openadmin.generator.i18nConstantsGenerator.java

License:Apache License

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

    JClassType clazz = typeOracle.findType(typeName);
    if (clazz == null) {
        logger.log(TreeLogger.ERROR, "Unable to find metadata for type '" + typeName + "'", null);
        throw new UnableToCompleteException();
    }//from  ww  w  .  jav a  2s.  c  om
    try {
        Map<String, String> generatedClasses = generateDynamicConstantClasses(clazz, logger, context);
        logger.log(TreeLogger.INFO, "Generating source for " + clazz.getQualifiedSourceName(), null);

        String packageName = clazz.getPackage().getName();
        String simpleName = clazz.getName() + "Wrapper";
        SourceWriter sourceWriter = getSourceWriter(packageName, simpleName, context, logger,
                new String[] { "org.broadleafcommerce.openadmin.client.i18nConstants" });
        if (sourceWriter != null) {
            sourceWriter.println(
                    "private java.util.List<String> supportedLocales = new java.util.ArrayList<String>();");
            sourceWriter.println("public " + simpleName + "() {");
            for (Map.Entry<String, String> entry : generatedClasses.entrySet()) {
                sourceWriter.print("supportedLocales.add(\"");
                sourceWriter.print(entry.getKey());
                sourceWriter.print("\");\n");
            }
            sourceWriter.println("}");
            sourceWriter.println("");
            sourceWriter.println(
                    "public void retrievei18nProperties(final org.broadleafcommerce.openadmin.client.i18nPropertiesClient i18nClient) {");
            sourceWriter.println(
                    "com.google.gwt.i18n.client.LocaleInfo localeInfo = com.google.gwt.i18n.client.LocaleInfo.getCurrentLocale();");
            sourceWriter.println("String localeName = localeInfo.getLocaleName();");
            sourceWriter.println("if (!supportedLocales.contains(localeName) && localeName.contains(\"_\")){");
            //look for a language equiv
            sourceWriter.println("localeName = localeName.substring(0, localeName.indexOf(\"_\"));");
            sourceWriter.println("if (!supportedLocales.contains(localeName)){");
            sourceWriter.println("localeName = null;");
            sourceWriter.println("}");
            sourceWriter.println("} else {");
            sourceWriter.println("localeName = null;");
            sourceWriter.println("}");
            sourceWriter.println("if (localeName == null){");
            //TODO re-introduce runAsync to optimize loading of i18n properties. This currently doesn't work because of timing problems with the module loading
            //sourceWriter.println("com.google.gwt.core.client.GWT.runAsync(new com.google.gwt.core.client.RunAsyncCallback() {");
            //sourceWriter.println("public void onFailure(Throwable err) {");
            //sourceWriter.println("asyncClient.onUnavailable(err);");
            //sourceWriter.println("}");
            //sourceWriter.println("public void onSuccess() {");
            sourceWriter.print("i18nClient.onSuccess(new ");
            sourceWriter.print(generatedClasses.values().iterator().next());
            sourceWriter.print("().getAlli18nProperties());\n");
            //sourceWriter.println("}});");
            sourceWriter.println("return;");
            sourceWriter.println("}");
            for (Map.Entry<String, String> entry : generatedClasses.entrySet()) {
                sourceWriter.println("if (localeName.equals(\"" + entry.getKey() + "\")){");
                //sourceWriter.println("com.google.gwt.core.client.GWT.runAsync(new com.google.gwt.core.client.RunAsyncCallback() {");
                //sourceWriter.println("public void onFailure(Throwable err) {");
                //sourceWriter.println("asyncClient.onUnavailable(err);");
                //sourceWriter.println("}");
                //sourceWriter.println("public void onSuccess() {");
                sourceWriter.print("i18nClient.onSuccess(new ");
                sourceWriter.print(entry.getValue());
                sourceWriter.print("().getAlli18nProperties());\n");
                //sourceWriter.println("}});");
                sourceWriter.println("return;");
                sourceWriter.println("}");
            }
            sourceWriter.println(
                    "i18nClient.onUnavailable(new RuntimeException(\"Unable to find a localized file for "
                            + packageName + "." + simpleName + "\"));");
            sourceWriter.println("}");
            sourceWriter.commit(logger);
            logger.log(TreeLogger.INFO,
                    "Done Generating source for " + clazz.getQualifiedSourceName() + "Wrapper", null);
        }

        return clazz.getQualifiedSourceName() + "Wrapper";
    } catch (NotFoundException e) {
        e.printStackTrace();
        throw new UnableToCompleteException();
    }
}

From source file:org.broadleafcommerce.openadmin.generator.i18nConstantsGenerator.java

License:Apache License

protected Map<String, String> generateDynamicConstantClasses(JClassType clazz, TreeLogger logger,
        GeneratorContext context) throws NotFoundException {
    ResourceOracle resourceOracle = context.getResourcesOracle();
    Map<String, String> generatedClassses = new HashMap<String, String>();
    String myTypeName = clazz.getQualifiedSourceName().replace('.', '/');
    Map<String, Resource> resourceMap = resourceOracle.getResourceMap();
    for (Map.Entry<String, Resource> entry : resourceMap.entrySet()) {
        if (entry.getKey().contains(myTypeName) && entry.getKey().endsWith(".properties")) {
            String noSuffix = entry.getKey().substring(0, entry.getKey().indexOf(".properties"));
            String position1 = null;
            String position2 = null;
            if (noSuffix.contains("_")) {
                String i18nMatch = noSuffix.substring(noSuffix.lastIndexOf("_") + 1, noSuffix.length());
                if (i18nMatch != null && i18nMatch.length() == 2) {
                    position1 = i18nMatch;
                    noSuffix = noSuffix.substring(0, noSuffix.lastIndexOf("_"));
                    if (noSuffix.contains("_")) {
                        i18nMatch = noSuffix.substring(noSuffix.lastIndexOf("_") + 1, noSuffix.length());
                        if (i18nMatch != null && i18nMatch.length() == 2) {
                            position2 = i18nMatch;
                        }//from   w w  w.j a v  a 2  s .  co  m
                    }
                }
            }
            String packageName = clazz.getPackage().getName();
            StringBuilder suffix = new StringBuilder();
            if (position1 != null) {
                suffix.append("_");
                suffix.append(position1);
            }
            if (position2 != null) {
                suffix.append("_");
                suffix.append(position2);
            }
            if (position1 == null && position2 == null) {
                suffix.append("_default");
            }
            String simpleName = clazz.getName() + suffix.toString();
            SourceWriter sourceWriter = getSourceWriter(packageName, simpleName, context, logger,
                    new String[] {});
            if (sourceWriter != null) {
                Map<String, String> props = new HashMap<String, String>();
                InputStream is = entry.getValue().openContents();
                try {
                    BufferedReader in = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    boolean eof = false;
                    while (!eof) {
                        String temp = in.readLine();
                        if (temp == null) {
                            eof = true;
                        } else {
                            temp = temp.trim();
                            if (!temp.startsWith("#") && temp.length() > 0 && temp.contains("=")) {
                                String key = temp.substring(0, temp.indexOf("=")).trim();
                                String value = temp.substring(temp.indexOf("=") + 1, temp.length()).trim();
                                props.put(key, value);
                            }
                        }
                    }
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } finally {
                    try {
                        is.close();
                    } catch (Throwable ignored) {
                    }
                }

                logger.log(TreeLogger.INFO, "Emitting localized code for: " + entry.getKey(), null);
                sourceWriter.println(
                        "private java.util.Map<String, String> i18nProperties = new java.util.HashMap<String, String>();");
                sourceWriter.println("public " + simpleName + "() {");
                for (Map.Entry<String, String> prop : props.entrySet()) {
                    sourceWriter.print("i18nProperties.put(\"");
                    sourceWriter.print(prop.getKey());
                    sourceWriter.print("\",\"");
                    sourceWriter.print(prop.getValue().replace("\"", "\\\""));
                    sourceWriter.print("\");\n");
                }
                sourceWriter.println("}");
                sourceWriter.println("");
                sourceWriter.println("public java.util.Map<String, String> getAlli18nProperties() {");
                sourceWriter.println("return i18nProperties;");
                sourceWriter.println("}");
                sourceWriter.commit(logger);
                logger.log(TreeLogger.INFO, "Done Generating source for " + packageName + "." + simpleName,
                        null);

                generatedClassses.put(suffix.toString().substring(1, suffix.toString().length()),
                        packageName + "." + simpleName);
            }
        }
    }

    return generatedClassses;
}

From source file:org.chromium.distiller.rebind.JsTestEntryGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typename)
        throws UnableToCompleteException {
    String packageName = "org.chromium.distiller";
    String outputClassname = "JsTestBuilderImpl";

    List<TestCase> testCases = getTestCases(logger, context);

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, outputClassname);
    composer.addImplementedInterface("org.chromium.distiller.JsTestSuiteBuilder");
    PrintWriter printWriter = context.tryCreate(logger, packageName, outputClassname);
    if (printWriter != null) {
        for (TestCase ts : testCases) {
            String className = ts.classType.getName();
            String qualifiedClassName = ts.classType.getPackage().getName() + "." + className;
            composer.addImport(qualifiedClassName);
        }//from   w  ww. j  a v  a2 s  .c o  m
        SourceWriter sourceWriter = composer.createSourceWriter(context, printWriter);
        sourceWriter.println("JsTestBuilderImpl () {");
        sourceWriter.println("}");
        sourceWriter.println("public JsTestSuiteBase build() {");
        sourceWriter.indent();
        sourceWriter.println("JsTestSuiteBase testSuite = new JsTestSuiteBase();");
        for (TestCase ts : testCases) {
            String className = ts.classType.getName();
            String qualifiedClassName = ts.classType.getPackage().getName() + "." + className;
            sourceWriter.println("testSuite.addTestCase(");
            sourceWriter.println("        new JsTestSuiteBase.TestCaseFactory() {");
            sourceWriter.println("            @Override");
            sourceWriter.println("            public JsTestCase build() {");
            sourceWriter.println("                return new " + className + "();");
            sourceWriter.println("            }");
            sourceWriter.println("        }, \"" + qualifiedClassName + "\")");
            sourceWriter.indent();
            for (JMethod test : ts.tests) {
                String methodName = test.getName();
                sourceWriter.println(".addTest(");
                sourceWriter.println("        new JsTestSuiteBase.TestCaseRunner() {");
                sourceWriter.println("            @Override");
                sourceWriter.println("            public void run(JsTestCase testCase) throws Throwable {");
                sourceWriter.println("                ((" + className + ")testCase)." + methodName + "();");
                sourceWriter.println("            }");
                sourceWriter.println("        }, \"" + methodName + "\")");
            }
            sourceWriter.println(";");
            sourceWriter.outdent();
        }
        sourceWriter.println("return testSuite;");
        sourceWriter.outdent();
        sourceWriter.println("}");
        sourceWriter.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:org.cruxframework.crux.core.rebind.rpc.CruxProxyCreator.java

License:Apache License

/**
 * @param logger//from ww w . j  a  v a2  s .  c o m
 * @param context
 * @param asyncServiceTypeName
 * @return
 * @throws UnableToCompleteException 
 */
private RebindResult createAsyncWrapper(GeneratorContext context, String asyncServiceTypeName)
        throws UnableToCompleteException {
    JClassType serviceAsync = context.getTypeOracle().findType(serviceIntf.getQualifiedSourceName() + "Async");
    String asyncWrapperName = getProxyWrapperQualifiedName();

    if (checkAlreadyGenerated(context, asyncWrapperName)) {
        return new RebindResult(RebindMode.USE_EXISTING, asyncWrapperName);
    }

    SourceWriter srcWriter = getSourceWriter(logger, context, asyncServiceTypeName, asyncWrapperName);
    if (srcWriter == null) {
        return new RebindResult(RebindMode.USE_EXISTING, asyncWrapperName);
    }

    generateWrapperProxyFields(srcWriter, asyncServiceTypeName);

    generateWrapperProxyContructor(srcWriter);

    generateProxyWrapperMethods(srcWriter, serviceAsync);

    if (this.hasSyncTokenMethod) {
        generateProxyWrapperStartMethod(srcWriter);

        generateProxyWrapperEndMethod(srcWriter);

        generateProxyWrapperUpdateTokenMethod(srcWriter);

        generateSetServiceEntryPointMethod(srcWriter);
    }

    srcWriter.commit(logger);

    return new RebindResult(RebindMode.USE_ALL_NEW_WITH_NO_CACHING, asyncWrapperName);
}