List of usage examples for com.google.gwt.user.rebind SourceWriter println
void println(String s);
From source file:com.guit.rebind.jsorm.JsonSerializerGenerator.java
License:Apache License
@Override protected void generate(SourceWriter writer) throws UnableToCompleteException { JClassType arg = baseClass/*from w ww . ja va2 s . c o m*/ .asParameterizationOf(getType(JsonSerializer.class.getCanonicalName()).isGenericType()) .getTypeArgs()[0]; String parameterType = arg.getParameterizedQualifiedSourceName(); writer.println("private " + TypeJsonSerializer.class.getCanonicalName() + "<" + parameterType + "> serializer = " + JsonSerializerUtil.generate(logger, context, arg) + ".getSingleton();"); writer.println("public String serialize(" + parameterType + " t) {"); writer.println("return serializer.serialize(t).toString();"); writer.println("}"); writer.println("public " + parameterType + " deserialize(String json) {"); writer.println("return serializer.deserialize(" + JSONParser.class.getCanonicalName() + ".parse(json));"); writer.println("}"); }
From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java
License:Apache License
public static String generate(TreeLogger logger, GeneratorContext context, JClassType pojoType) throws UnableToCompleteException { JsonSerializerUtil.logger = logger;// w w w .j av a2 s . c om // We cannot serialize java.lang.Object String pojoQualifiedName = pojoType.getQualifiedSourceName(); if (pojoQualifiedName.equals(Object.class.getCanonicalName())) { error("You cannot serialize Object... we either"); } if (exceptions == null) { exceptions = new HashMap<String, String>(); try { List<String> ormExceptions = context.getPropertyOracle() .getConfigurationProperty("json.orm.exception").getValues(); for (String e : ormExceptions) { String[] parts = e.split(" "); if (parts.length != 2) { error("Bad json orm exception format. i.e 'java.util.List java.util.ArrayList<%s>. Found: %s'", e); } exceptions.put(parts[0], parts[1]); } } catch (BadPropertyValueException e) { throw new IllegalStateException(e); } } String parameterizedQualifiedSourceName = pojoType.getParameterizedQualifiedSourceName(); String typeName = parameterizedQualifiedSourceName; // Basic types if (typeName.equals(Void.class.getCanonicalName())) { return VoidSerializer.class.getCanonicalName(); } else if (typeName.equals(String.class.getCanonicalName())) { return StringSerializer.class.getCanonicalName(); } else if (typeName.equals(Integer.class.getCanonicalName())) { return IntegerSerializer.class.getCanonicalName(); } else if (typeName.equals(Long.class.getCanonicalName())) { return LongSerializer.class.getCanonicalName(); } else if (typeName.equals(Double.class.getCanonicalName())) { return DoubleSerializer.class.getCanonicalName(); } else if (typeName.equals(Float.class.getCanonicalName())) { return FloatSerializer.class.getCanonicalName(); } else if (typeName.equals(Date.class.getCanonicalName())) { return DateSerializer.class.getCanonicalName(); } else if (typeName.equals(Boolean.class.getCanonicalName())) { return BooleanSerializer.class.getCanonicalName(); } // Build name avoiding generics collitions StringBuilder implName = new StringBuilder(); makeImplName(pojoType, implName); implName.append("_GuitJsonSerializer"); String packageName = pojoType.getPackage().getName(); if (packageName.startsWith("java.")) { packageName = "com.guit.java." + packageName.substring(5); } String implNameString = implName.toString(); if (getClass(packageName, implNameString)) { return packageName + "." + implNameString; } ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(packageName, implNameString); composer.addImplementedInterface(TypeJsonSerializer.class.getCanonicalName() + "<" + typeName + ">"); PrintWriter printWriter = context.tryCreate(logger, packageName, implNameString); String createdName = composer.getCreatedClassName(); if (printWriter != null) { SourceWriter writer = composer.createSourceWriter(context, printWriter); JType iterableParameterType = null; JPrimitiveType iterableParameterPrimitiveType = null; // Iterable JGenericType iterableType = context.getTypeOracle().findType(Iterable.class.getCanonicalName()) .isGenericType(); boolean isIterable = false; if (iterableType.isAssignableFrom(pojoType)) { isIterable = true; iterableParameterType = pojoType.asParameterizationOf(iterableType).getTypeArgs()[0]; iterableParameterPrimitiveType = iterableParameterType.isPrimitive(); // Find if theres any exception String qualifiedSourceName = pojoQualifiedName; if (exceptions.containsKey(qualifiedSourceName)) { parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<" + iterableParameterType.getParameterizedQualifiedSourceName() + ">"; } } // Map JGenericType mapType = context.getTypeOracle().findType(Map.class.getCanonicalName()).isGenericType(); boolean isMap = false; JClassType mapKeyType = null; JClassType mapValueType = null; if (mapType.isAssignableFrom(pojoType)) { isMap = true; JParameterizedType pojoMap = pojoType.asParameterizationOf(mapType); JClassType[] args = pojoMap.getTypeArgs(); mapKeyType = args[0]; mapValueType = args[1]; // Find if theres any exception String qualifiedSourceName = pojoQualifiedName; if (exceptions.containsKey(qualifiedSourceName)) { parameterizedQualifiedSourceName = exceptions.get(qualifiedSourceName) + "<" + mapKeyType.getParameterizedQualifiedSourceName() + "," + mapValueType.getParameterizedQualifiedSourceName() + ">"; } } // Array boolean isArray = false; JArrayType pojoArray = pojoType.isArray(); if (pojoArray != null) { isArray = true; iterableParameterType = pojoArray.getComponentType(); iterableParameterPrimitiveType = iterableParameterType.isPrimitive(); } // For pojos ArrayList<JField> fields = null; writer.println("public static " + createdName + " singleton;"); writer.println("public static " + createdName + " getSingleton() {"); writer.indent(); writer.println("return singleton == null ? (singleton = new " + createdName + "()) : singleton;"); writer.outdent(); writer.println("}"); writer.println("@Override"); writer.println("public " + JSONValue.class.getCanonicalName() + " serialize(" + typeName + " data) {"); writer.indent(); if (isMap) { writer.println("if (data != null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " array = new " + JSONArray.class.getCanonicalName() + "();"); writer.println("int n = 0;"); writer.println("for (" + Entry.class.getCanonicalName() + "<" + mapKeyType.getParameterizedQualifiedSourceName() + ", " + mapValueType.getParameterizedQualifiedSourceName() + ">" + " entry : data.entrySet()) {"); writer.indent(); writer.print("array.set(n, "); JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive(); if (mapKeyPrimitive == null) { printValueSerialized(logger, context, writer, "entry.getKey()", mapKeyType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "entry.getKey()", mapKeyPrimitive); } writer.println(");"); writer.println("n++;"); writer.print("array.set(n, "); JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive(); if (mapValuePrimitive == null) { printValueSerialized(logger, context, writer, "entry.getValue()", mapValueType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "entry.getValue()", mapValuePrimitive); } writer.println(");"); writer.println("n++;"); writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else if (isIterable || isArray) { writer.println("if (data != null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " array = new " + JSONArray.class.getCanonicalName() + "();"); writer.println("int n = 0;"); writer.println( "for (" + iterableParameterType.getParameterizedQualifiedSourceName() + " item : data) {"); writer.indent(); writer.print("array.set(n, "); if (iterableParameterPrimitiveType == null) { printValueSerialized(logger, context, writer, "item", iterableParameterType, pojoType); } else { printPrimitiveSerialized(typeName, writer, "item", iterableParameterPrimitiveType); } writer.println(");"); writer.println("n++;"); writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else if (pojoType.isEnum() != null) { writer.println("if (data != null) {"); writer.indent(); writer.println("return new " + JSONString.class.getCanonicalName() + "(data.name());"); writer.outdent(); writer.println("}"); writer.println("return " + JSONNull.class.getCanonicalName() + ".getInstance();"); } else { // Assert the type have an empty constructor try { pojoType.getConstructor(emptyParameter); } catch (NotFoundException e) { error("The data type of the place does not have an empty constructor. Found %s", typeName); } writer.println(jsonObject + " json = new " + jsonObject + "();"); fields = new ArrayList<JField>(); getFields(fields, pojoType); for (JField f : fields) { String fieldName = f.getName(); String getterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); JType fieldType = f.getType(); JPrimitiveType primitive = fieldType.isPrimitive(); String fieldTypeQualifiedType = fieldType.getQualifiedSourceName(); if (primitive != null) { writer.print("json.put(\"" + fieldName + "\","); printPrimitiveSerialized(typeName, writer, "get" + getterName + "(data)", primitive); writer.println(");"); } else { writer.println( fieldTypeQualifiedType + " " + fieldName + " = get" + getterName + "(data);"); writer.println("if (" + fieldName + " != null) {"); writer.indent(); writer.print("json.put(\"" + fieldName + "\","); printValueSerialized(logger, context, writer, fieldName, fieldType, pojoType); writer.println(");"); writer.outdent(); writer.println("}"); } } writer.println("return json;"); } writer.outdent(); writer.println("}"); // Getters and setters printJsniGettersAndSetters(writer, pojoType); writer.println("@Override"); writer.println( "public " + typeName + " deserialize(" + JSONValue.class.getCanonicalName() + " jsonValue) {"); writer.indent(); if (isMap) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();"); writer.println("int jsonArraySize = jsonArray.size();"); writer.println(parameterizedQualifiedSourceName + " map = new " + parameterizedQualifiedSourceName + "();"); writer.println("for (int n = 0; n < jsonArraySize; n+=2) {"); writer.indent(); writer.println(JSONValue.class.getCanonicalName() + " key = jsonArray.get(n);"); writer.println(JSONValue.class.getCanonicalName() + " value = jsonArray.get(n + 1);"); writer.print("map.put("); JPrimitiveType mapKeyPrimitive = mapKeyType.isPrimitive(); if (mapKeyPrimitive == null) { printValueDeserialized(logger, context, writer, "key", mapKeyType); } else { printPrimitiveDeserialized(typeName, writer, "key", mapKeyPrimitive); } writer.print(","); JPrimitiveType mapValuePrimitive = mapValueType.isPrimitive(); if (mapValuePrimitive == null) { printValueDeserialized(logger, context, writer, "value", mapValueType); } else { printPrimitiveDeserialized(typeName, writer, "value", mapValuePrimitive); } writer.println(");"); writer.outdent(); writer.println("}"); writer.println("return map;"); writer.outdent(); writer.println("} else { return null; }"); } else if (isIterable || isArray) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println(JSONArray.class.getCanonicalName() + " jsonArray = jsonValue.isArray();"); writer.println("int jsonArraySize = jsonArray.size();"); if (isIterable) { writer.println(parameterizedQualifiedSourceName + " array = new " + parameterizedQualifiedSourceName + "();"); } else { JArrayType array = iterableParameterType.isArray(); if (array != null) { String arrayName = array.getQualifiedSourceName() + "[]"; int index = arrayName.indexOf("["); String arrayDeclaration = arrayName.substring(0, index + 1) + "jsonArraySize" + arrayName.substring(index + 1); writer.println(arrayName + " array = new " + arrayDeclaration + ";"); } else { String parameterQualifiedName = iterableParameterType.getQualifiedSourceName(); writer.println(parameterQualifiedName + "[] array = new " + parameterQualifiedName + "[jsonArraySize];"); } } writer.println("for (int n = 0; n < jsonArraySize; n++) {"); writer.indent(); writer.println(JSONValue.class.getCanonicalName() + " item = jsonArray.get(n);"); if (isIterable) { writer.print("array.add("); } else { writer.print("array[n] = "); } if (iterableParameterPrimitiveType == null) { printValueDeserialized(logger, context, writer, "item", iterableParameterType); } else { printPrimitiveDeserialized(typeName, writer, "item", iterableParameterPrimitiveType); } if (isIterable) { writer.println(");"); } else { writer.println(";"); } writer.outdent(); writer.println("}"); writer.println("return array;"); writer.outdent(); writer.println("} else { return null; }"); } else if (pojoType.isEnum() != null) { writer.println("if (jsonValue.isNull() == null) {"); writer.indent(); writer.println("return " + typeName + ".valueOf(jsonValue.isString().stringValue());"); writer.outdent(); writer.println("} else { return null; }"); } else { // Assert the type have an empty constructor try { pojoType.getConstructor(emptyParameter); } catch (NotFoundException e) { error("The data type of the place does not have an empty constructor. Found %s", typeName); } writer.println(JSONObject.class.getCanonicalName() + " json = jsonValue.isObject();"); writer.println(typeName + " instance = new " + typeName + "();"); for (JField f : fields) { String fieldName = f.getName(); String setterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); JType fieldType = f.getType(); JPrimitiveType primitive = fieldType.isPrimitive(); if (primitive != null) { writer.print("set" + setterName + "(instance,"); printPrimitiveDeserialized(typeName, writer, "json.get(\"" + fieldName + "\")", primitive); writer.println(");"); } else { writer.println("if (json.containsKey(\"" + fieldName + "\")) {"); writer.indent(); writer.print("set" + setterName + "(instance,"); printValueDeserialized(logger, context, writer, "json.get(\"" + fieldName + "\")", fieldType); writer.println(");"); writer.outdent(); writer.println("}"); } } writer.println("return instance;"); } writer.outdent(); writer.println("}"); writer.commit(logger); } return createdName; }
From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java
License:Apache License
private static void printJsniGettersAndSetters(SourceWriter writer, JClassType pojoType) { for (JField f : pojoType.getFields()) { // Non static, final or transient if (f.isStatic() || f.isFinal() || f.isTransient()) { continue; }/* www .jav a 2 s .c om*/ String fieldName = f.getName(); String getterName = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); JType fieldType = f.getType(); // Print getters and setters String fieldTypeQualifiedType = fieldType.getQualifiedSourceName(); String pojoQualifiedName = pojoType.getQualifiedSourceName(); writer.println("private static native " + fieldTypeQualifiedType + " get" + getterName + "(" + pojoQualifiedName + " instance) /*-{\n" + " return instance.@" + pojoQualifiedName + "::" + fieldName + ";\n" + " }-*/;\n" + " \n" + " private static native void set" + getterName + "(" + pojoQualifiedName + " instance, " + fieldTypeQualifiedType + " value) /*-{\n" + " instance.@" + pojoQualifiedName + "::" + fieldName + " = value;\n" + " }-*/;"); } JClassType superclass = pojoType.getSuperclass(); if (superclass != null && !superclass.getQualifiedSourceName().equals(Object.class.getCanonicalName())) { printJsniGettersAndSetters(writer, superclass); } }
From source file:com.guit.rebind.jsorm.JsonSerializerUtil.java
License:Apache License
private static void printPrimitiveDeserialized(String typeName, SourceWriter writer, String fieldName, JPrimitiveType primitive) throws UnableToCompleteException { if (primitive.equals(JPrimitiveType.BOOLEAN)) { writer.println(fieldName + ".isBoolean().booleanValue()"); } else if (primitive.equals(JPrimitiveType.DOUBLE)) { writer.println(fieldName + ".isNumber().doubleValue()"); } else if (primitive.equals(JPrimitiveType.FLOAT)) { writer.println("(float)" + fieldName + ".isNumber().doubleValue()"); } else if (primitive.equals(JPrimitiveType.LONG)) { writer.println("(long)" + fieldName + ".isNumber().doubleValue()"); } else if (primitive.equals(JPrimitiveType.INT)) { writer.println("(int)" + fieldName + ".isNumber().doubleValue()"); } else {/*w w w .j a va 2 s . co m*/ error("The type %s is not a valid type for the place data. Found %s", primitive.getSimpleSourceName(), typeName); } }
From source file:com.guit.rebind.place.PlaceManagerInitializerGenerator.java
License:Apache License
@Override protected void generate(SourceWriter writer) throws UnableToCompleteException { writer.println("public void initialize(" + PlaceManagerImpl.class.getCanonicalName() + " manager) {"); writer.indent();/*from w w w. j a v a 2 s . co m*/ boolean encryptAll = !findConfigurationProperty("app.encrypt.place").getValues().get(0).equals("false"); for (Class<?> p : PlaceGinContributor.places) { String canonicalName = p.getCanonicalName(); String injectedPlace = p.isAnnotationPresent(RunAsync.class) ? GinOracle.getAsyncProvidedInstance(canonicalName) : GinOracle.getProvidedInstance(p.getCanonicalName()); String encryptPlace = (encryptAll || p.isAnnotationPresent(PlaceDataEncrypted.class)) ? "true" : "false"; writer.println("manager.addPlace(" + canonicalName + ".class, \"" + getPlaceName(p.getCanonicalName()) + "\", \"" + getPlaceTitle(p) + "\", " + injectedPlace + ", " + generatePlaceData(logger, context, canonicalName) + ".getSingleton(), " + encryptPlace + ");"); } ConfigurationProperty configurationProperty = findConfigurationProperty("app.default.place"); if (configurationProperty != null) { List<String> defaultPlaces = configurationProperty.getValues(); if (defaultPlaces.size() == 1) { String defaultPlace = defaultPlaces.get(0); if (defaultPlace != null) { JClassType type = getType(defaultPlace); if (type == null) { error("The default place type does not exists, check your gwt.xml module for typos in 'app.default.place'. Found: %s", defaultPlace); } writer.println( "manager.setDefaultPlace(\"" + getPlaceName(type.getQualifiedSourceName()) + "\");"); } } else { error("You can only have one default place"); } } writer.println(History.class.getCanonicalName() + ".addValueChangeHandler(manager);"); writer.println(Window.class.getCanonicalName() + ".addWindowClosingHandler(manager);"); writer.outdent(); writer.println("}"); }
From source file:com.gwtent.gen.aop.AOPCreator.java
License:Apache License
protected void createSource(SourceWriter source, JClassType classType) { createInterceptorMap(source, classType); source.println("private static final ClassType classType = TypeOracle.Instance.getClassType(" + classType.getSimpleSourceName() + ".class);"); source.println();// w ww. j a v a 2s .c o m declareMethodInvocation(source); source.println(); source.println("public " + getSimpleUnitName(classType) + "(){"); source.indent(); createMethodInvocation(source); source.outdent(); source.println("}"); overrideMethods(source, classType); source.println(); createMethodInvocationChain(source); }
From source file:com.gwtent.gen.aop.AOPCreator.java
License:Apache License
private void createInterceptorMap(SourceWriter source, JClassType classType) { source.println(""); source.println("private static class InterceptorMap{"); source.indent();/*from w ww . j ava 2 s.c om*/ source.println("static Map<Method, List<Method>> interceptors = new HashMap<Method, List<Method>>();"); source.println("static {"); source.indent(); source.println("ClassType aspectClass = null;"); source.println("Method method = null;"); for (JMethod sourceMethod : classType.getMethods()) { List<JMethod> allMatchedMethods = aspectCollector.allMatches(sourceMethod); if (allMatchedMethods.size() > 0) { methodCaches.add(new MethodCache(sourceMethod, allMatchedMethods)); source.println("{"); source.println("List<Method> matchAdvices = new ArrayList<Method>();"); for (JMethod matchedMethod : allMatchedMethods) { source.println("aspectClass = TypeOracle.Instance.getClassType(" + matchedMethod.getEnclosingType().getQualifiedSourceName() + ".class);"); source.println("method = aspectClass.findMethod(\"" + matchedMethod.getName() + "\", new String[]{" + GenUtils.getParamTypeNames(matchedMethod, '"') + "});"); source.println("if (method != null)"); source.println(" matchAdvices.add(method);"); } source.println( "interceptors.put(classType.findMethod(\"" + sourceMethod.getName() + "\", new String[]{" + GenUtils.getParamTypeNames(sourceMethod, '"') + "}), matchAdvices);"); source.println("}"); } } source.outdent(); source.println("}"); source.outdent(); source.println("}"); source.outdent(); }
From source file:com.gwtent.gen.aop.AOPCreator.java
License:Apache License
private void declareMethodInvocation(SourceWriter source) { for (MethodCache cache : methodCaches) { source.println("private final MethodInvocationLinkedAdapter " + getIvnValueName(cache.getSourceMethod()) + ";"); }/*from ww w .j a va 2 s .com*/ }
From source file:com.gwtent.gen.aop.AOPCreator.java
License:Apache License
private void createMethodInvocation(SourceWriter source) { source.println("Method method = null;"); for (MethodCache cache : methodCaches) { source.println("method = classType.findMethod(\"" + cache.getSourceMethod().getName() + "\", new String[]{" + GenUtils.getParamTypeNames(cache.getSourceMethod(), '"') + "});"); source.println(getIvnValueName(cache.getSourceMethod()) + " = createMethodInvocationChain(method);"); }//from w ww . j a va 2 s .c om }
From source file:com.gwtent.gen.aop.AOPCreator.java
License:Apache License
private void overrideMethods(SourceWriter source, JClassType classType) { for (MethodCache cache : methodCaches) { String ivnValueName = getIvnValueName(cache.getSourceMethod()); source.println(cache.getSourceMethod().toString()); source.println("{"); source.indent();/*from w w w .j ava 2 s .c o m*/ source.println( "if (" + ivnValueName + ".getCurrentInterceptor() instanceof MethodInterceptorFinalAdapter){"); if (GenUtils.checkIfReturnVoid(cache.getSourceMethod())) { source.println(" super." + cache.getSourceMethod().getName() + "(" + GenUtils.getParamNames(cache.getSourceMethod()) + ");"); source.println(" return;"); } else source.println(" return super." + cache.getSourceMethod().getName() + "(" + GenUtils.getParamNames(cache.getSourceMethod()) + ");"); source.println("}"); source.println(); source.println( "Object[] args = new Object[]{" + GenUtils.getParamNames(cache.getSourceMethod()) + "};"); source.println(ivnValueName + ".reset(args);"); source.println("try {"); if (GenUtils.checkIfReturnVoid(cache.getSourceMethod())) { source.println(" " + ivnValueName + ".proceed();"); source.println(" return;"); } else source.println(" return (" + cache.getSourceMethod().getReturnType().getQualifiedSourceName() + ") " + ivnValueName + ".proceed();"); source.println("} catch (Throwable e) {"); source.println(" throw new AspectException(e);"); source.println("}"); source.outdent(); source.println("}"); } }