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

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

Introduction

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

Prototype

void println(String s);

Source Link

Usage

From source file:net.sf.mmm.util.nls.impl.rebind.NlsBundleFactoryGenerator.java

License:Apache License

/**
 * Generates the <code>createBundle</code> method.
 * /*from  w  w  w .j  ava  2  s .  co m*/
 * @param sourceWriter is the {@link SourceWriter}.
 * @param logger is the {@link TreeLogger}.
 * @param context is the {@link GeneratorContext}.
 */
protected void generateMethodCreateBundle(SourceWriter sourceWriter, TreeLogger logger,
        GeneratorContext context) {

    // method declaration
    sourceWriter.print("public <BUNDLE extends ");
    sourceWriter.print(NlsBundle.class.getSimpleName());
    sourceWriter.println("> BUNDLE createBundle(Class<BUNDLE> bundleInterface) {");
    sourceWriter.indent();

    // method body
    sourceWriter.println("BUNDLE bundle = getBundle(bundleInterface);");
    sourceWriter.println("if (bundle == null) {");
    sourceWriter.indent();
    // create and register
    generateBlockBundleCreation(sourceWriter, logger, context);
    sourceWriter.outdent();
    sourceWriter.println("}");

    sourceWriter.println("return bundle;");

    // end method...
    sourceWriter.outdent();
    sourceWriter.println("}");

}

From source file:net.sf.mmm.util.nls.impl.rebind.NlsBundleFactoryGenerator.java

License:Apache License

/**
 * Generates the block that creates the {@link NlsBundle} instance lazily via {@link GWT#create(Class)}.
 * // w w w  .  j  a  v a  2  s.  c  o m
 * @param sourceWriter is the {@link SourceWriter}.
 * @param logger is the {@link TreeLogger}.
 * @param context is the {@link GeneratorContext}.
 */
protected void generateBlockBundleCreation(SourceWriter sourceWriter, TreeLogger logger,
        GeneratorContext context) {

    // find all subclasses of NlsBundle
    TypeOracle typeOracle = context.getTypeOracle();
    JClassType bundleClass = typeOracle.findType(NlsBundle.class.getName());
    JClassType bundleWithLookupClass = typeOracle.findType(NlsBundleWithLookup.class.getName());
    JClassType[] types = typeOracle.getTypes();
    int bundleCount = 0;
    logger.log(Type.INFO, "Checking " + types.length + " types...");
    for (JClassType type : types) {
        if ((type.isAssignableTo(bundleClass))
                && (!type.equals(bundleClass) && (!type.equals(bundleWithLookupClass)))) {
            logger.log(Type.INFO, "Found NlsBundle interface: " + type);

            sourceWriter.print("if (");
            sourceWriter.print(type.getQualifiedSourceName());
            sourceWriter.println(".class == bundleInterface) {");
            sourceWriter.indent();

            sourceWriter.print("bundle = GWT.create(");
            sourceWriter.print(type.getQualifiedSourceName());
            sourceWriter.println(".class);");

            sourceWriter.println("register(bundleInterface, bundle);");

            sourceWriter.outdent();
            sourceWriter.print("} else ");

            bundleCount++;
        }
    }
    sourceWriter.println("{");
    sourceWriter.indent();

    sourceWriter.print("throw new ");
    sourceWriter.print(IllegalStateException.class.getSimpleName());
    sourceWriter.println("(\"Undefined NlsBundle \" + bundleInterface.getName());");

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

    logger.log(Type.INFO, "Found " + bundleCount + " NlsBundle interface(s).");
}

From source file:net.sf.mmm.util.nls.impl.rebind.NlsBundleGeneratorGwtI18n.java

License:Apache License

/**
 * {@inheritDoc}//from   ww w. j a v  a  2  s  .  c om
 */
@Override
protected void generateFields(SourceWriter sourceWriter, TreeLogger logger, GeneratorContext context,
        JClassType bundleClass) {

    super.generateFields(sourceWriter, logger, context, bundleClass);

    // generate i18n interface singleton field
    sourceWriter.print("private static final ");
    String i18nInterface = generateBundleInterface(bundleClass, logger, context);
    sourceWriter.print(i18nInterface);
    sourceWriter.print(" ");
    sourceWriter.print(VARIABLE_GWT_I18N);
    sourceWriter.print(" = GWT.create(");
    sourceWriter.print(i18nInterface);
    sourceWriter.println(".class);");
    sourceWriter.println();
}

From source file:net.sf.mmm.util.nls.impl.rebind.NlsBundleGeneratorGwtI18n.java

License:Apache License

/**
 * {@inheritDoc}/*  ww  w.j  a  va 2  s.co  m*/
 */
@Override
protected void generateMethodMessageBlock(SourceWriter sourceWriter, TreeLogger logger,
        GeneratorContext context, String methodName) {

    sourceWriter.print(VARIABLE_MESSAGE);
    sourceWriter.print(" = ");
    sourceWriter.print(VARIABLE_GWT_I18N);
    sourceWriter.print(".");
    sourceWriter.print(methodName);
    sourceWriter.println("();");
}

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 w  w w.j  a v  a2  s.co  m*/
 * @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.sf.mmm.util.pojo.descriptor.impl.rebind.PojoDescriptorBuilderGenerator.java

License:Apache License

/**
 * Generates the method {@link AbstractPojoDescriptorBuilderLimited#createDescriptor(Class)}.
 * // w  ww  .ja  v a2  s . co  m
 * @param sourceWriter is the {@link SourceWriter} where to {@link SourceWriter#print(String) write} the
 *        source code to.
 * @param logger is the {@link TreeLogger}.
 * @param simpleName is the {@link Class#getSimpleName() simple name} of the {@link Class} to generate.
 * @param inputType is the {@link JClassType} reflecting the input-type that triggered the generation via
 *        {@link GWT#create(Class)}.
 * @param context is the {@link GeneratorContext}.
 */
private void generateMethodCreateDescriptor(SourceWriter sourceWriter, TreeLogger logger, String simpleName,
        JClassType inputType, GeneratorContext context) {

    sourceWriter.print("public <POJO> ");
    sourceWriter.print(AbstractPojoDescriptorImpl.class.getSimpleName());
    sourceWriter.println("<POJO> createDescriptor(Class<POJO> pojoType) {");
    sourceWriter.indent();

    PojoDescriptorGeneratorConfiguration configuration = getConfiguration();
    TypeOracle typeOracle = context.getTypeOracle();
    int typeCount = 0;
    JClassType[] types = typeOracle.getTypes();
    for (JClassType type : types) {
        if (configuration.isPojoTypeSupported(type, typeOracle)) {
            typeCount++;
            sourceWriter.print("if (pojoType == ");
            sourceWriter.print(type.getQualifiedSourceName());
            sourceWriter.println(".class) {");
            sourceWriter.indent();
            sourceWriter.print("return GWT.create(");
            sourceWriter.print(type.getQualifiedSourceName());
            sourceWriter.println(".class);");
            sourceWriter.outdent();
            sourceWriter.print("} else ");
        }
    }
    if (typeCount > 0) {
        sourceWriter.println("{");
        sourceWriter.indent();
        if (typeCount <= 3) {
            logger.log(Type.WARN, "Found only " + typeCount + " supported type(s)");
        } else {
            logger.log(Type.INFO, "Found " + typeCount + " supported types.");
        }
    } else {
        logger.log(Type.ERROR, "No type found for criteria: " + configuration.getPojoTypeDescription());
    }
    sourceWriter.println("return super.createDescriptor(pojoType);");
    if (typeCount > 0) {
        sourceWriter.outdent();
        sourceWriter.println("}");
    }
    generateSourceCloseBlock(sourceWriter);
}

From source file:net.sf.mmm.util.pojo.descriptor.impl.rebind.PojoDescriptorGenerator.java

License:Apache License

/**
 * Generates the method {@link AbstractPojoDescriptorImpl#newInstance()}.
 *
 * @param inputType is the {@link JClassType} reflecting the input-type that triggered the generation via
 *        {@link com.google.gwt.core.client.GWT#create(Class)}.
 * @param sourceWriter is the {@link SourceWriter} where to {@link SourceWriter#print(String) write} the
 *        source code to./*  ww w. jav  a  2  s .  c o m*/
 * @param pojoDescriptor is the {@link PojoDescriptor}.
 */
private void generateMethodNewInstance(JClassType inputType, SourceWriter sourceWriter,
        PojoDescriptor<?> pojoDescriptor) {

    generateSourcePublicMethodDeclaration(sourceWriter, inputType.getQualifiedSourceName(), "newInstance", "",
            false);

    if (inputType.isInterface() != null) {
        sourceWriter.print("throw new ");
        sourceWriter.println(InstantiationFailedException.class.getName());
        sourceWriter.println("(getPojoClass());");
    } else {
        sourceWriter.print("return new ");
        sourceWriter.print(inputType.getQualifiedSourceName());
        sourceWriter.println("();");
    }

    generateSourceCloseBlock(sourceWriter);
}

From source file:net.sf.mmm.util.pojo.descriptor.impl.rebind.PojoDescriptorGenerator.java

License:Apache License

/**
 * Generates the constructor of the {@link Class} to generate.
 *
 * @param sourceWriter is the {@link SourceWriter} where to {@link SourceWriter#print(String) write} the
 *        source code to./*  w  ww .java 2s  . c o  m*/
 * @param simpleName is the {@link Class#getSimpleName() simple name} of the {@link Class} to generate.
 * @param inputType is the {@link JClassType} reflecting the input-type that triggered the generation via
 *        {@link com.google.gwt.core.client.GWT#create(Class)}.
 * @param pojoDescriptor is the {@link PojoDescriptor}.
 * @param context is the {@link GeneratorContext}.
 */
protected void generateConstructor(SourceWriter sourceWriter, String simpleName, JClassType inputType,
        PojoDescriptor<?> pojoDescriptor, GeneratorContext context) {

    generateSourcePublicConstructorDeclaration(sourceWriter, simpleName);
    sourceWriter.print("super(new ");
    sourceWriter.print(SimpleGenericTypeLimited.class.getSimpleName());
    sourceWriter.print("(");
    sourceWriter.print(inputType.getName());
    sourceWriter.print(".class), ");
    sourceWriter.print(AbstractPojoDescriptorBuilderLimited.class.getSimpleName());
    sourceWriter.println(".getInstance());");

    // local variable for property descriptor
    sourceWriter.print(PojoPropertyDescriptorImpl.class.getSimpleName());
    sourceWriter.println(" propertyDescriptor;");

    JClassType superType = getConfiguration().getSupportedSuperType(inputType, context.getTypeOracle());
    StatefulPropertyGenerator state = new StatefulPropertyGenerator(sourceWriter, superType);

    for (PojoPropertyDescriptor propertyDescriptor : pojoDescriptor.getPropertyDescriptors()) {
        state.generatePropertyDescriptorBlock(propertyDescriptor);
    }
    generateSourceCloseBlock(sourceWriter);
}

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();
    }//from   w w  w  .j a  v a2s  . 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();
    }/* ww w. j  a v a2s. 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();
    }
}