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:com.redhat.rcm.maven.plugin.buildmetadata.data.MetaDataProviderBuilder.java
private void setProperty(final MetaDataProvider instance, final String propertyName, final String propertyValue) throws MojoExecutionException { final Class<? extends MetaDataProvider> metaDataProviderClass = instance.getClass(); try {/*from w w w. j a v a 2s . c om*/ final Field field = findField(metaDataProviderClass, propertyName); field.setAccessible(true); final Class<?> type = field.getType(); final Object typedPropertyValue = ConvertUtils.convert(propertyValue, type); field.set(instance, typedPropertyValue); } catch (final Exception e) { throw new MojoExecutionException("Cannot set property '" + propertyName + "' to value '" + propertyValue + "' for the instance of class '" + metaDataProviderClass.getName() + "'.", e); } }
From source file:ReflectionUtils.java
/** * clazzproperty.//from w w w .j av a 2 s . c o m * * @param value * * @param clazz * Class * @param propertyName * Class. */ public static Object convertValue(Object value, Class<?> toType) { try { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); ConvertUtils.register(dc, Date.class); return ConvertUtils.convert(value, toType); } catch (Exception e) { throw convertToUncheckedException(e); } }
From source file:com.xyz.util.ReflectionUtil.java
/** * ?clazzproperty./* w w w . j av a2 s .co m*/ * * @param value ? * @param clazz ???Class * @param propertyName ???Class. */ public static Object convertValue(Object value, Class<?> toType) { try { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); ConvertUtils.register(dc, Date.class); return ConvertUtils.convert(value.toString(), toType); } catch (Exception e) { throw convertToUncheckedException(e); } }
From source file:com.rodaxsoft.mailgun.MailingListMemberManager.java
/** * Converts the <code>vars</code> object into an instance of the varsType and * returns the members of the mailing list * @param varsType The target type for the <i>vars</i> object. * <i>Note: If no registered {@link Converter} is found for the varsType, * a {@link ContextedRuntimeException} will be thrown.</i> * @return A list of list member objects * @throws ContextedException If no registered {@link Converter} is found for the varsType * @see ConvertUtils#register(Converter, Class) * @since 0.2/* w ww . j a v a 2 s .c o m*/ * */ List<ListMember> getListMembers(Class<?> varsType) throws ContextedException { List<ListMember> members = null; if (varsType != null) { if (ConvertUtils.lookup(varsType) != null) { listMemberConverter.setVarClass(varsType); } else { ContextedException cre; cre = new ContextedException("No registered Converter for varType"); cre.addContextValue("varType", varsType.getName()); throw cre; } } final String path = "/lists/" + listAddress + "/members"; RESTResponse response = invokeGet(path); if (response.success()) { JSONObject jsonObj = response.toJSONObject(); JSONArray jsonArray = jsonObj.getJSONArray("items"); @SuppressWarnings("unchecked") Iterator<JSONObject> iter = jsonArray.iterator(); while (iter.hasNext()) { JSONObject obj = iter.next(); if (null == members) { members = new ArrayList<>(); } ListMember lm = (ListMember) ConvertUtils.convert(obj, ListMember.class); members.add(lm); } } return members; }
From source file:com.abssh.util.ReflectionUtils.java
/** * ??// w w w .j av a 2 s .c o m * * @param value * ? * @param toType * */ public static Object convertValue(Object value, Class<?> toType) { if (value == null) { return null; } if (value.equals("") && toType.getName().equals("java.util.Date")) { return null; } try { DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); ConvertUtils.register(dc, Date.class); return ConvertUtils.convert(value, toType); } catch (Exception e) { throw convertReflectionExceptionToUnchecked(e); } }
From source file:info.magnolia.jcr.util.PropertiesImportExport.java
protected Object convertPropertyStringToObject(String valueStr) { if (contains(valueStr, ':')) { final String type = StringUtils.substringBefore(valueStr, ":"); final String value = StringUtils.substringAfter(valueStr, ":"); // there is no beanUtils converter for Calendar if (type.equalsIgnoreCase("date")) { return ISO8601.parse(value); } else if (type.equalsIgnoreCase("binary")) { return new ByteArrayInputStream(value.getBytes()); } else {/*ww w .j a v a 2 s . c om*/ try { final Class<?> typeCl; if (type.equals("int")) { typeCl = Integer.class; } else { typeCl = Class.forName("java.lang." + StringUtils.capitalize(type)); } return ConvertUtils.convert(value, typeCl); } catch (ClassNotFoundException e) { // possibly a stray :, let's ignore it for now return valueStr; } } } // no type specified, we assume it's a string, no conversion return valueStr; }
From source file:net.sf.json.JSONDynaBean.java
/** * DOCUMENT ME!/*from w w w .ja v a 2s . c om*/ * * @param name DOCUMENT ME! * @param value DOCUMENT ME! */ public void set(String name, Object value) { DynaProperty property = getDynaProperty(name); if (property.getType() == null) { throw new NullPointerException("Unspecified property type for " + name); } if (value == null) { if (property.getType().isPrimitive()) { throw new NullPointerException("Property type for " + name + " is primitive"); } } else if (!isDynaAssignable(property.getType(), value.getClass())) { try { value = ConvertUtils.convert(String.valueOf(value), value.getClass()); } catch (Exception e) { throw new IllegalArgumentException("Unassignable property type for " + name); } } // log.debug( name + " = " + value ); dynaValues.put(name, value); }
From source file:com.conversantmedia.mapreduce.tool.DistributedResourceManager.java
private static Object getResourceValue(Field field, String valueString, String originalTypeClassname, Path[] distFiles) throws IOException, ClassNotFoundException { // First, determine our approach: Object value = null;/* w w w . j a va 2s . co m*/ if (field.getType().isAssignableFrom(String.class)) { value = valueString; } else if (ClassUtils.isPrimitiveOrWrapper(field.getType())) { value = ConvertUtils.convert(valueString, field.getType()); } else { Path path = distributedFilePath(valueString, distFiles); // This is something on the distributed cache (or illegal) if (field.getType() == Path.class) { value = path; } else if (field.getType() == File.class) { value = new File(path.toUri()); } // Deserialize .ser file else if (field.getType().isAssignableFrom(Class.forName(originalTypeClassname))) { ObjectInputStream in = null; try { File beanSerFile = new File(path.toUri().getPath()); FileInputStream fileIn = new FileInputStream(beanSerFile); in = new ObjectInputStream(fileIn); value = in.readObject(); } finally { IOUtils.closeQuietly(in); } } else { throw new IllegalArgumentException("Cannot locate resource for field [" + field.getName() + "]"); } } return value; }
From source file:com.xyz.util.ReflectionUtil.java
/** * ?clazzproperty.//from w ww . ja va2 s . c o m * * @param value ? * @param clazz ???Class * @param propertyName ???Class. */ public static Object convertValue(Object value, Class<?> clazz, String propertyName) { try { Class<?> toType = BeanUtils.getPropertyDescriptor(clazz, propertyName).getPropertyType(); DateConverter dc = new DateConverter(); dc.setUseLocaleFormat(true); dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" }); ConvertUtils.register(dc, Date.class); //String???'' if (toType.equals(String.class)) value = "'" + value + "'"; return ConvertUtils.convert(value.toString(), toType); } catch (Exception e) { throw convertToUncheckedException(e); } }
From source file:net.sf.qooxdoo.rpc.RpcServlet.java
/** * Looks up an instance of a service and creates one if necessary. * * @param session the current session (for storing * instances). * @param serviceClassName the fully qualified name of the class * to instantiate. * @param name the name to use for the instance. * @param requiredType The type the service must have. May be * null. /*from w ww .j av a 2s . co m*/ */ public synchronized Service getServiceInstance(HttpSession session, String serviceClassName, Object name, Class requiredType) throws ClassNotFoundException, IllegalAccessException, InstantiationException, InvocationTargetException, NoSuchMethodException { if (requiredType == null) { requiredType = Service.class; } String lookFor = serviceClassName; if (name != null) { lookFor += "/" + name; } Service inst = (Service) session.getAttribute(lookFor); if (inst == null) { Class clazz = Class.forName(serviceClassName); if (!requiredType.isAssignableFrom(clazz)) { throw new ClassCastException("The requested service class " + clazz.getName() + " is not from the required type " + requiredType.getName() + ""); } inst = (Service) clazz.newInstance(); Class[] paramTypes = new Class[1]; Object[] params = new Object[1]; paramTypes[0] = Environment.class; Method method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentEnvironment", paramTypes); if (method == null) { method = MethodUtils.getMatchingAccessibleMethod(clazz, "setQooxdooEnvironment", paramTypes); } if (method != null) { params[0] = new Environment(); method.invoke(inst, params); } if (name != null) { paramTypes[0] = String.class; method = MethodUtils.getMatchingAccessibleMethod(clazz, "setWebcomponentName", paramTypes); if (method != null) { params[0] = name; method.invoke(inst, params); } } session.setAttribute(lookFor, inst); // initialize the service properties ServletConfig servletConfig = getServletConfig(); Enumeration initParamNames = servletConfig.getInitParameterNames(); String initParamName; String initParamValue; int pos; String packageName; String propertyName; HashMap candidates = new HashMap(); while (initParamNames.hasMoreElements()) { initParamName = (String) initParamNames.nextElement(); pos = initParamName.lastIndexOf('.'); if (pos == -1) { packageName = ""; propertyName = initParamName; } else { packageName = initParamName.substring(0, pos); propertyName = initParamName.substring(pos + 1); } String candidateName; if (serviceClassName.startsWith(packageName)) { candidateName = (String) candidates.get(propertyName); if (candidateName == null) { candidates.put(propertyName, initParamName); } else if (candidateName.length() < initParamName.length()) { candidates.put(propertyName, initParamName); } } } Iterator candidatesIterator = candidates.keySet().iterator(); Class propertyType; while (candidatesIterator.hasNext()) { propertyName = (String) candidatesIterator.next(); initParamName = (String) candidates.get(propertyName); initParamValue = servletConfig.getInitParameter(initParamName); propertyType = PropertyUtils.getPropertyType(inst, propertyName); if (propertyType != null) { if (propertyType.getComponentType() == String.class) { PropertyUtils.setSimpleProperty(inst, propertyName, StringUtils.tokenize(initParamValue, ';')); } else { try { PropertyUtils.setSimpleProperty(inst, propertyName, ConvertUtils.convert(initParamValue, propertyType)); } catch (Exception e) { // try to instatiate a class of the supplied parameter //System.out.println("***** setting '" + propertyName + "' to an instance of '" + initParamValue + "'"); PropertyUtils.setSimpleProperty(inst, propertyName, getServiceInstance(session, initParamValue, null, null)); } } } else { //System.out.println("***** property '" + propertyName + "' not matched"); } } // tell the instance that we're done paramTypes = new Class[0]; method = MethodUtils.getMatchingAccessibleMethod(clazz, "webcomponentInit", paramTypes); if (method != null) { params = new Object[0]; method.invoke(inst, params); } } return inst; }