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

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

Introduction

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

Prototype

void outdent();

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 {//from   w  w  w . j a v  a  2 s .c om
        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.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();/*  www.ja  va2  s . c  om*/
    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);
    }/*w ww  .ja  v  a 2  s . c om*/
    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//from  w  w  w.  ja  va  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) {//  w w w.j a  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: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 www . j  ava 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 void createGetMethods(List<JMethod> getters, SourceWriter sw, String typeName) {
    sw.println("public <X> X getPropertyAsString(String s) {");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indentln("return (X)NestedModelUtil.getNestedValue(this, s);");
    sw.println("}");

    for (JMethod method : getters) {
        JClassType returnType = method.getReturnType().isClassOrInterface();
        String s = method.getName();
        String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
                                                                       // or

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.println("Object value = ((" + typeName + ")bean)." + s + "();");

        try {/* w ww. ja  va 2  s  . co m*/
            if (returnType != null && returnType.isAssignableTo(oracle.getType(List.class.getName()))
                    && returnType.isParameterized() != null) {
                JParameterizedType type = returnType.isParameterized();
                JClassType[] params = type.getTypeArgs();
                if (beans.contains(params[0])) {
                    sw.println("if (value != null) {");
                    sw.indent();
                    sw.println("java.util.List list = (java.util.List)value;");
                    sw.println("java.util.List list2 = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + params[0].getQualifiedSourceName()
                            + ".class).createModel((java.util.Collection) list);");
                    sw.outdent();
                    sw.println("return (X) list2;");
                    sw.println("}");
                }
            } else {
                // swap returnType as generic types were not matching
                // (beans.contains(returnType))
                if (returnType != null) {
                    String t = returnType.getQualifiedSourceName();
                    if (t.indexOf("extends") == -1) {
                        returnType = oracle.getType(t);
                    }
                }
                if (beans.contains(returnType)) {
                    sw.println("if (value != null) {");
                    sw.println("    BeanModel nestedModel = nestedModels.get(s);");
                    sw.println("    if (nestedModel != null) {");
                    sw.println("      Object bean = nestedModel.getBean();");
                    sw.println("      if (!bean.equals(value)){");
                    sw.println("        nestedModel = null;");
                    sw.println("      }");
                    sw.println("    }");
                    sw.println("    if (nestedModel == null) {");
                    sw.println("        nestedModel = " + BeanModelLookup.class.getCanonicalName()
                            + ".get().getFactory(" + returnType.getQualifiedSourceName()
                            + ".class).createModel(value);");
                    sw.println("        nestedModels.put(s, nestedModel);");
                    sw.println("    }");
                    sw.println("    return (X)processValue(nestedModel);");
                    sw.println("}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        sw.println("return (X)processValue(value);");
        sw.println("}");
    }
    sw.println("return super.getFromCache(s);");
    sw.println("}");
}

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

License:Apache License

protected void createSetMethods(List<JMethod> properties, SourceWriter sw, String typeName) {
    sw.println("public <X> X setProperty(String s, X val) {");
    sw.indent();/*w w  w  .ja  v a2s  .  com*/
    sw.println("Object obj = val;");

    sw.println("if (obj instanceof BeanModel) {");
    sw.println("obj = ((BeanModel) obj).getBean();");
    sw.println("} else if (obj instanceof java.util.List) {");
    sw.println("java.util.List list = new java.util.ArrayList();");
    sw.println("for(Object o : (java.util.List) obj) {");
    sw.println("if(o instanceof BeanModel) {");
    sw.println("list.add(((BeanModel) o).getBean());");
    sw.println("} else {");
    sw.println("list.add(o);");
    sw.println("}");
    sw.println("}");
    sw.println("obj = list;");
    sw.println("}");

    sw.println("if (allowNestedValues && val instanceof BeanModel) {");
    sw.indent();
    sw.println("obj = ((BeanModel)val).getBean();");
    sw.println("if (nestedModels.containsKey(s)) {");
    sw.indent();
    sw.println("nestedModels.put(s, (BeanModel)val);");
    sw.outdent();
    sw.println("}");
    sw.outdent();
    sw.println("}");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indent();
    sw.println("X old = (X) NestedModelUtil.setNestedValue(this, s, val);");
    sw.println("notifyPropertyChanged(s, val, old);");
    sw.println("return old;");
    sw.outdent();
    sw.println("}");

    for (JMethod method : properties) {
        String s = method.getName();
        String p = lowerFirst(s.substring(3));
        String type = getMethodAttributeType(method);

        if (type.indexOf("extends") != -1) {
            type = "java.lang.Object";
        }

        if (type.equals("byte")) {
            type = "Byte";
        } else if (type.equals("char")) {
            type = "Character";
        } else if (type.equals("short")) {
            type = "Short";
        } else if (type.equals("int")) {
            type = "Integer";
        } else if (type.equals("long")) {
            type = "Long";
        } else if (type.equals("float")) {
            type = "Float";
        } else if (type.equals("double")) {
            type = "Double";
        } else if (type.equals("boolean")) {
            type = "Boolean";
        }

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.indent();
        sw.println("Object old = get(s);");

        sw.println("((" + typeName + ")bean)." + s + "((" + type + ")obj);");
        sw.println("notifyPropertyChanged(s, val, old);");
        sw.println("return (X)old;");
        sw.outdent();
        sw.println("}");
    }
    sw.println("return super.set(s, val);");
    sw.outdent();
    sw.println("}");
}

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 av  a  2  s  .c  om
    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 void createGetMethods(List<JMethod> getters, SourceWriter sw, String typeName) {
    sw.println("public <X> X getPropertyAsString(String s) {");

    sw.println("if (allowNestedValues && NestedModelUtil.isNestedProperty(s)) {");
    sw.indentln("return (X)NestedModelUtil.getNestedValue(this, s);");
    sw.println("}");

    for (JMethod method : getters) {
        JClassType returnType = method.getReturnType().isClassOrInterface();
        String s = method.getName();
        String p = lowerFirst(s.substring(s.startsWith("g") ? 3 : 2)); // get
        // or//from w ww  . j  ava  2  s .c o  m

        sw.println("if (s.equals(\"" + p + "\")) {");
        sw.println("Object value = ((" + typeName + ")bean)." + s + "();");

        try {
            if (returnType != null && returnType.isAssignableTo(oracle.getType(List.class.getName()))
                    && returnType.isParameterized() != null) {
                JParameterizedType type = returnType.isParameterized();
                JClassType[] params = type.getTypeArgs();
                if (beans.contains(params[0])) {
                    sw.println("if (value != null) {");
                    sw.indent();
                    sw.println("java.util.List list = (java.util.List)value;");
                    sw.println("java.util.List list2 = " + BeanLookup.class.getCanonicalName()
                            + ".get().getFactory(" + params[0].getQualifiedSourceName()
                            + ".class).createModel((java.util.Collection) list);");
                    sw.outdent();
                    sw.println("return (X) list2;");
                    sw.println("}");
                }
            } else {
                // swap returnType as generic types were not matching
                // (beans.contains(returnType))
                if (returnType != null) {
                    String t = returnType.getQualifiedSourceName();
                    if (t.indexOf("extends") == -1) {
                        returnType = oracle.getType(t);
                    }
                }
                if (beans.contains(returnType)) {
                    sw.println("if (value != null) {");
                    sw.println("    Bean nestedModel = nestedModels.get(s);");
                    sw.println("    if (nestedModel != null) {");
                    sw.println("      Object bean = nestedModel.getBean();");
                    sw.println("      if (!bean.equals(value)){");
                    sw.println("        nestedModel = null;");
                    sw.println("      }");
                    sw.println("    }");
                    sw.println("    if (nestedModel == null) {");
                    sw.println("        nestedModel = " + BeanLookup.class.getCanonicalName()
                            + ".get().getFactory(" + returnType.getQualifiedSourceName()
                            + ".class).createModel(value);");
                    sw.println("        nestedModels.put(s, nestedModel);");
                    sw.println("    }");
                    sw.println("    return (X)processValue(nestedModel);");
                    sw.println("}");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        sw.println("return (X)processValue(value);");
        sw.println("}");
    }
    sw.println("return super.getFromCache(s);");
    sw.println("}");
}