List of usage examples for java.lang Class isEnum
public boolean isEnum()
From source file:org.apache.myfaces.ov2021.application.ApplicationImpl.java
@SuppressWarnings("unchecked") private Converter internalCreateConverter(final Class<?> targetClass) { // Locate a Converter registered for the target class itself. Object converterClassOrClassName = _converterTargetClassToConverterClassMap.get(targetClass); // Locate a Converter registered for interfaces that are // implemented by the target class (directly or indirectly). // Skip if class is String, for performance reasons // (save 3 additional lookups over a concurrent map per request). if (converterClassOrClassName == null && !String.class.equals(targetClass)) { final Class<?> interfaces[] = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0, len = interfaces.length; i < len; i++) { // search all superinterfaces for a matching converter, // create it final Converter converter = internalCreateConverter(interfaces[i]); if (converter != null) { return converter; }//from w w w.ja v a2 s . c o m } } } // Get EnumConverter for enum classes with no special converter, check // here as recursive call with java.lang.Enum will not work if (converterClassOrClassName == null && targetClass.isEnum()) { converterClassOrClassName = _converterTargetClassToConverterClassMap.get(Enum.class); } if (converterClassOrClassName != null) { try { Class<? extends Converter> converterClass = null; if (converterClassOrClassName instanceof Class<?>) { converterClass = (Class<? extends Converter>) converterClassOrClassName; } else if (converterClassOrClassName instanceof String) { converterClass = ClassUtils.simpleClassForName((String) converterClassOrClassName); _converterTargetClassToConverterClassMap.put(targetClass, converterClass); } else { //object stored in the map for this id is an invalid type. remove it and return null _converterTargetClassToConverterClassMap.remove(targetClass); } Converter converter = null; // check cached constructor information if (!_noArgConstructorConverterClasses.contains(converterClass)) { // the converter class either supports the one-arg constructor // or has never been processed before try { // look for a constructor that takes a single Class object // See JSF 1.2 javadoc for Converter Constructor<? extends Converter> constructor = converterClass .getConstructor(new Class[] { Class.class }); converter = constructor.newInstance(new Object[] { targetClass }); } catch (Exception e) { // the constructor does not exist // add the class to the no-arg constructor classes cache _noArgConstructorConverterClasses.add(converterClass); // use no-arg constructor converter = converterClass.newInstance(); } } else { // use no-arg constructor converter = converterClass.newInstance(); } setConverterProperties(converterClass, converter); return converter; } catch (Exception e) { log.log(Level.SEVERE, "Could not instantiate converter " + converterClassOrClassName.toString(), e); throw new FacesException("Could not instantiate converter: " + converterClassOrClassName.toString(), e); } } // locate converter for primitive types if (targetClass == Long.TYPE) { return internalCreateConverter(Long.class); } else if (targetClass == Boolean.TYPE) { return internalCreateConverter(Boolean.class); } else if (targetClass == Double.TYPE) { return internalCreateConverter(Double.class); } else if (targetClass == Byte.TYPE) { return internalCreateConverter(Byte.class); } else if (targetClass == Short.TYPE) { return internalCreateConverter(Short.class); } else if (targetClass == Integer.TYPE) { return internalCreateConverter(Integer.class); } else if (targetClass == Float.TYPE) { return internalCreateConverter(Float.class); } else if (targetClass == Character.TYPE) { return internalCreateConverter(Character.class); } // Locate a Converter registered for the superclass (if any) of the // target class, // recursively working up the inheritance hierarchy. Class<?> superClazz = targetClass.getSuperclass(); return superClazz != null ? internalCreateConverter(superClazz) : null; }
From source file:org.apache.myfaces.application.ApplicationImpl.java
@SuppressWarnings("unchecked") private Converter internalCreateConverter(final Class<?> targetClass) { // Locate a Converter registered for the target class itself. Object converterClassOrClassName = _converterTargetClassToConverterClassMap.get(targetClass); // Locate a Converter registered for interfaces that are // implemented by the target class (directly or indirectly). // Skip if class is String, for performance reasons // (save 3 additional lookups over a concurrent map per request). if (converterClassOrClassName == null && !String.class.equals(targetClass)) { final Class<?> interfaces[] = targetClass.getInterfaces(); if (interfaces != null) { for (int i = 0, len = interfaces.length; i < len; i++) { // search all superinterfaces for a matching converter, // create it final Converter converter = internalCreateConverter(interfaces[i]); if (converter != null) { return converter; }/*from ww w. ja va 2s . c om*/ } } } // Get EnumConverter for enum classes with no special converter, check // here as recursive call with java.lang.Enum will not work if (converterClassOrClassName == null && targetClass.isEnum()) { converterClassOrClassName = _converterTargetClassToConverterClassMap.get(Enum.class); } if (converterClassOrClassName != null) { try { Class<? extends Converter> converterClass = null; if (converterClassOrClassName instanceof Class<?>) { converterClass = (Class<? extends Converter>) converterClassOrClassName; } else if (converterClassOrClassName instanceof String) { converterClass = ClassUtils.simpleClassForName((String) converterClassOrClassName); _converterTargetClassToConverterClassMap.put(targetClass, converterClass); } else { //object stored in the map for this id is an invalid type. remove it and return null _converterTargetClassToConverterClassMap.remove(targetClass); } Converter converter = null; // check cached constructor information if (!_noArgConstructorConverterClasses.contains(converterClass)) { // the converter class either supports the one-arg constructor // or has never been processed before try { // look for a constructor that takes a single Class object // See JSF 1.2 javadoc for Converter Constructor<? extends Converter> constructor = converterClass .getConstructor(new Class[] { Class.class }); converter = constructor.newInstance(new Object[] { targetClass }); } catch (Exception e) { // the constructor does not exist // add the class to the no-arg constructor classes cache _noArgConstructorConverterClasses.add(converterClass); // use no-arg constructor converter = createConverterInstance(converterClass); } } else { // use no-arg constructor converter = createConverterInstance(converterClass); } setConverterProperties(converterClass, converter); return converter; } catch (Exception e) { log.log(Level.SEVERE, "Could not instantiate converter " + converterClassOrClassName.toString(), e); throw new FacesException("Could not instantiate converter: " + converterClassOrClassName.toString(), e); } } // locate converter for primitive types if (targetClass == Long.TYPE) { return internalCreateConverter(Long.class); } else if (targetClass == Boolean.TYPE) { return internalCreateConverter(Boolean.class); } else if (targetClass == Double.TYPE) { return internalCreateConverter(Double.class); } else if (targetClass == Byte.TYPE) { return internalCreateConverter(Byte.class); } else if (targetClass == Short.TYPE) { return internalCreateConverter(Short.class); } else if (targetClass == Integer.TYPE) { return internalCreateConverter(Integer.class); } else if (targetClass == Float.TYPE) { return internalCreateConverter(Float.class); } else if (targetClass == Character.TYPE) { return internalCreateConverter(Character.class); } // Locate a Converter registered for the superclass (if any) of the // target class, // recursively working up the inheritance hierarchy. Class<?> superClazz = targetClass.getSuperclass(); return superClazz != null ? internalCreateConverter(superClazz) : null; }
From source file:org.apache.axis2.datasource.jaxb.JAXBDSContext.java
/** * The root element being read is defined by schema/JAXB; however its contents are known by * schema/JAXB. Therefore we use unmarshal by the declared type (This method is used to * unmarshal rpc elements)//from www.j av a 2s . com * * @param u Unmarshaller * @param reader XMLStreamReader * @param type Class * @return Object * @throws WebServiceException */ public static Object unmarshalByType(final Unmarshaller u, final XMLStreamReader reader, final Class type, final boolean isList, final JAXBUtils.CONSTRUCTION_TYPE ctype) throws WebServiceException { if (DEBUG_ENABLED) { log.debug("Invoking unmarshalByType."); log.debug(" type = " + type); log.debug(" isList = " + isList); log.debug(" ctype = " + ctype); } return AccessController.doPrivileged(new PrivilegedAction() { public Object run() { try { // Unfortunately RPC is type based. Thus a // declared type must be used to unmarshal the xml. Object jaxb; if (!isList) { // case: We are not unmarshalling an xsd:list but an Array. if (type.isArray()) { // If the context is created using package // we will not have common arrays or type array in the context // but there is not much we can do about it so seralize it as // usual if (ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CONTEXT_PATH) { if (DEBUG_ENABLED) { log.debug("Unmarshal Array via BY_CONTEXT_PATH approach"); } jaxb = u.unmarshal(reader, type); } // list on client array on server, Can happen only in start from java // case. else if ((ctype == JAXBUtils.CONSTRUCTION_TYPE.BY_CLASS_ARRAY)) { // The type could be any Object or primitive //process primitives first //first verify if we have a primitive type associated in the array. //array could be single dimension or multi dimension. Class cType = type.getComponentType(); while (cType.isArray()) { cType = cType.getComponentType(); } if (cType.isPrimitive()) { if (DEBUG_ENABLED) { log.debug("Unmarshal Array of primitive via BY_CLASS_ARRAY approach"); } jaxb = u.unmarshal(reader, type); } // process non primitive // I will first unmarshall the xmldata to a String[] // Then use the unmarshalled jaxbElement to create // proper type Object Array. else { if (DEBUG_ENABLED) { log.debug("Unmarshal Array of non-primitive via BY_CLASS_ARRAY approach"); } jaxb = unmarshalArray(reader, u, type); } } else { if (DEBUG_ENABLED) { log.debug("Unmarshal Array"); } jaxb = u.unmarshal(reader, type); } } else if (type.isEnum()) { // When JAXBContext is created using a context path, it will not // include Enum classes. // These classes have @XmlEnum annotation but not @XmlType/@XmlElement, // so the user will see MarshallingEx, class not known to ctxt. // // This is a jax-b defect, for now this fix is in place to pass CTS. // This only fixes the // situation where the enum is the top-level object (e.g., message-part // in rpc-lit scenario) // // Sample of what enum looks like: // @XmlEnum public enum EnumString { // @XmlEnumValue("String1") STRING_1("String1"), // @XmlEnumValue("String2") STRING_2("String2"); // // public static getValue(String){} <-- resolves a "value" to an emum // object // ... } if (DEBUG_ENABLED) { log.debug("Unmarshalling " + type.getName() + " as Enum"); } JAXBElement<String> enumValue = u.unmarshal(reader, XmlEnumUtils.getConversionType(type)); if (enumValue != null) { jaxb = XmlEnumUtils.fromValue(type, enumValue.getValue()); } else { jaxb = null; } } //Normal case: We are not unmarshalling a xsd:list or Array else { if (DEBUG_ENABLED) { log.debug("Unmarshalling normal case (not array, not xsd:list, not enum)"); } jaxb = u.unmarshal(reader, type); } } else { // If this is an xsd:list, we need to return the appropriate // list or array (see NOTE above) // First unmarshal as a String //Second convert the String into a list or array if (DEBUG_ENABLED) { log.debug("Unmarshalling xsd:list"); } jaxb = unmarshalAsListOrArray(reader, u, type); } if (log.isDebugEnabled()) { Class cls; if (jaxb == null) { if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning null object"); } } else if (jaxb instanceof JAXBElement) { JAXBElement jbe = (JAXBElement) jaxb; if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning JAXBElement"); log.debug(" Class = " + jbe.getDeclaredType()); log.debug(" QName = " + jbe.getName()); } } else { if (DEBUG_ENABLED) { log.debug("End unmarshalByType returning " + jaxb.getClass()); } } } return jaxb; } catch (OMException e) { throw e; } catch (Throwable t) { throw new OMException(t); } } }); }
From source file:jp.co.acroquest.jsonic.JSON.java
/** * Converts Map, List, Number, String, Boolean or null to other Java Objects after parsing. * //from w w w . j av a 2 s. c o m * @param context current context. * @param value null or the instance of Map, List, Number, String or Boolean. * @param cls class for converting * @param type generics type for converting. type equals to c if not generics. * @return a converted object * @throws Exception if conversion failed. */ @SuppressWarnings("unchecked") protected <T> T postparse(Context context, Object value, Class<? extends T> cls, Type type) throws Exception { Converter c = null; if (value == null) { if (!cls.isPrimitive()) { c = NullConverter.INSTANCE; } } else { JSONHint hint = context.getHint(); if (hint == null) { // no handle } else if (hint.serialized() && hint != context.skipHint) { c = FormatConverter.INSTANCE; } else if (Serializable.class.equals(hint.type())) { c = SerializableConverter.INSTANCE; } else if (String.class.equals(hint.type())) { c = StringSerializableConverter.INSTANCE; } } if (c == null) { if (value != null && cls.equals(type) && cls.isAssignableFrom(value.getClass())) { c = PlainConverter.INSTANCE; } else { c = CONVERT_MAP.get(cls); } } if (c == null) { if (context.hasMemberCache(cls)) { c = ObjectConverter.INSTANCE; } else if (Properties.class.isAssignableFrom(cls)) { c = PropertiesConverter.INSTANCE; } else if (Map.class.isAssignableFrom(cls)) { c = MapConverter.INSTANCE; } else if (Collection.class.isAssignableFrom(cls)) { c = CollectionConverter.INSTANCE; } else if (cls.isArray()) { c = ArrayConverter.INSTANCE; } else if (cls.isEnum()) { c = EnumConverter.INSTANCE; } else if (Date.class.isAssignableFrom(cls)) { c = DateConverter.INSTANCE; } else if (Calendar.class.isAssignableFrom(cls)) { c = CalendarConverter.INSTANCE; } else if (CharSequence.class.isAssignableFrom(cls)) { c = CharSequenceConverter.INSTANCE; } else if (Appendable.class.isAssignableFrom(cls)) { c = AppendableConverter.INSTANCE; } else if (cls.equals(ClassUtil.findClass("java.net.InetAddress"))) { c = InetAddressConverter.INSTANCE; } else if (java.sql.Array.class.isAssignableFrom(cls) || Struct.class.isAssignableFrom(cls)) { c = NullConverter.INSTANCE; } else { c = ObjectConverter.INSTANCE; } } if (c != null) { return (T) c.convert(this, context, value, cls, type); } else { throw new UnsupportedOperationException(); } }
From source file:com.github.reinert.jjschema.JsonSchemaGenerator.java
protected <T> ObjectNode generatePropertySchema(Class<T> type, Method method, Field field) throws TypeException { Class<?> returnType = method != null ? method.getReturnType() : field.getType(); AccessibleObject propertyReflection = field != null ? field : method; SchemaIgnore ignoreAnn = propertyReflection.getAnnotation(SchemaIgnore.class); if (ignoreAnn != null) return null; ObjectNode schema = createInstance(); JsonManagedReference refAnn = propertyReflection.getAnnotation(JsonManagedReference.class); if (refAnn != null) { ManagedReference fowardReference; Class<?> genericClass; Class<?> collectionClass; if (Collection.class.isAssignableFrom(returnType)) { if (method != null) { ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); genericClass = (Class<?>) genericType.getActualTypeArguments()[0]; } else { genericClass = field.getClass(); }//from ww w . j a v a2s . c om collectionClass = returnType; } else { genericClass = returnType; } fowardReference = new ManagedReference(type, refAnn.value(), genericClass); if (!isFowardReferencePiled(fowardReference)) { pushFowardReference(fowardReference); } else // if (isBackwardReferencePiled(fowardReference)) { boolean a = pullFowardReference(fowardReference); boolean b = pullBackwardReference(fowardReference); //return null; return createRefSchema("#"); } } JsonBackReference backRefAnn = propertyReflection.getAnnotation(JsonBackReference.class); if (backRefAnn != null) { ManagedReference backReference; Class<?> genericClass; Class<?> collectionClass; if (Collection.class.isAssignableFrom(returnType)) { ParameterizedType genericType = (ParameterizedType) method.getGenericReturnType(); genericClass = (Class<?>) genericType.getActualTypeArguments()[0]; collectionClass = returnType; } else { genericClass = returnType; } backReference = new ManagedReference(genericClass, backRefAnn.value(), type); if (isFowardReferencePiled(backReference) && !isBackwardReferencePiled(backReference)) { pushBackwardReference(backReference); } else { // pullFowardReference(backReference); // pullBackwardReference(backReference); return null; } } if (Collection.class.isAssignableFrom(returnType)) { processPropertyCollection(method, field, schema); } else { schema = generateSchema(returnType); } // Check the field annotations, if the get method references a field, or the // method annotations on the other hand, and processSchemaProperty them to // the JsonSchema object Attributes attrs = propertyReflection.getAnnotation(Attributes.class); if (attrs != null) { processSchemaProperty(schema, attrs); // The declaration of $schema is only necessary at the root object schema.remove("$schema"); } // Check if the Nullable annotation is present, and if so, add 'null' to type attr Nullable nullable = propertyReflection.getAnnotation(Nullable.class); if (nullable != null) { if (returnType.isEnum()) { ((ArrayNode) schema.get("enum")).add("null"); } else { String oldType = schema.get(TAG_TYPE).asText(); ArrayNode typeArray = schema.putArray(TAG_TYPE); typeArray.add(oldType); typeArray.add("null"); } } return schema; }
From source file:org.hellojavaer.testcase.generator.TestCaseGenerator.java
@SuppressWarnings({ "unchecked", "rawtypes" }) private static <T> T produceBean(Class<T> clazz, ControlParam countrolParam, Stack<Class> parseClassList) { try {/*from w ww . j a va2 s .c o m*/ T item = clazz.newInstance(); for (PropertyDescriptor pd : BeanUtils.getPropertyDescriptors(clazz)) { Method writeMethod = pd.getWriteMethod(); if (writeMethod == null || pd.getReadMethod() == null || // countrolParam.getExcludeFieldList() != null && countrolParam.getExcludeFieldList().contains(pd.getName())// ) {// continue; } Class fieldClazz = pd.getPropertyType(); Long numIndex = countrolParam.getNumIndex(); // int enumIndex = countrolParam.getEnumIndex(); Random random = countrolParam.getRandom(); long strIndex = countrolParam.getStrIndex(); int charIndex = countrolParam.getCharIndex(); Calendar time = countrolParam.getTime(); if (TypeUtil.isBaseType(fieldClazz)) { if (TypeUtil.isNumberType(fieldClazz)) { if (fieldClazz == Byte.class) { writeMethod.invoke(item, Byte.valueOf((byte) (numIndex & 0x7F))); } else if (fieldClazz == Short.class) { writeMethod.invoke(item, Short.valueOf((short) (numIndex & 0x7FFF))); } else if (fieldClazz == Integer.class) { writeMethod.invoke(item, Integer.valueOf((int) (numIndex & 0x7FFFFFFF))); } else if (fieldClazz == Long.class) { writeMethod.invoke(item, Long.valueOf((long) numIndex)); } else if (fieldClazz == Float.class) { writeMethod.invoke(item, Float.valueOf((float) numIndex)); } else if (fieldClazz == Double.class) { writeMethod.invoke(item, Double.valueOf((double) numIndex)); } else if (fieldClazz == byte.class) {// writeMethod.invoke(item, (byte) (numIndex & 0x7F)); } else if (fieldClazz == short.class) { writeMethod.invoke(item, (short) (numIndex & 0x7FFF)); } else if (fieldClazz == int.class) { writeMethod.invoke(item, (int) (numIndex & 0x7FFFFFFF)); } else if (fieldClazz == long.class) { writeMethod.invoke(item, (long) numIndex); } else if (fieldClazz == float.class) { writeMethod.invoke(item, (float) numIndex); } else if (fieldClazz == double.class) { writeMethod.invoke(item, (double) numIndex); } numIndex++; if (numIndex < 0) { numIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setNumIndex(numIndex); } else if (fieldClazz == boolean.class) { writeMethod.invoke(item, random.nextBoolean()); } else if (fieldClazz == Boolean.class) { writeMethod.invoke(item, Boolean.valueOf(random.nextBoolean())); } else if (fieldClazz == char.class) { writeMethod.invoke(item, CHAR_RANGE[charIndex]); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == Character.class) { writeMethod.invoke(item, Character.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } else if (fieldClazz == String.class) { if (countrolParam.getUniqueFieldList() != null && countrolParam.getUniqueFieldList().contains(pd.getName())) { StringBuilder sb = new StringBuilder(); convertNum(strIndex, STRING_RANGE, countrolParam.getRandom(), sb); writeMethod.invoke(item, sb.toString()); strIndex += countrolParam.getStrStep(); if (strIndex < 0) { strIndex &= 0x7FFFFFFFFFFFFFFFL; } countrolParam.setStrIndex(strIndex); } else { writeMethod.invoke(item, String.valueOf(CHAR_RANGE[charIndex])); charIndex++; if (charIndex >= CHAR_RANGE.length) { charIndex = 0; } countrolParam.setCharIndex(charIndex); } } else if (fieldClazz == Date.class) { writeMethod.invoke(item, time.getTime()); time.add(Calendar.DAY_OF_YEAR, 1); } else if (fieldClazz.isEnum()) { int index = random.nextInt(fieldClazz.getEnumConstants().length); writeMethod.invoke(item, fieldClazz.getEnumConstants()[index]); } else { // throw new RuntimeException("out of countrol Class " + fieldClazz.getName()); } } else { parseClassList.push(fieldClazz); // TODO ? Set<Class> set = new HashSet<Class>(parseClassList); if (parseClassList.size() - set.size() <= countrolParam.getRecursiveCycleLimit()) { Object bean = produceBean(fieldClazz, countrolParam, parseClassList); writeMethod.invoke(item, bean); } parseClassList.pop(); } } return item; } catch (Exception e) { throw new RuntimeException(e); } }
From source file:net.ceos.project.poi.annotated.core.Engine.java
/** * Apply the base object from cell./* www .j a va 2 s.c o m*/ * * @param o * the object * @param fT * the field type * @param f * the field * @param c * the cell * @param xlsAnnotation * the {@link XlsElement} annotation * @return false if problem otherwise true * @throws WorkbookException * given when a not supported action. */ private boolean toObject(final Object o, final Class<?> fT, final Field f, final Cell c, final XlsElement xlsAnnotation) throws WorkbookException { /* flag which define if the cell was updated or not */ boolean isUpdated; f.setAccessible(true); switch (fT.getName()) { case CellHandler.OBJECT_DATE: CellHandler.dateReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATE: CellHandler.localDateReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_LOCALDATETIME: CellHandler.localDateTimeReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_STRING: CellHandler.stringReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_SHORT: /* falls through */ case CellHandler.PRIMITIVE_SHORT: CellHandler.shortReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_INTEGER: /* falls through */ case CellHandler.PRIMITIVE_INTEGER: CellHandler.integerReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_LONG: /* falls through */ case CellHandler.PRIMITIVE_LONG: CellHandler.longReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_DOUBLE: /* falls through */ case CellHandler.PRIMITIVE_DOUBLE: CellHandler.doubleReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_BIGDECIMAL: CellHandler.bigDecimalReader(o, f, c, xlsAnnotation); isUpdated = true; break; case CellHandler.OBJECT_FLOAT: /* falls through */ case CellHandler.PRIMITIVE_FLOAT: CellHandler.floatReader(o, f, c); isUpdated = true; break; case CellHandler.OBJECT_BOOLEAN: /* falls through */ case CellHandler.PRIMITIVE_BOOLEAN: CellHandler.booleanReader(o, f, c, xlsAnnotation); isUpdated = true; break; default: isUpdated = false; break; } if (!isUpdated && fT.isEnum()) { CellHandler.enumReader(o, fT, f, c); isUpdated = true; } return isUpdated; }
From source file:net.sf.juffrou.reflect.JuffrouTypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), for the specified property. * // ww w .j a v a 2 s . c o m * @param propertyName * name of the property * @param oldValue * the previous value, if available (may be <code>null</code>) * @param newValue * the proposed new value * @param requiredType * the type we must convert to (or <code>null</code> if not known, for example in case of a collection * element) * @param typeDescriptor * the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException * if type conversion failed */ @SuppressWarnings("unchecked") public <T> T convertIfNecessary(String propertyName, Object oldValue, Object newValue, Class<T> requiredType, TypeDescriptor typeDescriptor) throws IllegalArgumentException { Object convertedValue = newValue; // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException firstAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && convertedValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); TypeDescriptor targetTypeDesc = typeDescriptor; if (conversionService.canConvert(sourceTypeDesc, targetTypeDesc)) { try { return (T) conversionService.convert(convertedValue, sourceTypeDesc, targetTypeDesc); } catch (ConversionFailedException ex) { // fallback to default conversion logic below firstAttemptEx = ex; } } } // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementType = typeDescriptor.getElementTypeDescriptor(); if (elementType != null && Enum.class.isAssignableFrom(elementType.getType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class.equals(requiredType) && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (firstAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor strCtor = requiredType.getConstructor(String.class); return (T) BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (firstAttemptEx != null) { throw firstAttemptEx; } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type [").append(ClassUtils.getDescriptiveType(newValue)); msg.append("] to required type [").append(ClassUtils.getQualifiedName(requiredType)).append("]"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type [") .append(ClassUtils.getDescriptiveType(convertedValue)).append("]"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (firstAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && !Object.class.equals(requiredType)) { throw firstAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", firstAttemptEx); } return (T) convertedValue; }
From source file:com.bstek.dorado.idesupport.initializer.CommonRuleTemplateInitializer.java
protected Collection<AutoPropertyTemplate> getProperties(Class<?> type, XmlNodeInfo xmlNodeInfo, InitializerContext initializerContext) throws Exception { HashMap<String, AutoPropertyTemplate> properties = new LinkedHashMap<String, AutoPropertyTemplate>(); RuleTemplateManager ruleTemplateManager = initializerContext.getRuleTemplateManager(); if (xmlNodeInfo != null) { if (xmlNodeInfo.isInheritable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("impl"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); propertyTemplate = new AutoPropertyTemplate("parent"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); }/*from w ww. ja v a2 s .c o m*/ if (xmlNodeInfo.isScopable()) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("scope"); propertyTemplate.setPrimitive(true); Object[] ecs = Scope.class.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); properties.put(propertyTemplate.getName(), propertyTemplate); } if (StringUtils.isNotEmpty(xmlNodeInfo.getDefinitionType())) { Class<?> definitionType = ClassUtils.forName(xmlNodeInfo.getDefinitionType()); if (ListenableObjectDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("listener"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } if (InterceptableDefinition.class.isAssignableFrom(definitionType)) { AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate("interceptor"); propertyTemplate.setPrimitive(true); properties.put(propertyTemplate.getName(), propertyTemplate); } } for (Map.Entry<String, String> entry : xmlNodeInfo.getFixedProperties().entrySet()) { String propertyName = entry.getKey(); String value = entry.getValue(); AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName); propertyTemplate.setDefaultValue(value); propertyTemplate.setPrimitive(true); propertyTemplate.setFixed(true); propertyTemplate.setVisible(false); properties.put(propertyName, propertyTemplate); } for (Map.Entry<String, XmlProperty> entry : xmlNodeInfo.getProperties().entrySet()) { String propertyName = entry.getKey(); XmlProperty xmlProperty = entry.getValue(); TypeInfo propertyTypeInfo = TypeInfo.parse(xmlProperty.propertyType()); Class<?> propertyType = null; if (propertyTypeInfo != null) { propertyType = propertyTypeInfo.getType(); } AutoPropertyTemplate propertyTemplate = new AutoPropertyTemplate(propertyName, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); if (propertyType != null && !propertyType.equals(String.class)) { propertyTemplate.setType(propertyType.getName()); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); properties.put(propertyName, propertyTemplate); } } PropertyDescriptor[] propertyDescriptors = PropertyUtils.getPropertyDescriptors(type); for (PropertyDescriptor propertyDescriptor : propertyDescriptors) { Method readMethod = propertyDescriptor.getReadMethod(); if (readMethod != null && propertyDescriptor.getWriteMethod() != null) { if (readMethod.getDeclaringClass() != type) { try { readMethod = type.getDeclaredMethod(readMethod.getName(), readMethod.getParameterTypes()); } catch (NoSuchMethodException e) { continue; } } String propertyName = propertyDescriptor.getName(); XmlSubNode xmlSubNode = readMethod.getAnnotation(XmlSubNode.class); if (xmlSubNode != null) { continue; } TypeInfo propertyTypeInfo; Class<?> propertyType = propertyDescriptor.getPropertyType(); if (Collection.class.isAssignableFrom(propertyType)) { propertyTypeInfo = TypeInfo.parse((ParameterizedType) readMethod.getGenericReturnType(), true); propertyType = propertyTypeInfo.getType(); } else { propertyTypeInfo = new TypeInfo(propertyType, false); } AutoPropertyTemplate propertyTemplate = null; XmlProperty xmlProperty = readMethod.getAnnotation(XmlProperty.class); if (xmlProperty != null) { if (xmlProperty.unsupported()) { continue; } propertyTemplate = properties.get(propertyName); if (propertyTemplate == null) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); propertyTemplate.setPrimitive(xmlProperty.attributeOnly()); } if (("dataSet".equals(propertyName) || "dataPath".equals(propertyName) || "property".equals(propertyName)) && DataControl.class.isAssignableFrom(type)) { propertyTemplate.setHighlight(1); } if (xmlProperty.composite()) { initCompositeProperty(propertyTemplate, propertyType, initializerContext); } int clientTypes = ClientType.parseClientTypes(xmlProperty.clientTypes()); if (clientTypes > 0) { propertyTemplate.setClientTypes(clientTypes); } propertyTemplate.setDeprecated(xmlProperty.deprecated()); } else if (EntityUtils.isSimpleType(propertyType) || propertyType.equals(Class.class) || propertyType.isArray() && propertyType.getComponentType().equals(String.class)) { propertyTemplate = new AutoPropertyTemplate(propertyName, readMethod, xmlProperty); } if (propertyTemplate != null) { propertyTemplate.setType(propertyDescriptor.getPropertyType().getName()); if (propertyType.isEnum()) { Object[] ecs = propertyType.getEnumConstants(); String[] enumValues = new String[ecs.length]; for (int i = 0; i < ecs.length; i++) { enumValues[i] = ecs[i].toString(); } propertyTemplate.setEnumValues(enumValues); } ComponentReference componentReference = readMethod.getAnnotation(ComponentReference.class); if (componentReference != null) { ReferenceTemplate referenceTemplate = new LazyReferenceTemplate(ruleTemplateManager, componentReference.value(), "id"); propertyTemplate.setReference(referenceTemplate); } IdeProperty ideProperty = readMethod.getAnnotation(IdeProperty.class); if (ideProperty != null) { propertyTemplate.setVisible(ideProperty.visible()); propertyTemplate.setEditor(ideProperty.editor()); propertyTemplate.setHighlight(ideProperty.highlight()); if (StringUtils.isNotEmpty(ideProperty.enumValues())) { propertyTemplate.setEnumValues(StringUtils.split(ideProperty.enumValues(), ",;")); } } ClientProperty clientProperty = readMethod.getAnnotation(ClientProperty.class); if (clientProperty != null) { propertyTemplate.setDefaultValue(clientProperty.escapeValue()); } properties.put(propertyName, propertyTemplate); } } } return properties.values(); }
From source file:org.springframework.beans.TypeConverterDelegate.java
/** * Convert the value to the required type (if necessary from a String), * for the specified property.//ww w . j av a 2 s . co m * @param propertyName name of the property * @param oldValue the previous value, if available (may be {@code null}) * @param newValue the proposed new value * @param requiredType the type we must convert to * (or {@code null} if not known, for example in case of a collection element) * @param typeDescriptor the descriptor for the target property or field * @return the new value, possibly the result of type conversion * @throws IllegalArgumentException if type conversion failed */ @SuppressWarnings("unchecked") @Nullable public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue, @Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor) throws IllegalArgumentException { // Custom editor for this type? PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName); ConversionFailedException conversionAttemptEx = null; // No custom editor but custom ConversionService specified? ConversionService conversionService = this.propertyEditorRegistry.getConversionService(); if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) { TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { try { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } catch (ConversionFailedException ex) { // fallback to default conversion logic below conversionAttemptEx = ex; } } } Object convertedValue = newValue; // Value not of required type? if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) { if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) && convertedValue instanceof String) { TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor(); if (elementTypeDesc != null) { Class<?> elementType = elementTypeDesc.getType(); if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } } } if (editor == null) { editor = findDefaultEditor(requiredType); } convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor); } boolean standardConversion = false; if (requiredType != null) { // Try to apply some standard type conversion rules if appropriate. if (convertedValue != null) { if (Object.class == requiredType) { return (T) convertedValue; } else if (requiredType.isArray()) { // Array required -> apply appropriate conversion of elements. if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) { convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue); } return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType()); } else if (convertedValue instanceof Collection) { // Convert elements to target type, if determined. convertedValue = convertToTypedCollection((Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } else if (convertedValue instanceof Map) { // Convert keys and values to respective target type, if determined. convertedValue = convertToTypedMap((Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor); standardConversion = true; } if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) { convertedValue = Array.get(convertedValue, 0); standardConversion = true; } if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) { // We can stringify any primitive value... return (T) convertedValue.toString(); } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) { if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) { try { Constructor<T> strCtor = requiredType.getConstructor(String.class); return BeanUtils.instantiateClass(strCtor, convertedValue); } catch (NoSuchMethodException ex) { // proceed with field lookup if (logger.isTraceEnabled()) { logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex); } } catch (Exception ex) { if (logger.isDebugEnabled()) { logger.debug( "Construction via String failed for type [" + requiredType.getName() + "]", ex); } } } String trimmedValue = ((String) convertedValue).trim(); if (requiredType.isEnum() && "".equals(trimmedValue)) { // It's an empty enum identifier: reset the enum value to null. return null; } convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue); standardConversion = true; } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) { convertedValue = NumberUtils.convertNumberToTargetClass((Number) convertedValue, (Class<Number>) requiredType); standardConversion = true; } } else { // convertedValue == null if (requiredType == Optional.class) { convertedValue = Optional.empty(); } } if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) { if (conversionAttemptEx != null) { // Original exception from former ConversionService call above... throw conversionAttemptEx; } else if (conversionService != null && typeDescriptor != null) { // ConversionService not tried before, probably custom editor found // but editor couldn't produce the required type... TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue); if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) { return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor); } } // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException StringBuilder msg = new StringBuilder(); msg.append("Cannot convert value of type '").append(ClassUtils.getDescriptiveType(newValue)); msg.append("' to required type '").append(ClassUtils.getQualifiedName(requiredType)).append("'"); if (propertyName != null) { msg.append(" for property '").append(propertyName).append("'"); } if (editor != null) { msg.append(": PropertyEditor [").append(editor.getClass().getName()) .append("] returned inappropriate value of type '") .append(ClassUtils.getDescriptiveType(convertedValue)).append("'"); throw new IllegalArgumentException(msg.toString()); } else { msg.append(": no matching editors or conversion strategy found"); throw new IllegalStateException(msg.toString()); } } } if (conversionAttemptEx != null) { if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) { throw conversionAttemptEx; } logger.debug("Original ConversionService attempt failed - ignored since " + "PropertyEditor based conversion eventually succeeded", conversionAttemptEx); } return (T) convertedValue; }