List of usage examples for com.google.gwt.core.ext.typeinfo JType isParameterized
JParameterizedType isParameterized();
From source file:com.cgxlib.xq.rebind.JsonBuilderGenerator.java
License:Apache License
public void generateMethod(SourceWriter sw, JMethod method, String name, TreeLogger logger) throws UnableToCompleteException { String ifaceName = method.getEnclosingType().getQualifiedSourceName(); String retType = method.getReturnType().getParameterizedQualifiedSourceName(); sw.print("public final " + retType + " " + method.getName()); JParameter[] params = method.getParameters(); if (params.length == 0) { JArrayType arr = method.getReturnType().isArray(); JParameterizedType list = method.getReturnType().isParameterized(); sw.println("() {"); sw.indent();/* ww w. j a v a 2s.c om*/ if (retType.matches("(java.lang.Boolean|boolean)")) { sw.println("return p.getBoolean(\"" + name + "\");"); } else if (retType.matches("java.util.Date")) { sw.println("return new Date(java.lang.Long.parseLong(p.getStr(\"" + name + "\")));"); } else if (method.getReturnType().isPrimitive() != null) { sw.println("return (" + retType + ")p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Character")) { sw.println("return (char) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Byte")) { sw.println("return (byte) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Integer")) { sw.println("return (int) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Float")) { sw.println("return p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Double")) { sw.println("return (double) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Long")) { sw.println("return (long) p.getFloat(\"" + name + "\");"); } else if (retType.equals("java.lang.Byte")) { sw.println("return (byte) p.getFloat(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), stringType)) { sw.println("return p.getStr(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), jsonBuilderType)) { String q = method.getReturnType().getQualifiedSourceName(); sw.println("return " + "((" + q + ")GWT.create(" + q + ".class))" + ".load(getPropertiesBase(\"" + name + "\"));"); } else if (isTypeAssignableTo(method.getReturnType(), settingsType)) { String q = method.getReturnType().getQualifiedSourceName(); sw.println("return " + "((" + q + ")getPropertiesBase(\"" + name + "\"));"); } else if (retType.equals(Properties.class.getName())) { sw.println("return getPropertiesBase(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), jsType)) { sw.println("return p.getJavaScriptObject(\"" + name + "\");"); } else if (isTypeAssignableTo(method.getReturnType(), functionType)) { sw.println("return p.getFunction(\"" + name + "\");"); } else if (arr != null || list != null) { JType type = arr != null ? arr.getComponentType() : list.getTypeArgs()[0]; boolean buildType = isTypeAssignableTo(type, jsonBuilderType); String t = type.getQualifiedSourceName(); sw.println("JsArrayMixed a = p.getArray(\"" + name + "\");"); sw.println("int l = a == null ? 0 : a.length();"); String ret; if (buildType) { sw.println(t + "[] r = new " + t + "[l];"); sw.println("JsObjectArray<?> a1 = p.getArray(\"" + name + "\").cast();"); sw.println("int l1 = r.length;"); sw.println("for (int i = 0 ; i < l1 ; i++) {"); sw.println(" Object w = a1.get(i);"); sw.println(" " + t + " instance = GWT.create(" + t + ".class);"); sw.println(" r[i] = instance.load(w);"); sw.println("}"); ret = "r"; } else { ret = "getArrayBase(\"" + name + "\", new " + t + "[l], " + t + ".class)"; } if (arr != null) { sw.println("return " + ret + ";"); } else { sw.println("return Arrays.asList(" + ret + ");"); } } else if (method.getReturnType().isEnum() != null) { sw.println("return " + method.getReturnType().getQualifiedSourceName() + ".valueOf(p.getStr(\"" + name + "\"));"); } else { sw.println("System.err.println(\"JsonBuilderGenerator WARN: unknown return type " + retType + " " + ifaceName + "." + name + "()\"); "); // We return the object because probably the user knows how to handle it sw.println("return p.get(\"" + name + "\");"); } sw.outdent(); sw.println("}"); } else if (params.length == 1) { JType type = params[0].getType(); JArrayType arr = type.isArray(); JParameterizedType list = type.isParameterized(); sw.print("(" + type.getParameterizedQualifiedSourceName() + " a)"); sw.println("{"); sw.indent(); if (arr != null || list != null) { String a = "a"; if (list != null) { a = "a.toArray(new " + list.getTypeArgs()[0].getQualifiedSourceName() + "[0])"; } sw.println("setArrayBase(\"" + name + "\", " + a + ");"); } else if (type.getParameterizedQualifiedSourceName().matches("java.util.Date")) { sw.println("p.setNumber(\"" + name + "\", a.getTime());"); } else if (type.getParameterizedQualifiedSourceName().matches( "(java.lang.(Character|Long|Double|Integer|Float|Byte)|(char|long|double|int|float|byte))")) { sw.println("p.setNumber(\"" + name + "\", a);"); } else if (type.getParameterizedQualifiedSourceName().matches("(java.lang.Boolean|boolean)")) { sw.println("p.setBoolean(\"" + name + "\", a);"); } else if (type.getParameterizedQualifiedSourceName().matches("com.cgxlib.xq.client.Function")) { sw.println("p.setFunction(\"" + name + "\", a);"); } else if (type.isEnum() != null) { sw.println("p.set(\"" + name + "\", a.name());"); } else { sw.println("set(\"" + name + "\", a);"); } if (!"void".equals(retType)) { if (isTypeAssignableTo(method.getReturnType(), method.getEnclosingType())) { sw.println("return this;"); } else { sw.println("return null;"); } } sw.outdent(); sw.println("}"); } }
From source file:com.didactilab.gwt.phprpc.rebind.PhpTools.java
License:Apache License
public static String typeToString(JType type, boolean phpCompatible) { String name = ""; JArrayType arrayType = type.isArray(); if (arrayType != null) { if (phpCompatible) name = "array"; else/*from w ww . j av a 2 s .c om*/ name = typeToString(arrayType.getComponentType(), phpCompatible) + "[]"; } else { JClassType classType = type.isClassOrInterface(); if ((classType != null) && (classType.getEnclosingType() != null)) name = typeToString(classType.getEnclosingType(), phpCompatible) + "_"; name += filterType(type.getSimpleSourceName()); if (!phpCompatible) { JParameterizedType params = type.isParameterized(); if (params != null) { JClassType[] args = params.getTypeArgs(); name += "<"; for (int i = 0, c = args.length; i < c; i++) { name += typeToString(args[i], phpCompatible); if (i < c - 1) name += ", "; } name += ">"; } } } return name; }
From source file:com.github.ludorival.dao.gwt.rebind.EntityManagerGenerator.java
License:Apache License
private BeanMetadata create(GeneratorContext context, TreeLogger logger, String packageName, JClassType type, Class<?> classAdapter, IsEntity anno) throws TypeOracleException { String beanName = anno == null || anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(); Source implementation = null; JClassType implType = type;/* ww w.j av a 2s . com*/ TypeOracle typeOracle = context.getTypeOracle(); if (type.isInterface() != null) { implType = null; JClassType[] types = type.getSubtypes(); log(logger, Type.DEBUG, "Get all sub types of %s : %s", type, Arrays.toString(types)); if (types != null && types.length > 0) { for (JClassType jClassType : types) { if (isInstantiable(jClassType, logger)) { implType = jClassType; implementation = new Source(implType.getPackage().getName(), implType.getName()); break; } } } if (implType == null) { log(logger, Type.ERROR, "The type %s has not valid subtypes " + "%s !", type, Arrays.toString(types)); return null; } } if (!implType.isDefaultInstantiable()) return null; String prefix = classAdapter.getSimpleName().replace("Adapter", ""); boolean isEntity = anno != null; String className = prefix + beanName; if (parseOnlyInterface && implType != type) className += "Light"; PrintWriter writer = context.tryCreate(logger, packageName, className); if (writer == null) { return new BeanMetadata(type, className, implementation, isEntity); } ClassSourceFileComposerFactory factory = new ClassSourceFileComposerFactory(packageName, className); logger.log(Type.DEBUG, "Create Entity " + factory.getCreatedClassName()); factory.setSuperclass(classAdapter.getSimpleName() + "<" + type.getName() + ">"); factory.addImport(RuntimeException.class.getName()); factory.addImport(classAdapter.getName()); factory.addImport(type.getQualifiedSourceName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Collection.class.getName()); } factory.addImport(HashMap.class.getName()); factory.addImport(Property.class.getName()); factory.addImport(Property.class.getName() + ".Kind"); factory.addImport(Index.class.getName()); factory.addImport(implType.getQualifiedSourceName()); factory.addImport("javax.annotation.Generated"); factory.addAnnotationDeclaration("@Generated(" + "value=\"" + AdapterEntity.class.getName() + "\", " + "date=\"" + new Date() + "\", " + "comments=\"Generated by DAO-GWT project.\")"); SourceWriter sourceWriter = factory.createSourceWriter(context, writer); sourceWriter.println("//AUTO GENERATED FILE BY DAO-GWT " + getClass().getName() + ". DO NOT EDIT!\n"); sourceWriter.println("private static HashMap<String,Property<%s,?>> PROPERTIES = " + "new HashMap<String,Property<%s,?>>();", type.getName(), type.getName()); if (isEntity) { factory.addImport(ArrayList.class.getName()); factory.addImport(Index.class.getName()); sourceWriter.println("private static Collection<Index> INDEXES = " + "new ArrayList<Index>();"); } sourceWriter.println("static {"); sourceWriter.indent(); JClassType interfaz = type != implType ? type : null; JMethod[] methods = parseOnlyInterface ? type.getInheritableMethods() : implType.getInheritableMethods(); for (JMethod method : methods) { String name = method.getName(); //Check if the method has a IsIgnored annotation before to continue IsIgnored ignored = method.getAnnotation(IsIgnored.class); if (ignored != null) { log(logger, Type.DEBUG, EXPLICITELY_IGNORED, name, implType); continue; } boolean startsWithGet = name.startsWith("get"); boolean startsWithIs = name.startsWith("is"); if (!startsWithGet && !startsWithIs) { log(logger, Type.DEBUG, IGNORE_METHOD, name, implType); continue; } //check no parameters if (method.getParameterTypes().length != 0) { log(logger, Type.WARN, NO_PARAMETER_GETTER, name, implType); continue; } //check return type JType returnType = method.getReturnType(); if (returnType == null || returnType.getQualifiedSourceName().equals(Void.class.getName()) || returnType.getQualifiedSourceName().equals(void.class.getName())) { log(logger, Type.DEBUG, VOID_GETTER, name + "" + returnType, implType); continue; } //change the format of the name getXyy ==> xyy String getterSetter = name; if (startsWithGet) getterSetter = name.substring(3); else if (startsWithIs) getterSetter = name.substring(2); name = getterSetter.substring(0, 1).toLowerCase() + getterSetter.substring(1); // check if the getter has an annotation IsIndexable indexable = method.getAnnotation(IsIndexable.class); boolean isIndexable = indexable != null; if (isIndexable && !isEntity) log(logger, Type.WARN, ONLY_ENTITY_FOR_INDEX, name, implType, IsEntity.class); isIndexable = isIndexable && isEntity;//only entity can defined indexable element String indexName = isIndexable ? indexable.aliasName() : ""; String[] compositeIndexes = isIndexable ? indexable.compoundWith() : new String[0]; Kind kind = null; JType typeOfCollection = null; String typeOfCollectionString = "null"; if (!isPrimitive(returnType)) { //load complex properties except Key if (returnType.isEnum() != null) { kind = Kind.ENUM; } else { boolean isPrimitive = false; boolean isEnum = false; JParameterizedType pType = returnType.isParameterized(); JType collection = typeOracle.parse(Collection.class.getName()); if (pType != null && pType.getRawType().isAssignableTo(collection.isClassOrInterface())) { JClassType[] types = pType.getTypeArgs(); kind = Kind.COLLECTION_OF_PRIMITIVES; if (types.length > 1) { log(logger, Type.DEBUG, CANNOT_PROCESS_PARAMETERIZED_TYPE, returnType, implType); continue; } typeOfCollection = types[0]; typeOfCollectionString = typeOfCollection.getQualifiedSourceName() + ".class"; log(logger, Type.DEBUG, "The type of the collection is %s", typeOfCollectionString); isPrimitive = isPrimitive(typeOfCollection); isEnum = typeOfCollection.isEnum() != null; } if (!isPrimitive) { if (isEnum && kind != null) { kind = Kind.COLLECTION_OF_ENUMS; } else { JClassType classType = typeOfCollection != null ? typeOfCollection.isClassOrInterface() : returnType.isClassOrInterface(); boolean isBean = isBean(classType); if (isBean) { log(logger, Type.DEBUG, "The property %s is well a type %s", name, classType); if (kind == null) kind = Kind.BEAN; else kind = Kind.COLLECTION_OF_BEANS; } else { log(logger, Type.DEBUG, "The property %s has not a bean type %s", name, classType); continue; } } } } } assert kind != null; boolean isMemo = method.getAnnotation(IsMemo.class) != null; String oldName = "null"; OldName oldNameAnno = method.getAnnotation(OldName.class); if (oldNameAnno != null) oldName = "\"" + oldNameAnno.value() + "\""; //create a property if (kind == Kind.BEAN || kind == Kind.COLLECTION_OF_BEANS) factory.addImport(returnType.getQualifiedSourceName()); String valueType = ""; JClassType classType = returnType.isClassOrInterface(); JPrimitiveType primitiveType = returnType.isPrimitive(); if (classType != null) valueType = classType.getQualifiedSourceName(); else if (primitiveType != null) { valueType = primitiveType.getQualifiedBoxedSourceName(); } sourceWriter.println("{ //Property %s", name); sourceWriter.indent(); sourceWriter.print("Index index ="); if (isIndexable) { if (indexName.isEmpty()) indexName = name; sourceWriter.println("new Index(\"%s\",\"%s\",new String[]{%s});", indexName, name, String.join(",", compositeIndexes)); } else sourceWriter.println("null;"); boolean useKeyAsString = anno != null ? (name.equals(anno.keyName()) ? anno.useKeyAsString() : false) : false; KeyOf keyOf = method.getAnnotation(KeyOf.class); if (keyOf != null) { IsEntity isEntity2 = keyOf.entity().getAnnotation(IsEntity.class); if (isEntity2 == null) { log(logger, Type.ERROR, AdapterEntityManager.KEY_OF_NO_ENTITY, method, keyOf, keyOf.entity(), IsEntity.class); continue; } useKeyAsString = isEntity2.useKeyAsString(); } boolean isHidden = isHidden(method, interfaz); sourceWriter.println( "Property<%s,%s> property = new Property<%s,%s>(\"%s\",%s,%s.class,%s,%s,%s,%s,index,%s){", type.getName(), valueType, type.getName(), valueType, name, oldName, returnType.getQualifiedSourceName(), typeOfCollectionString, kind != null ? "Kind." + kind.name() : "null", useKeyAsString + "", isMemo + "", isHidden + ""); sourceWriter.indent(); sourceWriter.println("@Override"); sourceWriter.println("public %s get(%s instance){", valueType, type.getName()); sourceWriter.indent(); sourceWriter.println("return ((%s)instance).%s();", implType.getName(), startsWithGet ? "get" + getterSetter : "is" + getterSetter); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println("@Override"); sourceWriter.println("public void set(%s instance, %s value){", type.getName(), valueType); sourceWriter.indent(); if (getSetter(implType, getterSetter, returnType) != null) sourceWriter.println("((%s)instance).%s(value);", implType.getName(), "set" + getterSetter); else { logger.log(Type.WARN, " Not found setter for " + getterSetter); sourceWriter.println("throw new RuntimeException(\"No such setter " + getterSetter + " \");"); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("};"); sourceWriter.println("PROPERTIES.put(\"%s\",property);", name); if (!oldName.equals("null")) { sourceWriter.println("PROPERTIES.put(%s,property);", oldName); } if (isIndexable) sourceWriter.println("INDEXES.add(index);"); sourceWriter.outdent(); sourceWriter.println("}"); log(logger, Type.DEBUG, SUCCESSFUL_ADD_PROPERTY, name + ":" + valueType, implType); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("public %s(){", className); sourceWriter.indent(); /* * boolean asyncReady, boolean autoGeneratedFlag, String keyName, boolean useKeyAsString, Class<T> type,Class<? extends T> implType, Map<String, Property<T,?>> mapAllProperties, Collection<Index> indexes) { super(type,implType,mapAllProperties); */ if (isEntity) sourceWriter .println(String.format("super(\"%s\",%s,%s,\"%s\",%s,%s.class,%s.class,PROPERTIES,INDEXES);", anno.aliasName().isEmpty() ? type.getName() : anno.aliasName(), anno.asyncReady(), anno.autoGeneratedKey(), anno.keyName(), anno.useKeyAsString(), type.getName(), implType.getName())); else { sourceWriter.println( String.format("super(%s.class,%s.class,PROPERTIES);", type.getName(), implType.getName())); } sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.println(); sourceWriter.println("@Override"); sourceWriter.println("public %s newInstance(){", type.getName()); sourceWriter.indent(); sourceWriter.println("return new %s();", implType.getName()); sourceWriter.outdent(); sourceWriter.println("}"); sourceWriter.outdent(); sourceWriter.println("}"); context.commit(logger, writer); return new BeanMetadata(type, className, implementation, isEntity); }
From source file:com.github.nmorel.gwtjackson.rebind.AbstractCreator.java
License:Apache License
/** * Build a {@link JSerializerType} that instantiate a {@link JsonSerializer} for the given type. If the type is a bean, * the implementation of {@link AbstractBeanJsonSerializer} will be created. * * @param type type/*from w w w . j a v a 2 s .c o m*/ * @param subtype true if the serializer is for a subtype * * @return the {@link JSerializerType}. Examples: * <ul> * <li>ctx.getIntegerSerializer()</li> * <li>new org.PersonBeanJsonSerializer()</li> * </ul> */ protected final JSerializerType getJsonSerializerFromType(JType type, boolean subtype) throws UnableToCompleteException, UnsupportedTypeException { JSerializerType.Builder builder = new JSerializerType.Builder().type(type); if (null != type.isWildcard()) { // For wildcard type, we use the base type to find the serializer. type = type.isWildcard().getBaseType(); } if (null != type.isRawType()) { // For raw type, we use the base type to find the serializer. type = type.isRawType().getBaseType(); } JTypeParameter typeParameter = type.isTypeParameter(); if (null != typeParameter) { // It's a type parameter like T in 'MyClass<T>' if (!subtype || typeParameter.getDeclaringClass() == getMapperInfo().get().getType()) { // The serializer is created for the main type so we use the serializer field declared for this type. return builder.instance(CodeBlock.builder() .add(String.format(TYPE_PARAMETER_SERIALIZER_FIELD_NAME, typeParameter.getOrdinal())) .add(".json()").build()).build(); } else { // There is no declared serializer so we use the base type to find a serializer. type = typeParameter.getBaseType(); } } Optional<MapperInstance> configuredSerializer = configuration.getSerializer(type); if (configuredSerializer.isPresent()) { // The type is configured in AbstractConfiguration. if (null != type.isParameterized() || null != type.isGenericType()) { JClassType[] typeArgs; if (null != type.isGenericType()) { typeArgs = type.isGenericType().asParameterizedByWildcards().getTypeArgs(); } else { typeArgs = type.isParameterized().getTypeArgs(); } ImmutableList.Builder<JSerializerType> parametersSerializerBuilder = ImmutableList.builder(); for (int i = 0; i < typeArgs.length; i++) { JSerializerType parameterSerializerType; if (configuredSerializer.get().getParameters().length <= i) { break; } if (MapperType.KEY_SERIALIZER == configuredSerializer.get().getParameters()[i]) { parameterSerializerType = getKeySerializerFromType(typeArgs[i]); } else { parameterSerializerType = getJsonSerializerFromType(typeArgs[i], subtype); } parametersSerializerBuilder.add(parameterSerializerType); } ImmutableList<JSerializerType> parametersSerializer = parametersSerializerBuilder.build(); builder.parameters(parametersSerializer); builder.instance( methodCallCodeWithJMapperTypeParameters(configuredSerializer.get(), parametersSerializer)); } else { // The serializer has no parameters. builder.instance(methodCallCode(configuredSerializer.get())); } return builder.build(); } if (typeOracle.isJavaScriptObject(type)) { // It's a JSO and the user didn't give a custom serializer. We use the default one. configuredSerializer = configuration.getSerializer(typeOracle.getJavaScriptObject()); return builder.instance(methodCallCode(configuredSerializer.get())).build(); } if (typeOracle.isEnum(type) || typeOracle.isEnumSupertype(type)) { configuredSerializer = configuration.getSerializer(typeOracle.getEnum()); return builder.instance(methodCallCode(configuredSerializer.get())).build(); } JArrayType arrayType = type.isArray(); if (null != arrayType) { Class arraySerializer; if (arrayType.getRank() == 1) { // One dimension array arraySerializer = ArrayJsonSerializer.class; } else if (arrayType.getRank() == 2) { // Two dimension array arraySerializer = Array2dJsonSerializer.class; } else if (arrayType.getRank() == 3) { // Three dimension array arraySerializer = Array3dJsonSerializer.class; } else { // More dimensions are not supported String message = "Arrays with 4 or more dimensions are not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); } JSerializerType parameterSerializerType = getJsonSerializerFromType(arrayType.getLeafType(), subtype); builder.parameters(ImmutableList.of(parameterSerializerType)); builder.instance(CodeBlock.builder() .add("$T.newInstance($L)", arraySerializer, parameterSerializerType.getInstance()).build()); return builder.build(); } if (null != type.isAnnotation()) { String message = "Annotations are not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); } JClassType classType = type.isClassOrInterface(); if (null != classType) { // The type is a class or interface and has no default serializer. We generate one. JClassType baseClassType = classType; JParameterizedType parameterizedType = classType.isParameterized(); if (null != parameterizedType) { // It's a bean with generics, we create a serializer based on generic type. baseClassType = parameterizedType.getBaseType(); } BeanJsonSerializerCreator beanJsonSerializerCreator = new BeanJsonSerializerCreator( logger.branch(Type.DEBUG, "Creating serializer for " + baseClassType.getQualifiedSourceName()), context, configuration, typeOracle, baseClassType); BeanJsonMapperInfo mapperInfo = beanJsonSerializerCreator.create(); // Generics and parameterized types serializers have no default constructor. They need serializers for each parameter. ImmutableList<? extends JType> typeParameters = getTypeParameters(classType, subtype); ImmutableList.Builder<JParameterizedSerializer> parametersSerializerBuilder = ImmutableList.builder(); ImmutableList.Builder<JSerializerType> parametersJsonSerializerBuilder = ImmutableList.builder(); for (JType argType : typeParameters) { JSerializerType jsonSerializer = getJsonSerializerFromType(argType, subtype); parametersSerializerBuilder.add(new JParameterizedSerializer( getKeySerializerFromType(argType, subtype, true), jsonSerializer)); parametersJsonSerializerBuilder.add(jsonSerializer); } builder.parameters(parametersJsonSerializerBuilder.build()); builder.beanMapper(true); builder.instance(constructorCallCode( ClassName.get(mapperInfo.getPackageName(), mapperInfo.getSimpleSerializerClassName()), parametersSerializerBuilder.build())); return builder.build(); } String message = "Type '" + type.getQualifiedSourceName() + "' is not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); }
From source file:com.github.nmorel.gwtjackson.rebind.AbstractCreator.java
License:Apache License
/** * Build a {@link JDeserializerType} that instantiate a {@link JsonSerializer} for the given type. If the type is a bean, * the implementation of {@link AbstractBeanJsonSerializer} will be created. * * @param type type//from w w w . jav a 2 s . c o m * @param subtype true if the deserializer is for a subtype * * @return the {@link JDeserializerType}. Examples: * <ul> * <li>ctx.getIntegerDeserializer()</li> * <li>new org .PersonBeanJsonDeserializer()</li> * </ul> */ protected final JDeserializerType getJsonDeserializerFromType(JType type, boolean subtype) throws UnableToCompleteException, UnsupportedTypeException { JDeserializerType.Builder builder = new JDeserializerType.Builder().type(type); if (null != type.isWildcard()) { // For wildcard type, we use the base type to find the deserializer. type = type.isWildcard().getBaseType(); } if (null != type.isRawType()) { // For raw type, we use the base type to find the deserializer. type = type.isRawType().getBaseType(); } JTypeParameter typeParameter = type.isTypeParameter(); if (null != typeParameter) { // It's a type parameter like T in 'MyClass<T>' if (!subtype || typeParameter.getDeclaringClass() == getMapperInfo().get().getType()) { // The deserializer is created for the main type so we use the deserializer field declared for this type. return builder.instance(CodeBlock.builder() .add(String.format(TYPE_PARAMETER_DESERIALIZER_FIELD_NAME, typeParameter.getOrdinal())) .add(".json()").build()).build(); } else { // There is no declared deserializer so we use the base type to find a deserializer. type = typeParameter.getBaseType(); } } if (typeOracle.isEnumSupertype(type)) { String message = "Type java.lang.Enum is not supported by deserialization"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); } Optional<MapperInstance> configuredDeserializer = configuration.getDeserializer(type); if (configuredDeserializer.isPresent()) { // The type is configured in AbstractConfiguration. if (null != type.isParameterized() || null != type.isGenericType()) { JClassType[] typeArgs; if (null != type.isGenericType()) { typeArgs = type.isGenericType().asParameterizedByWildcards().getTypeArgs(); } else { typeArgs = type.isParameterized().getTypeArgs(); } ImmutableList.Builder<JDeserializerType> parametersDeserializerBuilder = ImmutableList.builder(); for (int i = 0; i < typeArgs.length; i++) { JDeserializerType parameterDeserializerType; if (MapperType.KEY_DESERIALIZER == configuredDeserializer.get().getParameters()[i]) { parameterDeserializerType = getKeyDeserializerFromType(typeArgs[i]); } else { parameterDeserializerType = getJsonDeserializerFromType(typeArgs[i], subtype); } parametersDeserializerBuilder.add(parameterDeserializerType); } ImmutableList<JDeserializerType> parametersDeserializer = parametersDeserializerBuilder.build(); builder.parameters(parametersDeserializer); builder.instance(methodCallCodeWithJMapperTypeParameters(configuredDeserializer.get(), parametersDeserializer)); } else { // The deserializer has no parameters. builder.instance(methodCallCode(configuredDeserializer.get())); } return builder.build(); } if (typeOracle.isJavaScriptObject(type)) { // It's a JSO and the user didn't give a custom deserializer. We use the default one. configuredDeserializer = configuration.getDeserializer(typeOracle.getJavaScriptObject()); return builder.instance(methodCallCode(configuredDeserializer.get())).build(); } if (typeOracle.isEnum(type)) { configuredDeserializer = configuration.getDeserializer(typeOracle.getEnum()); return builder .instance( methodCallCodeWithClassParameters(configuredDeserializer.get(), ImmutableList.of(type))) .build(); } JArrayType arrayType = type.isArray(); if (null != arrayType) { TypeSpec arrayCreator; Class<?> arrayDeserializer; JType leafType = arrayType.getLeafType(); int arrayRank = arrayType.getRank(); if (arrayRank < 10) { arrayCreator = ArrayCreator.build(arrayType, arrayRank, leafType); arrayDeserializer = ArrayJsonDeserializer.class; } else { // More dimensions are not supported String message = "Arrays with 4 or more dimensions are not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); } JDeserializerType parameterDeserializerType = getJsonDeserializerFromType(leafType, subtype); builder.parameters(ImmutableList.of(parameterDeserializerType)); builder.instance(CodeBlock.builder().add("$T.newInstance($L, $L)", arrayDeserializer, parameterDeserializerType.getInstance(), arrayCreator).build()); return builder.build(); } if (null != type.isAnnotation()) { String message = "Annotations are not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); } JClassType classType = type.isClassOrInterface(); if (null != classType) { // The type is a class or interface and has no default deserializer. We generate one. JClassType baseClassType = classType; JParameterizedType parameterizedType = classType.isParameterized(); if (null != parameterizedType) { // It's a bean with generics, we create a deserializer based on generic type. baseClassType = parameterizedType.getBaseType(); } BeanJsonDeserializerCreator beanJsonDeserializerCreator = new BeanJsonDeserializerCreator( logger.branch(Type.DEBUG, "Creating deserializer for " + baseClassType.getQualifiedSourceName()), context, configuration, typeOracle, baseClassType); BeanJsonMapperInfo mapperInfo = beanJsonDeserializerCreator.create(); // Generics and parameterized types deserializers have no default constructor. They need deserializers for each parameter. ImmutableList<? extends JType> typeParameters = getTypeParameters(classType, subtype); ImmutableList.Builder<JParameterizedDeserializer> parametersDeserializerBuilder = ImmutableList .builder(); ImmutableList.Builder<JDeserializerType> parametersJsonDeserializerBuilder = ImmutableList.builder(); for (JType argType : typeParameters) { JDeserializerType jsonDeserializer = getJsonDeserializerFromType(argType, subtype); parametersDeserializerBuilder.add(new JParameterizedDeserializer( getKeyDeserializerFromType(argType, subtype, true), jsonDeserializer)); parametersJsonDeserializerBuilder.add(jsonDeserializer); } builder.parameters(parametersJsonDeserializerBuilder.build()); builder.beanMapper(true); builder.instance(constructorCallCode( ClassName.get(mapperInfo.getPackageName(), mapperInfo.getSimpleDeserializerClassName()), parametersDeserializerBuilder.build())); return builder.build(); } String message = "Type '" + type.getQualifiedSourceName() + "' is not supported"; logger.log(TreeLogger.Type.WARN, message); throw new UnsupportedTypeException(message); }
From source file:com.github.nmorel.gwtjackson.rebind.JacksonTypeOracle.java
License:Apache License
public JType replaceType(TreeLogger logger, JType type, Annotation deserializeAs) throws UnableToCompleteException { JClassType classType = type.isClassOrInterface(); if (null == classType) { return type; }/*from w w w .ja va 2s. co m*/ Optional<JClassType> typeAs = getClassFromJsonDeserializeAnnotation(logger, deserializeAs, "as"); Optional<JClassType> keyAs = getClassFromJsonDeserializeAnnotation(logger, deserializeAs, "keyAs"); Optional<JClassType> contentAs = getClassFromJsonDeserializeAnnotation(logger, deserializeAs, "contentAs"); if (!typeAs.isPresent() && !keyAs.isPresent() && !contentAs.isPresent()) { return type; } JArrayType arrayType = type.isArray(); if (null != arrayType) { if (contentAs.isPresent()) { return typeOracle.getArrayType(contentAs.get()); } else if (typeAs.isPresent()) { return typeOracle.getArrayType(typeAs.get()); } else { return classType; } } JParameterizedType parameterizedType = type.isParameterized(); if (null != parameterizedType) { JGenericType genericType; if (typeAs.isPresent()) { genericType = typeAs.get().isGenericType(); } else { genericType = parameterizedType.getBaseType(); } if (!keyAs.isPresent() && !contentAs.isPresent()) { return typeOracle.getParameterizedType(genericType, parameterizedType.getTypeArgs()); } else if (contentAs.isPresent() && isIterable(parameterizedType)) { return typeOracle.getParameterizedType(genericType, new JClassType[] { contentAs.get() }); } else if (isMap(parameterizedType)) { JClassType key; if (keyAs.isPresent()) { key = keyAs.get(); } else { key = parameterizedType.getTypeArgs()[0]; } JClassType content; if (contentAs.isPresent()) { content = contentAs.get(); } else { content = parameterizedType.getTypeArgs()[1]; } return typeOracle.getParameterizedType(genericType, new JClassType[] { key, content }); } } if (typeAs.isPresent()) { return typeAs.get(); } return type; }
From source file:com.google.code.gwt.database.rebind.GeneratorUtils.java
License:Apache License
/** * Returns the name of the specified type, which can be safely emitted in the * generated sourcecode./*from w w w .jav a 2s. c om*/ */ public String getClassName(JType type) { if (type.isPrimitive() != null) { return type.isPrimitive().getSimpleSourceName(); } StringBuilder sb = new StringBuilder(shortenName(type.getQualifiedSourceName())); if (type.isParameterized() != null && type.isParameterized().getTypeArgs().length > 0) { sb.append('<'); boolean needComma = false; for (JType typeArg : type.isParameterized().getTypeArgs()) { if (needComma) { sb.append(", "); } else { needComma = true; } sb.append(shortenName(typeArg.getParameterizedQualifiedSourceName())); } sb.append('>'); } return sb.toString(); }
From source file:com.google.code.gwt.database.rebind.GeneratorUtils.java
License:Apache License
/** * Returns the (first) Type parameter of the specified type. *//* w w w .ja va 2s.c o m*/ public String getTypeParameter(JType type) throws UnableToCompleteException { JClassType[] typeArgs = type.isParameterized() != null ? type.isParameterized().getTypeArgs() : null; if (typeArgs == null || typeArgs.length == 0) { logger.log(TreeLogger.ERROR, "Expected a type parameter on the type " + type.getQualifiedSourceName()); throw new UnableToCompleteException(); } return shortenName(typeArgs[0].getQualifiedSourceName()); }
From source file:com.google.code.gwt.database.rebind.ServiceMethodCreator.java
License:Apache License
/** * Generates an iterating <code>tx.executeSql(...);</code> call statement. * /*from www. j av a2 s. com*/ * @throws UnableToCompleteException */ protected void generateExecuteIteratedSqlStatements() throws UnableToCompleteException { if (StringUtils.isNotEmpty(foreach)) { // Generate code to loop over a collection to create a tx.executeSql() // call for each item. // Ensure no parameters are specified on the service method named '_': if (!"_".equals(GeneratorUtils.getVariableName("_", service.getParameters()))) { logger.log(TreeLogger.ERROR, "The service method cannot apply a parameter named '_' when " + "the 'foreach' attribute is also specified on the @Update " + "annotation"); throw new UnableToCompleteException(); } // Find the types, parameters, assert not-nulls, etc.: JType collection = GeneratorUtils.findType(foreach, service.getParameters()); String forEachType = null; if (collection == null) { logger.log(TreeLogger.WARN, "no parameter on the service method named '" + foreach + "' found. Using Object as the type for the loop variable '_'"); } else if (collection.isParameterized() != null) { forEachType = genUtils.getTypeParameter(collection); } else if (collection.isArray() != null) { forEachType = genUtils.getClassName(collection.isArray().getComponentType()); } if (forEachType == null) { forEachType = "Object"; } sw.println("for (" + forEachType + " _ : " + foreach + ") {"); sw.indent(); generateExecuteSqlStatement(); sw.outdent(); sw.println("}"); } }
From source file:com.google.web.bindery.autobean.gwt.rebind.AutoBeanFactoryGenerator.java
License:Apache License
/** * Flattens a parameterized type into a simple list of types. *//*from www . j av a2s . co m*/ private void createTypeList(List<JType> accumulator, JType type) { accumulator.add(type); JParameterizedType hasParams = type.isParameterized(); if (hasParams != null) { for (JClassType arg : hasParams.getTypeArgs()) { createTypeList(accumulator, arg); } } }