List of usage examples for org.apache.commons.beanutils ConvertUtils convert
public static Object convert(String values[], Class clazz)
Convert an array of specified values to an array of objects of the specified class (if possible).
For more details see ConvertUtilsBean
.
From source file:org.andromda.presentation.gui.FormPopulator.java
/** * Populates the form from the given map of properties. If a matching property is null or an empty * string, then null is placed on the form. * * @param form the form to populate./*from w w w . j a va2 s. co m*/ * @param formatters any date or time formatters. * @param properties the properties to populate from. * @param ignoreProperties names of any properties to ignore when it comes to populating on the form. * @param override whether or not to override properties already set on the given form. * @param assignableTypesOnly whether or not copying should be attempted only if the property types are assignable. */ @SuppressWarnings("unchecked") // apache commons-beanutils PropertyUtils has no generics public static final void populateFormFromPropertyMap(final Object form, final Map<String, DateFormat> formatters, final Map<String, ?> properties, final String[] ignoreProperties, boolean override, boolean assignableTypesOnly) { if (properties != null) { try { final Collection<String> ignoredProperties = ignoreProperties != null ? Arrays.asList(ignoreProperties) : new ArrayList<String>(); final Map<String, Object> formProperties = PropertyUtils.describe(form); for (final Iterator<String> iterator = formProperties.keySet().iterator(); iterator.hasNext();) { final String name = iterator.next(); if (PropertyUtils.isWriteable(form, name) && !ignoredProperties.contains(name)) { final PropertyDescriptor descriptor = PropertyUtils.getPropertyDescriptor(form, name); if (descriptor != null) { boolean populateProperty = true; if (!override) { final String isSetPropertyName = name + "Set"; if (PropertyUtils.isReadable(form, isSetPropertyName)) { final Boolean isPropertySet = (Boolean) PropertyUtils.getProperty(form, isSetPropertyName); if (isPropertySet.booleanValue()) { populateProperty = false; } } } if (populateProperty) { final Object property = properties.get(name); // - only convert if the string is not empty if (property != null) { Object value = null; if (property instanceof String) { final String propertyAsString = (String) property; if (propertyAsString.trim().length() > 0) { DateFormat formatter = formatters != null ? formatters.get(name) : null; // - if the formatter is available we use that, otherwise we attempt to convert if (formatter != null) { try { value = formatter.parse(propertyAsString); } catch (ParseException parseException) { // - try the default formatter (handles the default java.util.Date.toString() format) formatter = formatters != null ? formatters.get(null) : null; value = formatter.parse(propertyAsString); } } else { value = ConvertUtils.convert(propertyAsString, descriptor.getPropertyType()); } } // - don't attempt to set null on primitive fields if (value != null || !descriptor.getPropertyType().isPrimitive()) { PropertyUtils.setProperty(form, name, value); } } else { value = property; try { if (!assignableTypesOnly || descriptor.getPropertyType() .isAssignableFrom(value.getClass())) { PropertyUtils.setProperty(form, name, value); } } catch (Exception exception) { final String valueTypeName = value.getClass().getName(); final String propertyTypeName = descriptor.getPropertyType().getName(); final StringBuilder message = new StringBuilder( "Can not set form property '" + name + "' of type: " + propertyTypeName + " with value: " + value); if (!descriptor.getPropertyType().isAssignableFrom(value.getClass())) { message.append("; " + valueTypeName + " is not assignable to " + propertyTypeName); } throw new IllegalArgumentException( message + ": " + exception.toString()); } } } } } } } } catch (final Throwable throwable) { throw new RuntimeException(throwable); } } }
From source file:org.apache.ddlutils.io.converters.NumberConverter.java
/** * {@inheritDoc}/* w w w .ja va2 s. c o m*/ */ public Object convertFromString(String textRep, int sqlTypeCode) throws ConversionException { if (textRep == null) { return null; } else { Class targetClass = null; switch (sqlTypeCode) { case Types.BIGINT: targetClass = Long.class; break; case Types.BIT: case Types.BOOLEAN: targetClass = Boolean.class; break; case Types.DECIMAL: case Types.NUMERIC: targetClass = BigDecimal.class; break; case Types.DOUBLE: case Types.FLOAT: targetClass = Double.class; break; case Types.INTEGER: targetClass = Integer.class; break; case Types.REAL: targetClass = Float.class; break; case Types.SMALLINT: case Types.TINYINT: targetClass = Short.class; break; } return targetClass == null ? textRep : ConvertUtils.convert(textRep, targetClass); } }
From source file:org.apache.ddlutils.model.Column.java
/** * Tries to parse the default value of the column and returns it as an object of the * corresponding java type. If the value could not be parsed, then the original * definition is returned.//from ww w. j ava 2s .c o m * * @return The parsed default value */ public Object getParsedDefaultValue() { if ((_defaultValue != null) && (_defaultValue.length() > 0)) { try { switch (_typeCode) { case Types.TINYINT: case Types.SMALLINT: return new Short(_defaultValue); case Types.INTEGER: return new Integer(_defaultValue); case Types.BIGINT: return new Long(_defaultValue); case Types.DECIMAL: case Types.NUMERIC: return new BigDecimal(_defaultValue); case Types.REAL: return new Float(_defaultValue); case Types.DOUBLE: case Types.FLOAT: return new Double(_defaultValue); case Types.DATE: return Date.valueOf(_defaultValue); case Types.TIME: return Time.valueOf(_defaultValue); case Types.TIMESTAMP: return Timestamp.valueOf(_defaultValue); case Types.BIT: case Types.BOOLEAN: return ConvertUtils.convert(_defaultValue, Boolean.class); } } catch (NumberFormatException ex) { return null; } catch (IllegalArgumentException ex) { return null; } } return _defaultValue; }
From source file:org.apache.ddlutils.platform.DefaultValueHelper.java
/** * Converts a boolean default value to the given target type. * /*from w w w . j a v a 2 s .com*/ * @param defaultValue The default value * @param targetTypeCode The target type code * @return The converted value */ private Object convertBoolean(String defaultValue, int targetTypeCode) { Boolean value = null; Object result = null; try { value = (Boolean) ConvertUtils.convert(defaultValue, Boolean.class); } catch (ConversionException ex) { return defaultValue; } if ((targetTypeCode == Types.BIT) || (targetTypeCode == Types.BOOLEAN)) { result = value; } else if (TypeMap.isNumericType(targetTypeCode)) { result = (value.booleanValue() ? new Integer(1) : new Integer(0)); } else { result = value.toString(); } return result; }
From source file:org.apache.geode.management.internal.cli.util.JsonUtil.java
/** * Converts given JSON String in to a Object. Refer http://www.json.org/ to construct a JSON * format.//from ww w .j a v a2 s . com * * @param jsonString jsonString to be converted in to a Map. * @return an object constructed from given JSON String * * @throws IllegalArgumentException if the specified JSON string can not be converted in to an * Object */ public static <T> T jsonToObject(String jsonString, Class<T> klass) { T objectFromJson = null; try { GfJsonObject jsonObject = new GfJsonObject(jsonString); objectFromJson = klass.newInstance(); Method[] declaredMethods = klass.getMethods(); Map<String, Method> methodsMap = new HashMap<String, Method>(); for (Method method : declaredMethods) { methodsMap.put(method.getName(), method); } int noOfFields = jsonObject.size(); Iterator<String> keys = jsonObject.keys(); while (keys.hasNext()) { String key = keys.next(); Method method = methodsMap.get("set" + capitalize(key)); if (method != null) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { Class<?> parameterType = parameterTypes[0]; Object value = jsonObject.get(key); if (isPrimitiveOrWrapper(parameterType)) { value = ConvertUtils.convert(getPrimitiveOrWrapperValue(parameterType, value), parameterType); } // Bug #51175 else if (isArray(parameterType)) { value = toArray(value, parameterType); } else if (isList(parameterType)) { value = toList(value, parameterType); } else if (isMap(parameterType)) { value = toMap(value, parameterType); } else if (isSet(parameterType)) { value = toSet(value, parameterType); } else { value = jsonToObject(value.toString(), parameterType); } method.invoke(objectFromJson, new Object[] { value }); noOfFields--; } } } if (noOfFields != 0) { throw new IllegalArgumentException("Not enough setter methods for fields in given JSON String : " + jsonString + " in class : " + klass); } } catch (InstantiationException e) { throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); } catch (GfJsonException e) { throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); } catch (InvocationTargetException e) { throw new IllegalArgumentException("Couldn't convert JSON to Object of type " + klass, e); } return objectFromJson; }
From source file:org.apache.struts.config.FormPropertyConfig.java
/** * <p>Return an object representing the initial value of this property. * This is calculated according to the following algorithm:</p> * * <ul>//from w w w. j a va2s .c om * * <li>If the value you have specified for the <code>type</code> property * represents an array (i.e. it ends with "[]"): * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an instance of the specified array type.</li> * * <li>If you have not specified a value for the <code>initial</code> * property, an array of the length specified by the <code>size</code> * property will be created. Each element of the array will be * instantiated via the zero-args constructor on the specified class (if * any). Otherwise, <code>null</code> will be returned.</li> * * </ul></li> * * <li>If the value you have specified for the <code>type</code> property * does not represent an array: * * <ul> * * <li>If you have specified a value for the <code>initial</code> * property, <code>ConvertUtils.convert</code> will be called to convert * it into an object instance.</li> * * <li>If you have not specified a value for the <code>initial</code> * attribute, Struts will instantiate an instance via the zero-args * constructor on the specified class (if any). Otherwise, * <code>null</code> will be returned.</li> * * </ul></li> * * </ul> */ public Object initial() { Object initialValue = null; try { Class clazz = getTypeClass(); if (clazz.isArray()) { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = Array.newInstance(clazz.getComponentType(), size); if (!(clazz.getComponentType().isPrimitive())) { for (int i = 0; i < size; i++) { try { Array.set(initialValue, i, clazz.getComponentType().newInstance()); } catch (Throwable t) { log.error("Unable to create instance of " + clazz.getName() + " for property=" + name + ", type=" + type + ", initial=" + initial + ", size=" + size + "."); //FIXME: Should we just dump the entire application/module ? } } } } } else { if (initial != null) { initialValue = ConvertUtils.convert(initial, clazz); } else { initialValue = clazz.newInstance(); } } } catch (Throwable t) { initialValue = null; } return (initialValue); }
From source file:org.apache.struts.service.factory.FactoryService.java
/** Initialize parameter to be used at bean creation process in bean factory. * Strategy to choose value to set tho the bean parameter - <br><p> * <li>if bean registration contains direct parameter setter - * parameter-value tag with value to be used for this parameter * then new parameter will initialized with it * <li>if parameter mapping has <code>force</code> attribute with * <code>true</code> value then value of the property * <code>value</code> from the <cede>ParameterMapping</code> * will be used as value for the parameter * <li>if <code>source</code> parameter supplied in parameter mapping * then retrieve value from specified source (default source - * request.parameter). If nothing found in specified source * (null value) then <code>value</code> attribute from * paramater mapping will be used as default value for parameter.</p> * /*from w w w . j a v a 2 s. c o m*/ * <p>Available sources - <br> * <li><code>request.parameter</code> - parameter of the request by name from * <code>name</code> attribute from parameterMapping * <li><code>request</code> or <code>request.attribute</code> - attribute * from request named by name from <code>name</code> attribute from * parameterMapping * <li><code>session</code> or <code>session.attribute</code> - attribute * from session named by name from <code>name</code> attribute from * parameterMapping * <li><code>application</code> or <code>application.attribute</code> - * attribute from application scope named by name from <code>name</code> * attribute from parameterMapping * <li><code>application.property</code> - value of the servlet property * named by name from <code>name</code> attribute from parameterMapping * <li><code>form</code> or <code>form.property</code> - value from form * mapped to this action if exists one. <code>name</code> attribute * from parameterMapping used as name of the property * </p> * * @param parameterMapping Mapping for parameter * @param registration Bean registration * @param request The servlet request we are processing * * @return Parameter */ public Parameter processParameterInit(ParameterMapping parameterMapping, Registration registration, HttpServletRequest request) throws Throwable { Parameter parameter = new Parameter(parameterMapping); Object parValue = registration.getParameterValue(parameterMapping.getName()); if (parValue != null) { parameter.setValue(ConvertUtils.convert((String) parValue, parameterMapping.getStub())); } else if (parameterMapping.getForce()) { parameter.setValue(ConvertUtils.convert(parameterMapping.getValue(), parameterMapping.getStub())); } else { String parameterSource = parameterMapping.getSource(); if (parameterSource == null) parameterSource = defaultParameterSource; if ("request".equals(parameterSource) || "request.attribute".equals(parameterSource)) { parValue = request.getAttribute(parameterMapping.getName()); if (parValue != null && parValue.getClass().getName().equals(parameterMapping.getType())) { parameter.setValue(parValue); } else { if (getDebug() >= 1) log("Attribute for parameter '" + parameterMapping.getName() + "' not found in request scope or type is different"); } } else if ("session".equals(parameterSource) || "session.attribute".equals(parameterSource)) { HttpSession session = ((HttpServletRequest) request).getSession(false); if (session != null) { parValue = session.getAttribute(parameterMapping.getName()); if (parValue != null && parValue.getClass().getName().equals(parameterMapping.getType())) { parameter.setValue(parValue); } else { if (getDebug() >= 1) log("Attribute for parameter '" + parameterMapping.getName() + "' not found in session scope or type is different"); } } } else if ("application".equals(parameterSource) || "application.attribute".equals(parameterSource)) { parValue = getServlet().getServletContext().getAttribute(parameterMapping.getName()); if (parValue != null && parValue.getClass().getName().equals(parameterMapping.getType())) { parameter.setValue(parValue); } else { if (getDebug() >= 1) log("Attribute for parameter '" + parameterMapping.getName() + "' not found in application scope or type is different"); } } else if ("application.property".equals(parameterSource)) { parameter.setValue(PropertyUtils.getProperty(this, parameterMapping.getName())); } else if ("form".equals(parameterSource) || "form.property".equals(parameterSource)) { parameter.setValue(PropertyUtils.getProperty(this, parameterMapping.getName())); } else { parameter.setValue(ConvertUtils.convert(request.getParameter(parameterMapping.getName()), parameterMapping.getStub())); } if (parameter.getValue() == null) { parameter.setValue(ConvertUtils.convert(parameterMapping.getValue(), parameterMapping.getStub())); } } return parameter; }
From source file:org.apache.struts.validator.BeanValidatorForm.java
/** * Set the value of a simple property with the specified name. * * @param name Name of the property whose value is to be set * @param value Value to which this property is to be set *//*from w w w .ja v a 2 s . c o m*/ public void set(String name, Object value) { // Set the page number (for validator) if ("page".equals(name)) { if (value == null) { page = 0; } else if (value instanceof Integer) { page = ((Integer) value).intValue(); } else { try { page = ((Integer) ConvertUtils.convert(value.toString(), Integer.class)).intValue(); } catch (Exception ignore) { page = 0; } } } dynaBean.set(name, value); }
From source file:org.apache.torque.dsfactory.AbstractDataSourceFactory.java
/** * Encapsulates setting configuration properties on * <code>DataSource</code> objects. * * @param property the property to read from the configuration * @param c the configuration to read the property from * @param ds the <code>DataSource</code> instance to write the property to * @throws Exception if anything goes wrong *//*from ww w.j av a 2 s. co m*/ protected void setProperty(String property, Configuration c, Object ds) throws Exception { if (c == null || c.isEmpty()) { return; } String key = property; Class<?> dsClass = ds.getClass(); int dot = property.indexOf('.'); try { if (dot > 0) { property = property.substring(0, dot); MappedPropertyDescriptor mappedPD = new MappedPropertyDescriptor(property, dsClass); Class<?> propertyType = mappedPD.getMappedPropertyType(); Configuration subProps = c.subset(property); // use reflection to set properties Iterator<?> j = subProps.getKeys(); while (j.hasNext()) { String subProp = (String) j.next(); String propVal = subProps.getString(subProp); Object value = ConvertUtils.convert(propVal, propertyType); PropertyUtils.setMappedProperty(ds, property, subProp, value); if (log.isDebugEnabled()) { log.debug( "setMappedProperty(" + ds + ", " + property + ", " + subProp + ", " + value + ")"); } } } else { if ("password".equals(key)) { // do not log value of password // for this, ConvertUtils.convert cannot be used // as it also logs the value of the converted property // so it is assumed here that the password is a String String value = c.getString(property); PropertyUtils.setSimpleProperty(ds, property, value); if (log.isDebugEnabled()) { log.debug("setSimpleProperty(" + ds + ", " + property + ", " + " (value not logged)" + ")"); } } else { Class<?> propertyType = PropertyUtils.getPropertyType(ds, property); Object value = ConvertUtils.convert(c.getString(property), propertyType); PropertyUtils.setSimpleProperty(ds, property, value); if (log.isDebugEnabled()) { log.debug("setSimpleProperty(" + ds + ", " + property + ", " + value + ")"); } } } } catch (RuntimeException e) { throw new TorqueRuntimeException("Runtime error setting property " + property, e); } catch (Exception e) { log.error("Property: " + property + " value: " + c.getString(key) + " is not supported by DataSource: " + ds.getClass().getName()); } }
From source file:org.apache.torque.JndiConfigurationTest.java
/** * Creates a Data Source from the Torque configuration without using Torque. * @return a SharedPoolDataSource source. * @throws Exception if we cannot create a Data source. *//* w w w.j a v a 2 s . c om*/ protected BasicDataSource getDataSource() throws Exception { Configuration torqueConfiguration = getTorqueConfiguraton(); String defaultDatabase = getDefaultDatabase(torqueConfiguration); Configuration dsfactoryConfiguration = torqueConfiguration .subset(Torque.TORQUE_KEY + "." + DataSourceFactory.DSFACTORY_KEY + "." + defaultDatabase + "." + AbstractDataSourceFactory.CONNECTION_KEY); BasicDataSource dataSource = new BasicDataSource(); for (Iterator i = dsfactoryConfiguration.getKeys(); i.hasNext();) { String key = (String) i.next(); String stringValue = dsfactoryConfiguration.getString(key); if ("user".equals(key)) { // setUser() in SharedPoolDataSouce corresponds to // setUsername() in BasicDataSourceFactory key = "username"; } else if ("driver".equals(key)) { // setDriver() in SharedPoolDataSouce corresponds to // setDriverClassName() in BasicDataSourceFactory key = "driverClassName"; } Class propertyType = PropertyUtils.getPropertyType(dataSource, key); Object value = ConvertUtils.convert(stringValue, propertyType); PropertyUtils.setSimpleProperty(dataSource, key, value); } return dataSource; }