Example usage for com.google.gwt.core.ext GeneratorContext tryCreate

List of usage examples for com.google.gwt.core.ext GeneratorContext tryCreate

Introduction

In this page you can find the example usage for com.google.gwt.core.ext GeneratorContext tryCreate.

Prototype

PrintWriter tryCreate(TreeLogger logger, String packageName, String simpleName);

Source Link

Document

Attempts to get a PrintWriter so that the caller can generate the source code for the named type.

Usage

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    filter = IntrospectorFilterHelper.getFilter(context);
    // System.out.println("ClientReflector generation...");
    long start = System.currentTimeMillis();
    Map<Class, String> ann2impl = new HashMap<Class, String>();
    Map<String, String> simpleNameCheck = new HashMap<String, String>();
    try {/*  ww w .  ja  v  a 2s . co m*/
        ClassSourceFileComposerFactory crf = null;
        // scan for reflectable annotations etc
        String superClassName = null;
        JClassType intrType = context.getTypeOracle().getType(typeName);
        if (intrType.isInterface() != null) {
            intrType = context.getTypeOracle().getType(ClientReflector.class.getName());
        }
        ReflectionModule module = intrType.getAnnotation(ReflectionModule.class);
        String moduleName = module.value();
        filter.setModuleName(moduleName);
        String implementationName = String.format("ClientReflector_%s_Impl", moduleName);
        superClassName = intrType.getQualifiedSourceName();
        crf = new ClassSourceFileComposerFactory(this.packageName, implementationName);
        PrintWriter printWriter = context.tryCreate(logger, packageName, implementationName);
        if (printWriter == null) {
            return packageName + "." + implementationName;
        }
        crf.addImport(LinkedHashMap.class.getName());
        crf.addImport(Map.class.getName());
        crf.addImport(GWT.class.getName());
        crf.addImport(JavaScriptObject.class.getName());
        crf.addImport(Registry.class.getName());
        crf.addImport(Annotation.class.getName());
        crf.addImport(UnsafeNativeLong.class.getName());
        crf.setSuperclass(superClassName);
        crf.addImport(ClientBeanReflector.class.getName());
        crf.addImport(ClientPropertyReflector.class.getName());
        crf.addImport(ClientReflector.class.getName());
        crf.addImport(RegistryLocation.class.getName());
        ctLookup.clear();
        visibleAnnotationClasses = new ArrayList<Class<? extends Annotation>>();
        List<JAnnotationType> jAnns = this.getClientVisibleAnnotations(logger, context.getTypeOracle());
        for (JAnnotationType jAnnotationType : jAnns) {
            visibleAnnotationClasses
                    .add((Class<? extends Annotation>) Class.forName(jAnnotationType.getQualifiedBinaryName()));
        }
        visibleAnnotationClasses.add(Omit.class);
        filter.filterAnnotations(jAnns, visibleAnnotationClasses);
        writeAnnotations(logger, context, jAnns, crf, moduleName.equals(ReflectionModule.INITIAL));
        List<JClassType> beanInfoTypes = this.getBeanInfoTypes(logger, context.getTypeOracle(), crf);
        List<JClassType> instantiableTypes = this.getInstantiableTypes(logger, context.getTypeOracle(), crf);
        Map<JClassType, Set<RegistryLocation>> gwtRegisteringClasses = getRegistryAnnotations(
                context.getTypeOracle());
        filter.filterReflectionInfo(beanInfoTypes, instantiableTypes, gwtRegisteringClasses);
        SourceWriter srcW = createWriter(crf, printWriter);
        writeIt(beanInfoTypes, instantiableTypes, srcW, gwtRegisteringClasses, implementationName);
        commit(context, logger, printWriter);
        System.out.format(
                "Client reflection generation  [%s] - " + "%s annotations, %s beans, "
                        + "%s instantiable types - %s ms\n",
                filter.getModuleName(), jAnns.size(), beanInfoTypes.size(), instantiableTypes.size(),
                System.currentTimeMillis() - start);
        filter.generationComplete();
        return packageName + "." + implementationName;
    } catch (Exception e) {
        e.printStackTrace();
        throw new WrappedRuntimeException(e);
    }
}

From source file:cc.alcina.framework.entity.gwtsynth.ClientReflectionGenerator.java

License:Apache License

private void writeAnnotations(TreeLogger logger, GeneratorContext context, List<JAnnotationType> jAnns,
        ClassSourceFileComposerFactory crf, boolean initial) throws Exception {
    for (JAnnotationType type : jAnns) {
        Class<? extends Annotation> annClass = forName(type);
        String implementationName = type.getName() + "_Impl";
        ann2impl.put(annClass, type.getPackage().getName() + "." + implementationName);
    }/*w  ww .  j  a  v a  2s  .c o  m*/
    for (JAnnotationType type : jAnns) {
        Class<? extends Annotation> annClass = forName(type);
        String implementationName = type.getName() + "_Impl";
        String implFQN = type.getPackage().getName() + "." + implementationName;
        crf.addImport(implFQN);
        ClassSourceFileComposerFactory annf = new ClassSourceFileComposerFactory(type.getPackage().getName(),
                implementationName);
        annf.addImport(Annotation.class.getCanonicalName());
        annf.addImport(type.getQualifiedSourceName());
        annf.addImplementedInterface(type.getName());
        List<Method> declaredMethods = new ArrayList<Method>(Arrays.asList(annClass.getDeclaredMethods()));
        Collections.sort(declaredMethods, ToStringComparator.INSTANCE);
        StringBuffer constrParams = new StringBuffer();
        boolean first = true;
        for (Method method : declaredMethods) {
            Class<?> returnType = method.getReturnType();
            addImport(annf, returnType);
            addImport(crf, returnType);
        }
        PrintWriter printWriter = context.tryCreate(logger, packageName, implementationName);
        // if calling from a non-initial module, we just want to add imports
        // without rewriting (indeed, we can't...) the annotation impls
        if (printWriter != null) {
            SourceWriter sw = createWriter(annf, printWriter);
            for (Method method : declaredMethods) {
                Class returnType = method.getReturnType();
                String rn = returnType.getSimpleName();
                String mn = method.getName();
                StringBuffer sb = new StringBuffer();
                writeLiteral(method.getDefaultValue(), returnType, sb, true);
                sw.println(String.format("private %s %s = %s;", rn, mn, sb.toString()));
                sw.println(String.format("public %s %s(){return %s;}", rn, mn, mn));
                sw.println(String.format("public %s _set%s(%s %s){this.%s = %s;return this;}",
                        implementationName, mn, rn, mn, mn, mn));
                sw.println();
            }
            sw.println();
            sw.println("public Class<? extends Annotation> annotationType() {");
            sw.indentln(String.format("return %s.class;", annClass.getSimpleName()));
            sw.println("}");
            sw.println();
            sw.println(String.format("public %s (){}", implementationName));
            sw.outdent();
            sw.println("}");
            commit(context, logger, printWriter);
        }
    }
}

From source file:ch.unifr.pai.twice.comm.serverPush.rebind.RemoteEventDeSerializerGenerator.java

License:Apache License

public SourceWriter getSourceWriter(JClassType classType, GeneratorContext context, TreeLogger logger) {
    String packageName = classType.getPackage().getName();
    String simpleName = classType.getSimpleSourceName() + "Impl";
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
    composer.setSuperclass(classType.getName());

    composer.addImport(classType.getQualifiedSourceName());

    // Need to add whatever imports your generated class needs.
    // composer.addImport("com.google.gwt.user.client.Window");
    // composer.addImport("com.google.gwt.user.client.rpc.AsyncCallback");
    // composer.addImport("com.google.gwt.user.client.ui.Button");
    // composer.addImport("com.google.gwt.user.client.ui.RootPanel");

    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);
    if (printWriter == null) {
        return null;
    } else {//from  w  w  w. j a v a 2s . com
        SourceWriter sw = composer.createSourceWriter(context, printWriter);
        return sw;
    }
}

From source file:ch.unifr.pai.twice.module.rebind.TWICEModuleGenerator.java

License:Apache License

/**
 * Define the class to be generated.//from   w ww .  j a  va 2  s.  c  om
 * 
 * @param classType
 * @param context
 * @param logger
 * @return
 */
public SourceWriter getSourceWriter(JClassType classType, GeneratorContext context, TreeLogger logger) {
    String packageName = classType.getPackage().getName();
    String simpleName = classType.getSimpleSourceName() + "Impl";
    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, simpleName);
    composer.setSuperclass(classType.getName());
    composer.addImplementedInterface(TWICEModuleInstantiator.class.getName() + "<"
            + getGenericClass(classType).getQualifiedSourceName() + ">");

    PrintWriter printWriter = context.tryCreate(logger, packageName, simpleName);
    if (printWriter == null) {
        return null;
    } else {
        SourceWriter sw = composer.createSourceWriter(context, printWriter);
        return sw;
    }
}

From source file:com.ait.ext4j.rebind.BeanModelGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    oracle = context.getTypeOracle();//  w ww.  j av a 2  s .co  m
    beanModelMarkerType = oracle.findType(BeanModelMarker.class.getName());
    beanModelTagType = oracle.findType(BeanModelTag.class.getName());

    try {
        // final all beans and bean markers
        beans = new ArrayList<JClassType>();
        JClassType[] types = oracle.getTypes();
        for (JClassType type : types) {
            if (isBeanMarker(type)) {
                beans.add(getMarkerBean(type));
            } else if (isBean(type)) {
                beans.add(type);
            }
        }

        final String genPackageName = BeanModelLookup.class.getPackage().getName();
        final String genClassName = "BeanModelLookupImpl";

        ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName,
                genClassName);
        composer.setSuperclass(BeanModelLookup.class.getCanonicalName());
        composer.addImport(BeanModelFactory.class.getName());
        composer.addImport(Map.class.getName());
        composer.addImport(FastMap.class.getName());

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

        if (pw != null) {
            SourceWriter sw = composer.createSourceWriter(context, pw);

            sw.println("private Map<String, BeanModelFactory> m;");

            sw.println("public BeanModelFactory getFactory(Class b) {");
            sw.indent();
            sw.println("String n = b.getName();");
            sw.println("if (m == null) {");
            sw.indentln("m = new FastMap<BeanModelFactory>();");
            sw.println("}");
            sw.println("if (m.get(n) == null) {");
            sw.indent();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < beans.size(); i++) {
                JClassType bean = beans.get(i);
                String name = createBean(bean, logger, context);
                String factory = createFactory(bean, name, logger, context);

                if (i > 0) {
                    sw.print(" else ");
                }
                sw.println("if (" + bean.getQualifiedSourceName() + ".class.getName().equals(n)) {");
                sw.indentln("m" + i + "();");

                sb.append("private void m" + i + "() {\n");
                sb.append("  m.put(" + bean.getQualifiedSourceName() + ".class.getName(), new " + factory
                        + "());\n");
                sb.append("}\n");

                sw.print("}");
            }
            sw.outdent();
            sw.println("}");
            sw.println("return m.get(n);");
            sw.outdent();
            sw.println("}");

            sw.println(sb.toString());
            sw.commit(logger);
        }

        return composer.getCreatedClassName();

    } catch (Exception e) {
        logger.log(TreeLogger.ERROR, "Class " + typeName + " not found.", e);
        throw new UnableToCompleteException();
    }

}

From source file:com.ait.ext4j.rebind.BeanModelGenerator.java

License:Apache License

protected String createFactory(JClassType bean, String beanModelName, TreeLogger logger,
        GeneratorContext context) throws Exception {
    final String genPackageName = BeanModelLookup.class.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_") + "_Factory";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModelFactory.class.getCanonicalName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        String typeName = bean.getQualifiedSourceName();
        SourceWriter sw = composer.createSourceWriter(context, pw);
        sw.println("public BeanModel newInstance() {");
        sw.println("return new " + beanModelName + "();");
        sw.println("}");

        sw.println("public BeanModel createModel(Object bean) {");
        sw.println("BeanModel model = newInstance();");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
            sw.println("model.set(\"" + p + "\"," + " ((" + typeName + ")bean)." + s + "()" + ");");
        }//from  w  ww. java2 s .  co m
        sw.println("model.setBean(bean);");
        sw.println("return model;");
        sw.println("}");
        sw.commit(logger);
    }
    return composer.getCreatedClassName();
}

From source file:com.ait.ext4j.rebind.BeanModelGenerator.java

License:Apache License

protected String createBean(JClassType bean, TreeLogger logger, GeneratorContext context) throws Exception {
    final String genPackageName = bean.getPackage().getName();
    final String genClassName = "BeanModel_" + bean.getQualifiedSourceName().replace(".", "_");

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanModel.class.getCanonicalName());
    composer.addImport(BeanModel.class.getName());
    composer.addImport(NestedModelUtil.class.getName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        List<JMethod> setters = findSetters(bean);
        SourceWriter sw = composer.createSourceWriter(context, pw);

        sw.println("public " + genClassName + "(){");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
                                                                           // or
                                                                           // is
            sw.println("beanProperties.add(\"" + p + "\");");
        }//  ww  w  .ja  v  a2 s  . co m
        sw.println("}");

        createGetMethods(getters, sw, bean.getQualifiedSourceName());
        createSetMethods(setters, sw, bean.getQualifiedSourceName());

        // delegate equals to bean
        sw.println("public boolean equals(Object obj) {");
        sw.println("  if (obj instanceof " + "BeanModel" + ") {");
        sw.println("    obj = ((BeanModel)obj).getBean();");
        sw.println("  }");
        sw.println("  return bean.equals(obj);");
        sw.println("}");

        // delegate hashCode to bean
        sw.println("public int hashCode(){");
        sw.println("  return bean.hashCode();");
        sw.println("}");

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

From source file:com.ait.ext4j.rebind.TemplateGenerator.java

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    TypeOracle oracle = context.getTypeOracle();
    this.templatesInterface = oracle.findType(Name.getSourceNameForClass(Template.class));

    JClassType interfaceType;//from   w w w  . j  av a2  s  . co m
    try {
        interfaceType = oracle.getType(typeName);
    } catch (NotFoundException e) {
        throw new RuntimeException(e);
    }

    if (interfaceType.isInterface() == null) {
        logger.log(TreeLogger.ERROR, typeName + " is not an interface type");
        throw new UnableToCompleteException();
    }
    if (!interfaceType.isAssignableTo(templatesInterface)) {
        logger.log(Type.ERROR, "This isn't a Template subtype...");
        throw new UnableToCompleteException();
    }

    String content = getTemplateContent(context, logger, interfaceType);
    String packageName = interfaceType.getPackage().getName();
    String className = "Template_For_" + interfaceType.getQualifiedSourceName().replace(".", "_");

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, className);
    composer.addImport(SafeHtml.class.getName());
    composer.addImport(SafeHtmlUtils.class.getName());
    composer.addImplementedInterface(Template.class.getName());

    PrintWriter pw = context.tryCreate(logger, packageName, className);
    SourceWriter sw = composer.createSourceWriter(context, pw);

    sw.println("  public SafeHtml getContent(){");
    sw.println("      return SafeHtmlUtils.fromSafeConstant(\"" + content + "\");");
    sw.println("  }");
    sw.println("");
    sw.println("");
    sw.println("  public SafeHtml getSafeContent(){");
    sw.println("      return SafeHtmlUtils.fromString(\"" + content + "\");");
    sw.println("  }");

    sw.commit(logger);
    return composer.getCreatedClassName();

}

From source file:com.ait.toolkit.rebind.BeanModelGenerator.java

License:Open Source License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    oracle = context.getTypeOracle();//from  w w  w . j  a v  a 2s  .  c  o  m
    beanModelMarkerType = oracle.findType(BeanMarker.class.getName());
    beanModelTagType = oracle.findType(BeanTag.class.getName());

    try {
        // final all beans and bean markers
        beans = new ArrayList<JClassType>();
        JClassType[] types = oracle.getTypes();
        for (JClassType type : types) {
            if (isBeanMarker(type)) {
                beans.add(getMarkerBean(type));
            } else if (isBean(type)) {
                beans.add(type);
            }
        }

        final String genPackageName = BeanLookup.class.getPackage().getName();
        final String genClassName = "BeanLookupImpl";

        ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName,
                genClassName);
        composer.setSuperclass(BeanLookup.class.getCanonicalName());
        composer.addImport(BeanFactory.class.getName());
        composer.addImport(Map.class.getName());
        composer.addImport(FastMap.class.getName());

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

        if (pw != null) {
            SourceWriter sw = composer.createSourceWriter(context, pw);

            sw.println("private Map<String, BeanFactory> m;");

            sw.println("public BeanFactory getFactory(Class b) {");
            sw.indent();
            sw.println("String n = b.getName();");
            sw.println("if (m == null) {");
            sw.indentln("m = new FastMap<BeanFactory>();");
            sw.println("}");
            sw.println("if (m.get(n) == null) {");
            sw.indent();
            StringBuffer sb = new StringBuffer();
            for (int i = 0; i < beans.size(); i++) {
                JClassType bean = beans.get(i);
                String name = createBean(bean, logger, context);
                String factory = createFactory(bean, name, logger, context);

                if (i > 0) {
                    sw.print(" else ");
                }
                sw.println("if (" + bean.getQualifiedSourceName() + ".class.getName().equals(n)) {");
                sw.indentln("m" + i + "();");

                sb.append("private void m" + i + "() {\n");
                sb.append("  m.put(" + bean.getQualifiedSourceName() + ".class.getName(), new " + factory
                        + "());\n");
                sb.append("}\n");

                sw.print("}");
            }
            sw.outdent();
            sw.println("}");
            sw.println("return m.get(n);");
            sw.outdent();
            sw.println("}");

            sw.println(sb.toString());
            sw.commit(logger);
        }

        return composer.getCreatedClassName();

    } catch (Exception e) {
        logger.log(TreeLogger.ERROR, "Class " + typeName + " not found.", e);
        throw new UnableToCompleteException();
    }

}

From source file:com.ait.toolkit.rebind.BeanModelGenerator.java

License:Open Source License

protected String createFactory(JClassType bean, String beanModelName, TreeLogger logger,
        GeneratorContext context) throws Exception {
    final String genPackageName = BeanLookup.class.getPackage().getName();
    final String genClassName = "Bean_" + bean.getQualifiedSourceName().replace(".", "_") + "_Factory";

    ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(genPackageName, genClassName);
    composer.setSuperclass(BeanFactory.class.getCanonicalName());
    PrintWriter pw = context.tryCreate(logger, genPackageName, genClassName);

    if (pw != null) {
        List<JMethod> getters = findGetters(bean);
        String typeName = bean.getQualifiedSourceName();
        SourceWriter sw = composer.createSourceWriter(context, pw);
        sw.println("public Bean newInstance() {");
        sw.println("return new " + beanModelName + "();");
        sw.println("}");

        sw.println("public Bean createModel(Object bean) {");
        sw.println("Bean model = newInstance();");
        for (JMethod method : getters) {
            String s = method.getName();
            String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
            sw.println("model.set(\"" + p + "\"," + " ((" + typeName + ")bean)." + s + "()" + ");");
        }/*from w w w.  java  2 s .  c o m*/
        sw.println("model.setBean(bean);");
        sw.println("return model;");
        sw.println("}");
        sw.commit(logger);
    }
    return composer.getCreatedClassName();
}