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:cc.alcina.framework.entity.gen.SimpleCssResourceGenerator.java

License:Apache License

@Override
public String createAssignment(TreeLogger logger, ResourceContext context, JMethod method)
        throws UnableToCompleteException {
    try {/*  w w w .j  a v a2s . c  o m*/
        ConfigurationProperty cp = context.getGeneratorContext().getPropertyOracle()
                .getConfigurationProperty(IGNORE_DATA_URLS);
        logMissingUrlResources = !Boolean.valueOf(cp.getValues().get(0));
    } catch (BadPropertyValueException e1) {
        e1.printStackTrace();
    }
    URL[] resources = ResourceGeneratorUtil.findResources(logger, context, method);
    if (resources.length != 1) {
        logger.log(TreeLogger.ERROR, "Exactly one resource must be specified", null);
        throw new UnableToCompleteException();
    }
    URL resource = resources[0];
    SourceWriter sw = new StringSourceWriter();
    // Write the expression to create the subtype.
    sw.println("new " + SimpleCssResource.class.getName() + "() {");
    sw.indent();
    if (!AbstractResourceGenerator.STRIP_COMMENTS) {
        // Convenience when examining the generated code.
        sw.println("// " + resource.toExternalForm());
    }
    sw.println("public String getText() {");
    sw.indent();
    String toWrite = Util.readURLAsString(resource);
    if (context.supportsDataUrls()) {
        try {
            toWrite = replaceWithDataUrls(context, toWrite);
        } catch (Exception e) {
            logger.log(Type.ERROR, "css data url gen", e);
            throw new UnableToCompleteException();
        }
    }
    if (toWrite.length() > MAX_STRING_CHUNK) {
        writeLongString(sw, toWrite);
    } else {
        sw.println("return \"" + Generator.escape(toWrite) + "\";");
    }
    sw.outdent();
    sw.println("}");
    sw.println("public String getName() {");
    sw.indent();
    sw.println("return \"" + method.getName() + "\";");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    return sw.toString();
}

From source file:cc.alcina.framework.entity.gen.SimpleCssResourceGenerator.java

License:Apache License

/**
 * A single constant that is too long will crash the compiler with an out of
 * memory error. Break up the constant and generate code that appends using
 * a buffer.//from  w  ww. j  a v a  2  s.  co m
 */
private void writeLongString(SourceWriter sw, String toWrite) {
    sw.println("StringBuilder builder = new StringBuilder();");
    int offset = 0;
    int length = toWrite.length();
    while (offset < length - 1) {
        int subLength = Math.min(MAX_STRING_CHUNK, length - offset);
        sw.print("builder.append(\"");
        sw.print(Generator.escape(toWrite.substring(offset, offset + subLength)));
        sw.println("\");");
        offset += subLength;
    }
    sw.println("return builder.toString();");
}

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

License:Apache License

public void writeIt(List<JClassType> beanInfoTypes, List<JClassType> instantiableTypes, SourceWriter sw,
        Map<JClassType, Set<RegistryLocation>> gwtRegisteringClasses, String implName) throws Exception {
    String qualifiedImplName = this.packageName + "." + implName;
    Map<JClassType, String> initClassMethodNames = new LinkedHashMap<>();
    Map<JClassType, String> initNewInstanceNames = new LinkedHashMap<>();
    List<String> methodLines = new ArrayList<String>();
    sw.indent();/*from   w w w .  ja v a2s  . com*/
    sw.println("private JavaScriptObject createLookup;");
    sw.println();
    sw.println(String.format("public %s() {", implName));
    sw.indent();
    sw.println("super();");
    sw.println("init();");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("@Override");
    sw.println("@UnsafeNativeLong");
    sw.println("public native <T> T newInstance0(Class<T> clazz, long objectId, long localId) /*-{");
    sw.indent();
    sw.println(String.format("var constructor = this.@%s::createLookup.get(clazz);", qualifiedImplName));
    sw.println("return constructor ? constructor() : null;");
    sw.outdent();
    sw.println("}-*/;");
    sw.println();
    sw.println();
    int methodCount = 0;
    for (JClassType jct : beanInfoTypes) {
        if (filter.omitForModule(jct, ReflectionAction.BEAN_INFO_DESCRIPTOR)) {
            continue;
        }
        String methodName = "initClass" + (methodCount++);
        initClassMethodNames.put(jct, methodName);
        sw.println(String.format("private void %s(){", methodName));
        sw.indent();
        sw.println(
                "Map<String,ClientPropertyReflector> propertyReflectors = new LinkedHashMap<String,ClientPropertyReflector>();");
        for (JMethod method : getPropertyGetters(jct)) {
            String propertyName = getPropertyNameForReadMethod(method);
            if (propertyName.equals("class") || propertyName.equals("propertyChangeListeners")) {
                continue;
            }
            if (method.isStatic()) {
                continue;
            }
            Collection<Annotation> annotations = getSuperclassAnnotationsForMethod(method);
            int aCount = 0;
            String annArray = "";
            boolean ignore = false;
            for (Annotation a : annotations) {
                if (a.annotationType() == Omit.class) {
                    ignore = true;
                }
            }
            if (ignore) {
                continue;
            }
            sw.println("{");
            sw.indent();
            for (Annotation a : annotations) {
                if (!a.annotationType().isAnnotationPresent(ClientVisible.class)
                        || a.annotationType() == RegistryLocation.class) {
                    continue;
                }
                if (aCount++ != 0) {
                    annArray += ", ";
                }
                String annImpl = getAnnImpl(a, ann2impl, aCount);
                annArray += "a" + aCount;
                sw.println(annImpl);
            }
            sw.println(String.format(
                    "ClientPropertyReflector reflector = " + "new ClientPropertyReflector(\"%s\",%s.class,"
                            + " new Annotation[]{%s}) ;",
                    propertyName, method.getReturnType().getQualifiedSourceName(), annArray));
            sw.println("propertyReflectors.put(reflector.getPropertyName(), reflector);");
            sw.outdent();
            sw.println("}");
        }
        int aCount = 0;
        String annArray = "";
        for (Annotation a : getClassAnnotations(jct, visibleAnnotationClasses, false)) {
            if (aCount++ != 0) {
                annArray += ", ";
            }
            String annImpl = getAnnImpl(a, ann2impl, aCount);
            annArray += "a" + aCount;
            sw.println(annImpl);
        }
        sw.println(String.format(
                "ClientBeanReflector beanReflector = new ClientBeanReflector("
                        + "%s.class,new Annotation[]{%s},propertyReflectors);",
                jct.getQualifiedSourceName(), annArray));
        sw.println("gwbiMap.put(beanReflector.getBeanClass(),beanReflector );");
        sw.outdent();
        sw.println("}");
        sw.println("");
    }
    Set<JClassType> allTypes = new LinkedHashSet<JClassType>();
    allTypes.addAll(instantiableTypes);
    allTypes.addAll(beanInfoTypes);
    List<JClassType> constructorTypes = CollectionFilters.filter(allTypes, new CollectionFilter<JClassType>() {
        @Override
        public boolean allow(JClassType o) {
            return o.isEnum() == null;
        }
    });
    methodCount = 0;
    for (JClassType jClassType : constructorTypes) {
        /*
         * private native void registerNewInstanceFunction0(Class clazz)/*-{
         * var closure=this;
         * this.@au.com.barnet.jade.client.test.TestClientReflector
         * ::createLookup[clazz] = function() { return
         * closure.@au.com.barnet
         * .jade.client.test.TestClientReflector::createInstance0()(); }; }-
         */;
        String registerMethodName = String.format("registerNewInstanceFunction%s", methodCount);
        String createMethodName = String.format("createInstance%s", methodCount);
        initNewInstanceNames.put(jClassType,
                String.format("%s(%s.class);", registerMethodName, jClassType.getQualifiedSourceName()));
        sw.println(String.format("private Object %s(){", createMethodName));
        sw.indent();
        sw.println(String.format("return GWT.create(%s.class);", jClassType.getQualifiedSourceName()));
        sw.outdent();
        sw.println("};");
        sw.println();
        sw.println(String.format("private native void %s(Class clazz)/*-{", registerMethodName));
        sw.indent();
        sw.println("var closure = this;");
        sw.println(String.format("var fn = function() {", qualifiedImplName));
        sw.indent();
        sw.println(String.format("return closure.@%s::%s()();", qualifiedImplName, createMethodName));
        sw.outdent();
        sw.println("};");
        sw.println(String.format("this.@%s::createLookup.set(clazz,fn);", qualifiedImplName));
        sw.outdent();
        sw.println("}-*/;");
        sw.println();
        methodCount++;
    }
    sw.println("private native void initCreateLookup0()/*-{");
    sw.indent();
    sw.println(String.format("this.@%s::createLookup = new Map();", qualifiedImplName));
    sw.outdent();
    sw.println("}-*/;");
    sw.println();
    sw.println("protected void initReflector(Class clazz) {");
    sw.indent();
    sw.println("switch(clazz.getName()){");
    sw.indent();
    initClassMethodNames.entrySet().forEach(e -> {
        sw.println("case \"%s\":", e.getKey().getQualifiedBinaryName());
        sw.indent();
        sw.println("%s();", e.getValue());
        sw.println("break;");
        sw.outdent();
    });
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("protected void initialiseNewInstance(Class clazz) {");
    sw.indent();
    sw.println("switch(clazz.getName()){");
    sw.indent();
    initNewInstanceNames.entrySet().forEach(e -> {
        sw.println("case \"%s\":", e.getKey().getQualifiedBinaryName());
        sw.indent();
        sw.println("%s", e.getValue());
        sw.println("break;");
        sw.outdent();
    });
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.println();
    sw.println("private void init() {");
    sw.indent();
    sw.println("initCreateLookup0();");
    for (JClassType t : allTypes) {
        if (!filter.omitForModule(t, ReflectionAction.NEW_INSTANCE)) {
            sw.println(String.format("forNameMap.put(\"%s\",%s.class);", t.getQualifiedBinaryName(),
                    t.getQualifiedSourceName()));
        }
    }
    sw.println("");
    sw.println("//init registry");
    sw.println("");
    for (JClassType clazz : gwtRegisteringClasses.keySet()) {
        for (RegistryLocation l : gwtRegisteringClasses.get(clazz)) {
            StringBuffer sb = new StringBuffer();
            writeAnnImpl(l, ann2impl, 0, false, sb, false);
            sw.println(
                    String.format("Registry.get().register(%s.class,%s);", clazz.getQualifiedSourceName(), sb));
        }
    }
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
}

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);
    }//ww  w. j  ava  2 s .  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:cc.alcina.framework.entity.util.AsLiteralSerializer.java

License:Apache License

public String generate(Object source) throws Exception {
    // traverse/*  w  w w . j  a  v a 2 s .c o m*/
    traverse(source, null);
    reachedClasses.remove(null);
    for (Class c : reachedClasses) {
        if (isEnumSubClass(c)) {
            continue;
        }
        composerFactory.addImport(c.getName().replace("$", "."));
    }
    StringWriter stringWriter = new StringWriter();
    SourceWriter sw = composerFactory.createSourceWriter(new PrintWriter(stringWriter));
    sw.indent();
    ArrayList<OutputInstantiation> insts = new ArrayList<OutputInstantiation>(reached.values());
    Collections.sort(insts);
    for (OutputInstantiation inst : insts) {
        Class<? extends Object> valueClass = inst.value.getClass();
        String className = getClassName(valueClass);
        if (isEnumExt(valueClass) || inst.value instanceof Class) {
            sw.println(String.format("%s %s;", className, getObjLitRef(inst), getLiteralValue(inst.value)));
        } else {
            sw.println(String.format("%s %s;", className, getObjLitRef(inst), className,
                    getLiteralValue(inst.value)));
        }
    }
    StringBuffer mainCall = new StringBuffer();
    newCall(mainCall, sw, false);
    for (OutputInstantiation inst : insts) {
        Class<? extends Object> valueClass = inst.value.getClass();
        String className = getClassName(valueClass);
        String add = null;
        if (isEnumExt(valueClass) || inst.value instanceof Class) {
            add = (String.format(" %s= %s;", getObjLitRef(inst), getLiteralValue(inst.value)));
        } else {
            add = (String.format(" %s= new %s (%s);", getObjLitRef(inst), className,
                    getLiteralValue(inst.value)));
        }
        sw.println(add);
        methodLengthCounter += add.length() + 1;
        if (methodLengthCounter > 20000) {
            newCall(mainCall, sw, true);
        }
    }
    for (OutputAssignment assign : assignments) {
        String assignLit = String.format("%s.%s(%s);", getObjLitRef(assign.src),
                assign.pd.getWriteMethod().getName(), getObjLitRef(assign.target));
        sw.println(assignLit);
        methodLengthCounter += assignLit.length() + 1;
        if (methodLengthCounter > 20000) {
            newCall(mainCall, sw, true);
        }
    }
    for (OutputInstantiation inst : addToCollnMap.keySet()) {
        List<OutputInstantiation> elts = addToCollnMap.get(inst);
        for (OutputInstantiation elt : elts) {
            String add = String.format("%s.add(%s);", getObjLitRef(inst), getObjLitRef(elt));
            sw.println(add);
            methodLengthCounter += add.length() + 1;
            if (methodLengthCounter > 20000) {
                newCall(mainCall, sw, true);
            }
        }
    }
    for (OutputInstantiation inst : addToMapMap.keySet()) {
        List<OutputInstantiation> elts = addToMapMap.get(inst);
        Iterator<OutputInstantiation> itr = elts.iterator();
        for (; itr.hasNext();) {
            OutputInstantiation key = itr.next();
            OutputInstantiation value = itr.next();
            String add = String.format("%s.put(%s,%s);", getObjLitRef(inst), getObjLitRef(key),
                    getObjLitRef(value));
            sw.println(add);
            methodLengthCounter += add.length() + 1;
            if (methodLengthCounter > 20000) {
                newCall(mainCall, sw, true);
            }
        }
    }
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    sw.println(String.format("public %s generate() {", source.getClass().getSimpleName()));
    sw.indent();
    sw.println(mainCall.toString());
    sw.println("return obj_1;");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");
    return stringWriter.toString();
}

From source file:cc.alcina.framework.entity.util.AsLiteralSerializer.java

License:Apache License

private void newCall(StringBuffer mainCall, SourceWriter sw, boolean close) {
    if (close) {/*from w  w w. ja v  a 2s  .  c  o m*/
        sw.outdent();
        sw.println("}");
        sw.outdent();
        sw.println("}");
    }
    sw.println(String.format("private class Generate_%s {", ++callCounter));
    sw.indent();
    sw.println("private void run() {");
    sw.indent();
    mainCall.append(String.format("new Generate_%s().run();", callCounter));
    methodLengthCounter = 0;
}

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

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Build a new class, that implements a "paintScreen" method
    JClassType classType;/*from  w  w w . j  av a  2 s . c o  m*/

    try {
        classType = context.getTypeOracle().getType(typeName);
        // Here you would retrieve the metadata based on typeName for this
        // Screen
        SourceWriter src = getSourceWriter(classType, context, logger);
        if (src != null) {
            src.println("@Override");
            src.println(
                    "public " + RemoteEvent.class.getName() + "<?> deserialize(" + JSONObject.class.getName()
                            + " o, String t, String string, " + TWICESecurityManager.class.getName()
                            + " securityManager) throws " + MessagingException.class.getName() + " {");
            JClassType abstractRemoteEvent = context.getTypeOracle().findType(RemoteEvent.class.getName());
            src.println("if(t==null){");
            src.println("return null;");
            src.println("}");
            for (JClassType subType : abstractRemoteEvent.getSubtypes()) {
                if (!subType.getPackage().getName()
                        .contains(ch.unifr.pai.twice.comm.serverPush.client.RemoteEventDeserializer.class
                                .getPackage().getName())
                        && !subType.getName().endsWith("Impl")) {
                    src.println("else if(t.equals(" + subType.getQualifiedSourceName() + ".class.getName())){");
                    src.println(subType.getQualifiedSourceName() + " event = " + GWT.class.getName()
                            + ".create(" + subType.getQualifiedSourceName() + ".class);");
                    src.println("return event.deserialize(string, securityManager);");
                    src.println("}");
                }
            }
            src.println("return null;}");
            src.commit(logger);
        }
        return typeName + "Impl";
    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

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

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Build a new class, that implements a "paintScreen" method
    JClassType classType;// w  w w  .  j a  v a2s . c  o  m

    try {
        classType = context.getTypeOracle().getType(typeName);
        JClassType superClass = classType.getSuperclass();
        JClassType[] generics = superClass.isParameterized().getTypeArgs();
        JClassType eventHandlerClass = generics[0];

        // Here you would retrieve the metadata based on typeName for this
        // Screen
        SourceWriter src = getSourceWriter(classType, context, logger);
        if (src != null) {
            src.println("@Override");
            src.println("public " + String.class.getName() + " getEventType(){");
            src.println("return " + classType.getQualifiedSourceName() + ".class.getName();");
            src.println("}");

            if (superClass.getQualifiedSourceName().equals(RemoteEventWrapper.class.getName())
                    || superClass.getQualifiedSourceName().equals(UndoableRemoteEventWrapper.class.getName())) {
                JClassType eventClass = generics[1];
                src.println("@Override");
                src.println("public void wrap(" + eventClass.getQualifiedSourceName() + " event){");
                for (JMethod method : classType.getMethods()) {
                    String realMethodName = method.getName().replaceAll("_", "().");
                    src.println("setProperty(\"" + method.getName() + "\", " + String.class.getName()
                            + ".valueOf(event." + realMethodName + "()));");
                }
                src.println("}");

                for (JMethod method : classType.getMethods()) {
                    if (method.isAbstract()) {
                        src.println();
                        src.println("@Override");
                        src.println("public " + String.class.getName() + " " + method.getName() + "(){");
                        src.println(
                                JSONValue.class.getName() + " value = json.get(\"" + method.getName() + "\");");
                        src.println(
                                "return value!=null && value.isString()!=null ? value.isString().stringValue() : null;");
                        src.println("}");
                    }
                }

                src.println();
            }

            src.println("@Override");
            src.println("public " + GwtEvent.class.getName() + "." + Type.class.getSimpleName() + "<"
                    + eventHandlerClass.getQualifiedSourceName() + "> getAssociatedType() {");
            src.println("\treturn " + classType.getQualifiedSourceName() + ".TYPE;");
            src.println("}");

            src.println();

            src.println("@Override");
            src.println(
                    "protected void dispatch(" + eventHandlerClass.getQualifiedSourceName() + " handler) {");
            // for (JMethod m : eventHandlerClass.getMethods()) {
            // if(!m.getName().equals("undo")){
            boolean undoable = classType
                    .isAssignableTo(context.getTypeOracle().getType(UndoableRemoteEvent.class.getName()));
            if (undoable) {
                src.println("if(isUndo())");
                src.println("handler.undo(this);");
                src.println("else {");
                src.println("handler.saveState(this);");
            }
            src.println("\t handler.onEvent(this);");
            if (undoable) {
                src.println("}");
            }

            // }
            // }
            src.println("}");
            src.println();
            src.println("@Override");
            src.println("public String serialize(" + TWICESecurityManager.class.getName() + " security) throws "
                    + MessagingException.class.getName() + "{");
            for (JField field : classType.getFields()) {
                if (!field.isStatic() && !field.isTransient()) {
                    src.println("if(" + field.getName() + "!=null){");
                    src.println("setProperty(\"" + field.getName() + "\", String.valueOf(" + field.getName()
                            + "));}");

                }
            }
            src.println("return super.serialize(security);");
            src.println("}");
            src.println();
            src.println("@Override");
            src.println(
                    "public " + RemoteEvent.class.getName() + "<" + eventHandlerClass.getQualifiedSourceName()
                            + "> deserialize(String string, " + TWICESecurityManager.class.getName()
                            + " security) throws " + MessagingException.class.getName() + "{");
            src.println(RemoteEvent.class.getName() + " result = super.deserialize(string, security);");
            for (JField field : classType.getFields()) {
                if (!field.isStatic()) {
                    if (String.class.getName().equals(field.getType().getQualifiedSourceName()))
                        src.println(field.getName() + " = getProperty(\"" + field.getName() + "\");");
                    else {
                        src.println("String " + field.getName() + "Tmp = getProperty(\"" + field.getName()
                                + "\");");
                        src.println(field.getName() + " = " + field.getName() + "Tmp!=null ? "
                                + field.getType().getQualifiedSourceName() + ".valueOf(" + field.getName()
                                + "Tmp) : null;");
                    }
                }
            }
            src.println("return result;");
            src.println("}");
            src.commit(logger);

        }
        return typeName + "Impl";

    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

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

License:Apache License

@Override
public String generate(TreeLogger logger, GeneratorContext context, String typeName)
        throws UnableToCompleteException {
    // Build a new class, that implements a "paintScreen" method
    JClassType classType;/*w  ww. jav  a  2s .co m*/
    try {
        classType = context.getTypeOracle().getType(typeName);
        JClassType genericClass = getGenericClass(classType);

        SourceWriter src = getSourceWriter(classType, context, logger);
        if (src != null) {
            src.println("@Override");
            src.println("public " + Map.class.getName() + "<" + String.class.getName() + ", "
                    + Object.class.getName() + "> getConfigurableFields("
                    + genericClass.getQualifiedSourceName() + " instance){");
            src.println(Map.class.getName() + "<" + String.class.getName() + ", " + Object.class.getName()
                    + "> result = new " + HashMap.class.getName() + "<" + String.class.getName() + ", "
                    + Object.class.getName() + ">();");
            for (JField f : genericClass.getFields()) {
                Configurable c = f.getAnnotation(Configurable.class);
                if (c != null && !f.isFinal() && !f.isPrivate() && !f.isProtected()) {
                    src.println("result.put(\"" + c.value() + "\", instance." + f.getName() + ");");
                }
            }
            src.println("return result;");
            src.println("}");

            src.println("@Override");
            src.println("public void configure(" + Map.class.getName() + "<" + String.class.getName() + ", "
                    + String.class.getName() + "> properties, " + genericClass.getQualifiedSourceName()
                    + " instance){");
            src.println("for(" + String.class.getName() + " key : properties.keySet()){");
            src.println("String value = properties.get(key);");
            src.println("if(key==null){");
            src.println("}");
            for (JField f : genericClass.getFields()) {
                Configurable c = f.getAnnotation(Configurable.class);
                if (c != null && !f.isFinal() && !f.isPrivate() && !f.isProtected()) {
                    JPrimitiveType t = f.getType().isPrimitive();
                    if (t != null) {
                        src.println("else if(key.equals(\"" + c.value() + "\")){");
                        switch (t) {
                        case INT:
                            src.println("instance." + f.getName() + "=" + Integer.class.getName()
                                    + ".parseInt(value);");
                            break;
                        case BOOLEAN:
                            src.println("instance." + f.getName() + "=" + Boolean.class.getName()
                                    + ".parseBoolean(value);");
                            break;
                        case DOUBLE:
                            src.println("instance." + f.getName() + "=" + Double.class.getName()
                                    + ".parseDouble(value);");
                            break;
                        case FLOAT:
                            src.println("instance." + f.getName() + "=" + Float.class.getName()
                                    + ".parseFloat(value);");
                            break;
                        case LONG:
                            src.println("instance." + f.getName() + "=" + Long.class.getName()
                                    + ".parseLong(value);");
                            break;
                        default:
                            throw new RuntimeException("The primitive type \"" + t.name()
                                    + "\" is not supported for configuration");
                        }
                    } else if (f.getType().getQualifiedSourceName().equals(String.class.getName())) {
                        src.println("instance." + f.getName() + "=value");
                    } else {
                        throw new RuntimeException("The type \"" + f.getType().getQualifiedSourceName()
                                + "\" is not supported for configuration");
                    }
                    src.println("}");
                }
            }
            src.println("}");
            src.println("}");

            src.println("@Override");
            src.println("public " + RunAsyncCallback.class.getName() + " instantiate(final "
                    + AsyncCallback.class.getName() + "<" + genericClass.getQualifiedSourceName()
                    + "> callback){");
            src.println("return new " + RunAsyncCallback.class.getName() + "(){");
            src.println("@Override");
            src.println("public void onSuccess(){");
            src.println(genericClass.getQualifiedSourceName() + " module = " + GWT.class.getName() + ".create("
                    + genericClass.getQualifiedSourceName() + ".class);");
            src.println("//start(module);");
            src.println("callback.onSuccess(module);");
            src.println("}");
            src.println("@Override");
            src.println("public void onFailure(" + Throwable.class.getName() + " reason){");
            src.println("callback.onFailure(reason);");
            src.println("}");
            src.println("};");
            src.println("}");
            src.commit(logger);
        }

        return typeName + "Impl";

    } catch (NotFoundException e) {
        e.printStackTrace();
    }
    return null;
}

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();/*from w  w w . j  a  va 2 s. c  om*/
    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();
    }

}