List of usage examples for org.springframework.beans BeanUtils isSimpleValueType
public static boolean isSimpleValueType(Class<?> clazz)
From source file:org.openmrs.calculation.CalculationUtil.java
/** * Utility method that casts the specified value to the specified Type and handles conversions * to primitive wrapper classes in a better/more lenient way than java's type casting. Note that * the method will throw a {@link ConversionException} at runtime if it fails to convert the * specified value/* ww w.j a va2s. c o m*/ * * @see ConversionException * @param valueToCast the value to be cast * @param clazz the class to cast to * @return a value of the specified type * @should fail if the value to convert is not of a compatible type * @should convert the value to the specified type if it is compatible * @should return null if the passed in value is null * @should convert a valid string value to Boolean * @should convert a character value to Character * @should convert a valid string value to Short * @should convert a valid string value to Integer * @should convert a valid string value to Long * @should convert a valid string value to Float * @should convert a valid string value to Double * @should convert a valid string value to Byte * @should convert a single character value to Short * @should convert a valid single character value to Integer * @should convert a valid single character value to Long * @should convert a result with an number value in the valid range to byte * @should convert a valid string to an enum constant * @should convert a valid string to a class object * @should convert a valid string to a Locale * @should format a date object to a string using the default date format */ @SuppressWarnings("unchecked") public static <T> T cast(Object value, Class<T> clazz) { if (value == null) return null; if (clazz == null) throw new IllegalArgumentException("The class to cast to cannot be null"); T castValue = null; // We should be able to convert any value to a String if (String.class.isAssignableFrom(clazz)) { if (Date.class.isAssignableFrom(value.getClass())) castValue = (T) Context.getDateFormat().format((Date) value); else castValue = (T) value.toString(); } else { //we should be able to convert strings to simple types like String "2" to integer 2, //enums, dates, etc. Java types casting doesn't allow this so we need to transform the value first to //a string. BeanUtils from old spring versions doesn't consider enums as simple types if (BeanUtils.isSimpleValueType(clazz) || clazz.isEnum()) { try { String stringValue = null; //objects of types like date and Class whose toString methods are not reliable if (String.class.isAssignableFrom(value.getClass())) stringValue = (String) value; else stringValue = value.toString(); if (Character.class.equals(clazz) && stringValue.length() == 1) { value = stringValue.charAt(0); } else if (Locale.class.isAssignableFrom(clazz)) { return (T) LocaleUtility.fromSpecification(stringValue); } else if (Class.class.isAssignableFrom(clazz)) { return (T) Context.loadClass(stringValue); } else { Method method = clazz.getMethod("valueOf", new Class<?>[] { String.class }); value = method.invoke(null, stringValue); } } catch (Exception e) { //ignore and default to clazz.cast below } } try { castValue = clazz.cast(value); } catch (ClassCastException e) { throw new ConversionException(value, clazz); } } return castValue; }
From source file:com.expressui.core.util.ReflectionUtil.java
/** * Finds all properties in the bean that are complex, that is not BeanUtils.isSimpleValueType * * @param bean bean to reflectively analyze * @return collection of properties on the bean *//*from w w w . jav a 2 s .c o m*/ public static Collection<String> findComplexProperties(Object bean) { Collection<String> complexProperties = new ArrayList<String>(); WrapDynaBean wrapDynaBean = new WrapDynaBean(bean); DynaProperty[] properties = wrapDynaBean.getDynaClass().getDynaProperties(); for (DynaProperty property : properties) { String propertyName = property.getName(); Class propertyType = property.getType(); if (!BeanUtils.isSimpleValueType(propertyType)) { complexProperties.add(propertyName); } } return complexProperties; }
From source file:org.kmnet.com.fw.web.el.Functions.java
/** * build query string from map or bean./*from w w w . ja va 2s . com*/ * <p> * query string is encoded with "UTF-8". * </p> * @param params map or bean * @return query string. returns empty string if <code>params</code> is <code>null</code> or empty string or * {@link Iterable} or {@link BeanUtils#isSimpleValueType(Class)}. */ @SuppressWarnings("unchecked") public static String query(Object params) { if (params == null) { return ""; } Class<?> clazz = params.getClass(); if (clazz.isArray() || params instanceof Iterable || BeanUtils.isSimpleValueType(clazz)) { return ""; } String query; if (params instanceof Map) { query = mapToQuery((Map<String, Object>) params); } else { Map<String, Object> map = new LinkedHashMap<String, Object>(); BeanWrapper beanWrapper = PropertyAccessorFactory.forBeanPropertyAccess(params); PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(clazz); for (PropertyDescriptor pd : pds) { String name = pd.getName(); if (!"class".equals(name)) { Object value = beanWrapper.getPropertyValue(name); map.put(name, value); } } query = mapToQuery(map, beanWrapper); } return query; }
From source file:org.terasoluna.gfw.web.el.Functions.java
/** * build query string from map or bean./*from www . j a v a 2 s .c om*/ * <p> * query string is encoded with "UTF-8". * </p> * <p> * Note : About a {@link Map} property<br> * In this method, {@code null} and empty element are distinguished explicitly. Conversion rules are as follows: * <ul> * <li>If the value of a property is {@code null}, it is converted to empty string and the key is prefixed with {@code "_"} * .(converted to the reset parameter provided by Spring Web MVC)</li> * <li>If the value of a {@link Map} property is empty element, it is not converted.</li> * </ul> * <br> * But if this method is used after the {@code <form:form>} tag provided by Spring Web MVC, {@code null} is converted to * empty element during the processing of {@code <form:form>} tag. As a result, {@code null} value is not converted to a * reset parameter that start with {@code "_"}. In this case, this method does not guarantee the symmetry with the form * binding provided by Spring Web MVC. * @see ObjectToMapConverter * @param params map or bean * @return query string. returns empty string if <code>params</code> is <code>null</code> or empty string or * {@link Iterable} or {@link BeanUtils#isSimpleValueType(Class)}. */ @SuppressWarnings("unchecked") public static String query(Object params) { if (params == null) { return ""; } Class<?> clazz = params.getClass(); if (BeanUtils.isSimpleValueType(clazz)) { return ""; } return mapToQuery((Map) OBJECT_TO_MAP_CONVERTER.convert(params)); }
From source file:com.ocs.dynamo.domain.model.impl.EntityModelFactoryImpl.java
/** * Determines the attribute type of an attribute * //from ww w . ja v a2 s .c o m * @param model * the model representation of the attribute * @return */ private AttributeType determineAttributeType(Class<?> parentClass, AttributeModelImpl model) { AttributeType result = null; String name = model.getName(); int p = name.lastIndexOf("."); if (p > 0) { name = name.substring(p + 1); } if (!BeanUtils.isSimpleValueType(model.getType())) { // No relation type set in view model definition, hence derive // defaults Embedded embedded = ClassUtils.getAnnotation(parentClass, name, Embedded.class); Attribute attribute = ClassUtils.getAnnotation(parentClass, name, Attribute.class); if (embedded != null) { result = AttributeType.EMBEDDED; } else if (Collection.class.isAssignableFrom(model.getType())) { if (attribute != null && attribute.memberType() != null && !attribute.memberType().equals(Object.class)) { // if a member type is explicitly set, use that type result = AttributeType.DETAIL; model.setMemberType(attribute.memberType()); } else if (ClassUtils.getAnnotation(parentClass, name, ManyToMany.class) != null || ClassUtils.getAnnotation(parentClass, name, OneToMany.class) != null) { result = AttributeType.DETAIL; model.setMemberType(ClassUtils.getResolvedType(parentClass, model.getName(), 0)); } else if (ClassUtils.getAnnotation(parentClass, name, ElementCollection.class) != null) { result = AttributeType.ELEMENT_COLLECTION; model.setMemberType(ClassUtils.getResolvedType(parentClass, model.getName(), 0)); } else if (AbstractEntity.class.isAssignableFrom(model.getType())) { // not a collection but a reference to another object result = AttributeType.MASTER; } } else if (model.getType().isArray()) { // a byte array with the @Lob annotation is transformed to a // @Lob field Lob lob = ClassUtils.getAnnotation(parentClass, name, Lob.class); if (lob != null) { result = AttributeType.LOB; } } else { // not a collection but a reference to another object result = AttributeType.MASTER; } } else { // simple attribute type result = AttributeType.BASIC; } return result; }
From source file:com.revolsys.ui.web.rest.interceptor.WebAnnotationMethodHandlerAdapter.java
/** * Determine whether the given value qualifies as a "binding candidate", i.e. might potentially be subject to * bean-style data binding later on./*from w w w. j a v a 2 s. c o m*/ */ protected boolean isBindingCandidate(final Object value) { return value != null && !value.getClass().isArray() && !(value instanceof Collection) && !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass()); }
From source file:org.archive.crawler.restlet.JobRelatedResource.java
/** * Constructs a nested Map data structure of the information represented * by {@code object}. The result is particularly suitable for use with with * {@link XmlMarshaller}.//w ww. jav a2 s . c om * * @param field * field name for object * @param object * object to make presentable map for * @param alreadyWritten * Set of objects already made presentable whose addition to the * Map should be suppressed * @param beanPathPrefix * beanPath prefix to apply to sub fields browse links * @return the presentable Map */ protected Map<String, Object> makePresentableMapFor(String field, Object object, HashSet<Object> alreadyWritten, String beanPathPrefix) { Map<String, Object> info = new LinkedHashMap<String, Object>(); Reference baseRef = getRequest().getResourceRef().getBaseRef(); String beanPath = beanPathPrefix; if (StringUtils.isNotBlank(field)) { info.put("field", field); if (StringUtils.isNotBlank(beanPathPrefix)) { if (beanPathPrefix.endsWith(".")) { beanPath += field; } else if (beanPathPrefix.endsWith("[")) { beanPath += field + "]"; } info.put("url", new Reference(baseRef, "../beans/" + TextUtils.urlEscape(beanPath)).getTargetRef()); } } String key = getBeanToNameMap().get(object); if (object == null) { info.put("propValue", null); return info; } if (object instanceof String || BeanUtils.isSimpleValueType(object.getClass()) || object instanceof File) { info.put("class", object.getClass().getName()); info.put("propValue", object); return info; } if (alreadyWritten.contains(object)) { info.put("propValuePreviouslyDescribed", true); return info; } alreadyWritten.add(object); // guard against repeats and cycles if (StringUtils.isNotBlank(key) && StringUtils.isNotBlank(field)) { info.put("key", key); info.put("url", new Reference(baseRef, "../beans/" + key).getTargetRef()); return info; } info.put("class", object.getClass().getName()); Collection<Object> properties = new LinkedList<Object>(); BeanWrapperImpl bwrap = new BeanWrapperImpl(object); for (PropertyDescriptor pd : getPropertyDescriptors(bwrap)) { if (pd.getReadMethod() != null && !pd.isHidden()) { String propName = pd.getName(); if (beanPath != null) { beanPathPrefix = beanPath + "."; } Object propValue = makePresentableMapFor(propName, bwrap.getPropertyValue(propName), alreadyWritten, beanPathPrefix); properties.add(propValue); } } if (properties.size() > 0) { info.put("properties", properties); } Collection<Object> propValues = new LinkedList<Object>(); if (object.getClass().isArray()) { // TODO: may want a special handling for an array of // primitive types? int len = Array.getLength(object); for (int i = 0; i < len; i++) { if (beanPath != null) { beanPathPrefix = beanPath + "["; } // TODO: protect against overlong content? propValues.add(makePresentableMapFor(i + "", Array.get(object, i), alreadyWritten, beanPathPrefix)); } } if (object instanceof List<?>) { List<?> list = (List<?>) object; for (int i = 0; i < list.size(); i++) { if (beanPath != null) { beanPathPrefix = beanPath + "["; } // TODO: protect against overlong content? try { propValues.add(makePresentableMapFor(i + "", list.get(i), alreadyWritten, beanPathPrefix)); } catch (Exception e) { LOGGER.warning(list + ".get(" + i + ") -" + e); } } } else if (object instanceof Iterable<?>) { for (Object next : (Iterable<?>) object) { propValues.add(makePresentableMapFor("#", next, alreadyWritten, beanPathPrefix)); } } if (object instanceof Map<?, ?>) { for (Object next : ((Map<?, ?>) object).entrySet()) { // TODO: protect against giant maps? Map.Entry<?, ?> entry = (Map.Entry<?, ?>) next; if (beanPath != null) { beanPathPrefix = beanPath + "["; } propValues.add(makePresentableMapFor(entry.getKey().toString(), entry.getValue(), alreadyWritten, beanPathPrefix)); } } if (propValues.size() > 0) { info.put("propValue", propValues); } return info; }
From source file:org.springframework.data.document.web.bind.annotation.support.HandlerMethodInvoker.java
/** * Determine whether the given value qualifies as a "binding candidate", i.e. might potentially be subject to * bean-style data binding later on./*from w w w. j a v a 2s . c o m*/ */ protected boolean isBindingCandidate(Object value) { return (value != null && !value.getClass().isArray() && !(value instanceof Collection) && !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass())); }
From source file:org.springframework.web.method.annotation.ModelFactory.java
/** * Whether the given attribute requires a {@link BindingResult} in the model. *///from w w w . ja va 2 s. c om private boolean isBindingCandidate(String attributeName, Object value) { if (attributeName.startsWith(BindingResult.MODEL_KEY_PREFIX)) { return false; } if (this.sessionAttributesHandler.isHandlerSessionAttribute(attributeName, value.getClass())) { return true; } return (!value.getClass().isArray() && !(value instanceof Collection) && !(value instanceof Map) && !BeanUtils.isSimpleValueType(value.getClass())); }