List of usage examples for com.google.gwt.core.ext.typeinfo JType isEnum
JEnumType isEnum();
null if it is not. 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();//from w ww. j a v a 2s. com 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.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;/*from w w w .jav a 2 s . c o m*/ 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.JacksonTypeOracle.java
License:Apache License
public boolean isEnum(JType type) { return null != type.isEnum(); }
From source file:com.hiramchirino.restygwt.rebind.JsonEncoderDecoderInstanceLocator.java
License:Apache License
private String encodeDecodeExpression(JType type, String expression, Style style, String encoderMethod, String mapMethod, String setMethod, String listMethod) throws UnableToCompleteException { if (null != type.isEnum()) { return type.getQualifiedSourceName() + ".valueOf(" + encodeDecodeExpression(STRING_TYPE, expression, style, encoderMethod, mapMethod, setMethod, listMethod); }//from w w w . java 2s . c o m String encoderDecoder = getEncoderDecoder(type, logger); if (encoderDecoder != null) { return encoderDecoder + "." + encoderMethod + "(" + expression + ")"; } JClassType clazz = type.isClassOrInterface(); if (isCollectionType(clazz)) { JParameterizedType parameterizedType = type.isParameterized(); if (parameterizedType == null || parameterizedType.getTypeArgs() == null) { error("Collection types must be parameterized."); } JClassType[] types = parameterizedType.getTypeArgs(); if (parameterizedType.isAssignableTo(MAP_TYPE)) { if (types.length != 2) { error("Map must define two and only two type parameters"); } if (types[0] != STRING_TYPE) { error("Map's first type parameter must be of type String"); } encoderDecoder = getEncoderDecoder(types[1], logger); if (encoderDecoder != null) { return mapMethod + "(" + expression + ", " + encoderDecoder + ", " + JSON_CLASS + ".Style." + style.name() + ")"; } } else if (parameterizedType.isAssignableTo(SET_TYPE)) { if (types.length != 1) { error("Set must define one and only one type parameter"); } encoderDecoder = getEncoderDecoder(types[0], logger); if (encoderDecoder != null) { return setMethod + "(" + expression + ", " + encoderDecoder + ")"; } } else if (parameterizedType.isAssignableFrom(LIST_TYPE)) { if (types.length != 1) { error("List must define one and only one type parameter"); } encoderDecoder = getEncoderDecoder(types[0], logger); debug("type encoder for: " + types[0] + " is " + encoderDecoder); if (encoderDecoder != null) { return listMethod + "(" + expression + ", " + encoderDecoder + ")"; } } } error("Do not know how to encode/decode " + type); return null; }
From source file:com.vaadin.server.widgetsetutils.metadata.ConnectorBundle.java
License:Apache License
private void addSerializeSupport(TreeLogger logger, JType type) throws UnableToCompleteException { hasSerializeSupport.add(type);/*from w ww. j a v a 2 s . com*/ JParameterizedType parametrized = type.isParameterized(); if (parametrized != null) { for (JClassType parameterType : parametrized.getTypeArgs()) { setNeedsSerialize(parameterType); } } if (serializationHandledByFramework(type)) { return; } JClassType customSerializer = customSerializers.get(type); JClassType typeAsClass = type.isClass(); JEnumType enumType = type.isEnum(); JArrayType arrayType = type.isArray(); if (customSerializer != null) { logger.log(Type.INFO, "Will serialize " + type + " using " + customSerializer.getName()); setSerializer(type, new CustomSerializer(customSerializer)); } else if (arrayType != null) { logger.log(Type.INFO, "Will serialize " + type + " as an array"); setSerializer(type, new ArraySerializer(arrayType)); setNeedsSerialize(arrayType.getComponentType()); } else if (enumType != null) { logger.log(Type.INFO, "Will serialize " + type + " as an enum"); setSerializer(type, new EnumSerializer(enumType)); } else if (typeAsClass != null) { // Bean checkSerializable(logger, typeAsClass); logger.log(Type.INFO, "Will serialize " + type + " as a bean"); JClassType needsSuperClass = typeAsClass; while (needsSuperClass != null) { if (needsSuperClass.isPublic()) { setNeedsSuperclass(needsSuperClass); } needsSuperClass = needsSuperClass.getSuperclass(); } setNeedsGwtConstructor(typeAsClass); for (Property property : getProperties(typeAsClass)) { setNeedsProperty(property); JType propertyType = property.getPropertyType(); setNeedsSerialize(propertyType); } } }
From source file:fr.putnami.pwt.core.model.rebind.ModelCreator.java
License:Open Source License
private void createSubModels(TreeLogger logger, GeneratorContext context) { for (JType jType : this.imports) { if (jType == null) { continue; }//from ww w .j av a2 s . co m if (jType.isEnum() != null) { continue; } if (ModelCreator.DISCARD_MODEL_TYPES.contains(jType.getQualifiedSourceName())) { continue; } if (jType instanceof JClassType) { ModelCreator creator = new ModelCreator((JClassType) jType); String subModelType = creator.create(logger, context); this.subModels.put(jType, subModelType); } } }
From source file:org.cruxframework.crux.core.rebind.rest.CruxRestProxyCreatorFromServerMetadata.java
License:Apache License
private boolean isTypesCompatiblesForSerialization(Class<?> class1, JType jType) { if (jType.isEnum() != null) { return isEnumTypesCompatibles(class1, jType.isEnum()); } else if (JClassUtils.isSimpleType(jType)) { return (getAllowedType(jType).contains(class1)); } else {/* w ww. j av a 2 s . c o m*/ JClassType classOrInterface = jType.isClassOrInterface(); if (classOrInterface != null) { if (javascriptObjectType.isAssignableFrom(classOrInterface)) { if (classOrInterface.getQualifiedSourceName().equals(JsArray.class.getCanonicalName())) { boolean validArray = false; if (class1.isArray()) { Class<?> componentType = class1.getComponentType(); JClassType jClassType = jType.isClassOrInterface(); validArray = jClassType != null && isTypesCompatiblesForSerialization(componentType, JClassUtils.getTypeArgForGenericType(jClassType)); } return validArray || (List.class.isAssignableFrom(class1)) || (Set.class.isAssignableFrom(class1)); } else { return true; } } } } //Use a jsonEncorer implicitly return true; }
From source file:org.cruxframework.crux.core.rebind.rest.JSonSerializerProxyCreator.java
License:Apache License
private void generateDecodeStringForJsonFriendlyType(SourcePrinter srcWriter, JType objectType, String jsonValueVar, String resultObjectVar) { try {//from www. j a va2 s . co m if (objectType.getQualifiedSourceName().equals("java.lang.String") || objectType.isEnum() != null) { srcWriter.println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType( jsonValueVar + ".isString().stringValue()", objectType) + ";"); } else if (objectType.getQualifiedSourceName().equals("java.sql.Date")) { logger.log(TreeLogger.Type.WARN, "We recommend to avoid type [" + objectType.getParameterizedQualifiedSourceName() + "]: " + "there are some known issues with respect to Jackson timezone handling, partly due to design of this class."); srcWriter .println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType( jsonValueVar + ".isString().stringValue().replace(\"/\",\"-\")", objectType) + ";"); } else { srcWriter.println(resultObjectVar + " = " + JClassUtils.getParsingExpressionForSimpleType(jsonValueVar + ".toString()", objectType) + ";"); } } catch (NotFoundException e) { throw new CruxGeneratorException("Type [" + objectType.getParameterizedQualifiedSourceName() + "] can not be deserialized by JsonEncoder. " + "Error Interpreting object type.", e); } }
From source file:org.cruxframework.crux.core.rebind.rest.JSonSerializerProxyCreator.java
License:Apache License
private void generateEncodeStringForJsonFriendlyType(SourcePrinter srcWriter, JType objectType, String objectVar, String resultJSONValueVar) { if (objectType.getQualifiedSourceName().equals(String.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ");"); } else if ((objectType == JPrimitiveType.BYTE) || (objectType.getQualifiedSourceName().equals(Byte.class.getCanonicalName())) || (objectType == JPrimitiveType.SHORT) || (objectType.getQualifiedSourceName().equals(Short.class.getCanonicalName())) || (objectType == JPrimitiveType.INT) || (objectType.getQualifiedSourceName().equals(Integer.class.getCanonicalName())) || (objectType == JPrimitiveType.LONG) || (objectType.getQualifiedSourceName().equals(Long.class.getCanonicalName())) || (objectType == JPrimitiveType.FLOAT) || (objectType.getQualifiedSourceName().equals(Float.class.getCanonicalName())) || (objectType == JPrimitiveType.DOUBLE) || (objectType.getQualifiedSourceName().equals(Double.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ");"); } else if (objectType.getQualifiedSourceName().equals(Date.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ".getTime());"); } else if (objectType.getQualifiedSourceName().equals(java.sql.Date.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONNumber(" + objectVar + ".getTime());"); } else if ((objectType == JPrimitiveType.BOOLEAN) || (objectType.getQualifiedSourceName().equals(Boolean.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = JSONBoolean.getInstance(" + objectVar + ");"); } else if ((objectType == JPrimitiveType.CHAR) || (objectType.getQualifiedSourceName().equals(Character.class.getCanonicalName()))) { srcWriter.println(resultJSONValueVar + " = new JSONString(\"\"+" + objectVar + ");"); } else if (objectType.isEnum() != null) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ".toString());"); } else if (objectType.getQualifiedSourceName().equals(BigInteger.class.getCanonicalName()) || objectType.getQualifiedSourceName().equals(BigDecimal.class.getCanonicalName())) { srcWriter.println(resultJSONValueVar + " = new JSONString(" + objectVar + ".toString());"); } else {//from ww w. j a v a 2s .co m throw new CruxGeneratorException("Type [" + objectType.getParameterizedQualifiedSourceName() + "] can not be serialized by JsonEncoder. " + "Error Interpreting object type."); } }
From source file:org.cruxframework.crux.core.utils.JClassUtils.java
License:Apache License
/** * //from w w w.j ava 2s. com * @param valueVariable * @param expectedType * @return * @throws NotFoundException */ public static String getParsingExpressionForSimpleType(String valueVariable, JType expectedType) throws NotFoundException { if (expectedType == JPrimitiveType.INT || Integer.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Integer.parseInt(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.SHORT || Short.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Short.parseShort(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.LONG || Long.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Long.parseLong(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.BYTE || Byte.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Byte.parseByte(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.FLOAT || Float.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Float.parseFloat(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.DOUBLE || Double.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Double.parseDouble(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.BOOLEAN || Boolean.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "Boolean.parseBoolean(" + valueVariable + ")"; } else if (expectedType == JPrimitiveType.CHAR || Character.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return valueVariable + ".charAt(1)"; } else if (Date.class.getCanonicalName().equals(expectedType.getQualifiedSourceName())) { return "new " + Date.class.getCanonicalName() + "(Long.parseLong(" + valueVariable + "))"; } else if (expectedType.isEnum() != null) { return expectedType.getQualifiedSourceName() + ".valueOf(" + valueVariable + ")"; } else { JClassType stringType = ((JClassType) expectedType).getOracle().getType(String.class.getName()); if (stringType.isAssignableFrom((JClassType) expectedType)) { return valueVariable; } if (((JClassType) expectedType).findConstructor(new JType[] { stringType }) != null) { return "new " + expectedType.getQualifiedSourceName() + "(" + valueVariable + ")"; } JMethod valueOfMethod = ((JClassType) expectedType).findMethod("valueOf", new JType[] { stringType }); if (valueOfMethod != null && valueOfMethod.isStatic()) { return expectedType.getQualifiedSourceName() + ".valueOf(" + valueVariable + ")"; } JMethod fromStringMethod = ((JClassType) expectedType).findMethod("fromString", new JType[] { stringType }); if (fromStringMethod != null && fromStringMethod.isStatic()) { return expectedType.getQualifiedSourceName() + ".fromString(" + valueVariable + ")"; } } return null; }