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.ms123.common.data.JdoLayerImpl.java
public void populate(SessionContext sessionContext, Map from, Object to, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from w w w. j a va 2 s . c o m Map<String, String> expressions = (Map) hintsMap.get("__expressions"); if (expressions == null) expressions = new HashMap(); BeanMap beanMap = new BeanMap(to); String entityName = m_inflector.getEntityName(to.getClass().getSimpleName()); debug("populate.from:" + from + ",to:" + to + ",BeanMap:" + beanMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (from == null) { return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = from.keySet().iterator(); while (it.hasNext()) { String key = it.next(); Object oldValue = beanMap.get(key); boolean permitted = m_permissionService.hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(key, entityName, "write"); if (!key.startsWith("_") && !permitted) { debug("---->populate:field(" + key + ") no write permission"); continue; } else { debug("++++>populate:field(" + key + ") write permitted"); } String datatype = null; String edittype = null; if (!key.startsWith("_")) { Map config = (Map) permittedFields.get(key); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (key.equals(STATE_FIELD) && !m_permissionService.hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(key); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class clazz = beanMap.getType(key); debug("\ttype:" + clazz + "(" + key + "=" + from.get(key) + ")"); if ("_ignore_".equals(from.get(key))) { continue; } if (clazz == null) { debug("\t--- Warning property not found:" + key); } else if (clazz.equals(java.util.Date.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); debug("\tDate found:" + key + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); beanMap.put(key, date); } else if (clazz.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (clazz.equals(java.util.List.class) || clazz.equals(java.util.Set.class)) { boolean isList = clazz.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class type = TypeUtils.getTypeForField(to, key); debug("type:" + type + " fill with: " + from.get(key) + ",list:" + beanMap.get(key) + "/mode:" + mode); Collection valList = isList ? new ArrayList() : new HashSet(); Object fromVal = from.get(key); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (from.get(key) instanceof Collection) { valList = (Collection) from.get(key); } if (valList == null) { valList = isList ? new ArrayList() : new HashSet(); } Collection toList = (Collection) PropertyUtils.getProperty(to, key); debug("toList:" + toList); debug("valList:" + valList); if (toList == null) { toList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(to, key, toList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(toList, valList); if (!isEqual) { toList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : toList) { if (type.getName().endsWith(".Team")) { int status = m_teamService.getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { toList.remove(o); } } debug("populate.replace.toList:" + toList + "/" + type.getName()); if (isSimple) { if (!isEqual) { for (Object o : valList) { toList.add(o); } } } else { for (Object o : valList) { Map valMap = (Map) o; Object n = type.newInstance(); if (type.getName().endsWith(".Team")) { valMap.remove("id"); Object desc = valMap.get("description"); Object name = valMap.get("name"); Object dis = valMap.get("disabled"); String teamid = (String) valMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { valMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { valMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { valMap.put("disabled", false); } pm.makePersistent(n); populate(sessionContext, valMap, n, null); PropertyUtils.setProperty(n, "teamintern", ti); } else { pm.makePersistent(n); populate(sessionContext, valMap, n, null); } debug("populated.add:" + new HashMap(new BeanMap(n))); toList.add(n); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : valList) { if (toList.contains(o)) { toList.remove(o); } } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { toList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : valList) { toList.add(o); } } else { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map, "teamid"); if (o != null) { populate(sessionContext, map, o, null); } else { o = type.newInstance(); if (type.getName().endsWith(".Team")) { Object desc = map.get("description"); Object name = map.get("name"); Object dis = map.get("disabled"); String teamid = (String) map.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { map.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { map.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { map.put("disabled", false); } pm.makePersistent(o); populate(sessionContext, map, o, null); PropertyUtils.setProperty(o, "teamintern", ti); } else { pm.makePersistent(o); populate(sessionContext, map, o, null); } toList.add(o); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : valList) { Map map = (Map) ol; Object o = Utils.listContainsId(toList, map); if (o != null) { debug("id:" + map + " already assigned"); } else { Object id = map.get("id"); Boolean assign = Utils.getBoolean(map.get("assign")); Object obj = pm.getObjectById(type, id); if (assign) { toList.add(obj); } else { toList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Boolean.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Double.class)) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); try { beanMap.put(key, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + key + "=>" + value + ";" + e); } } else if (clazz.equals(java.lang.Long.class)) { try { beanMap.put(key, ConvertUtils.convert(from.get(key), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if (clazz.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(from.get(key), Integer.class)); try { beanMap.put(key, ConvertUtils.convert(from.get(key), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + key + "=>" + from.get(key) + ";" + e); } } else if ("binary".equals(datatype) || clazz.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (from.get(key) instanceof FileItem) { FileItem fi = (FileItem) from.get(key); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } beanMap.put(key, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (from.get(key) instanceof Map) { Map map = (Map) from.get(key); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); beanMap.put(key, bytes); is = new FileInputStream(new File(storeLocation)); } else if (from.get(key) instanceof String) { String value = (String) from.get(key); if ("ignore".equals(value)) { debug("ignore:"); return; } if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { byte b[] = value.getBytes(); beanMap.put(key, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } } else { debug("populate.byte[].no a FileItem:" + key + "=>" + from.get(key)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { beanMap.put("text", text); } catch (Exception e) { beanMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); beanMap.put("type", mime.toString()); from.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + key + "=>" + from.get(key) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class type = TypeUtils.getTypeForField(to, key); if (type != null) { Object o = type.newInstance(); boolean hasAnn = type.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (o instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { Object id = null; try { Object _id = from.get(key); if (_id != null) { if (_id instanceof Map) { id = ((Map) _id).get("id"); } else { String s = String.valueOf(_id); if (s.indexOf("/") >= 0) { _id = Utils.extractId(s); } Class idClass = PropertyUtils.getPropertyType(o, "id"); id = (idClass.equals(Long.class)) ? Long.valueOf(_id + "") : _id; } } } catch (Exception e) { } if (id != null && !"".equals(id) && !"null".equals(id)) { debug("\tId2:" + id); Object relatedObject = pm.getObjectById(type, id); List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (!l.contains(to)) { l.add(to); } } beanMap.put(key, relatedObject); } else { Object relatedObject = beanMap.get(key); debug("\trelatedObject:" + relatedObject); if (relatedObject != null) { List<Collection> candidates = TypeUtils.getCandidateLists(relatedObject, to, null); if (candidates.size() == 1) { Collection l = candidates.get(0); debug("list.contains:" + l.contains(to)); if (l.contains(to)) { l.remove(to); } } } beanMap.put(key, null); } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(from.get(key), beanMap.get(key), mode); // debug("populate:" + key + "=>" + value); // debug("String:" + ConvertUtils.convert(from.get(key), String.class)); try { beanMap.put(key, value); } catch (Exception e) { debug("populate.failed:" + key + "=>" + value + ";" + e); } } } String expression = expressions.get(key); if (!isEmpty(expression)) { beanMap.put(key, oldValue); Map scriptCache = (Map) sessionContext.getProperty("scriptCache"); if (scriptCache == null) { scriptCache = new HashMap(); sessionContext.setProperty("scriptCache", scriptCache); } Object result = Utils.eval(expression, beanMap, scriptCache); try { if ("string".equals(datatype) && !(result instanceof String)) { beanMap.put(key, ConvertUtils.convert(result, String.class)); } else { beanMap.put(key, result); } } catch (Exception e) { info("Cannot set value for(" + key + "):" + result + "/" + e.getMessage()); } } } }
From source file:org.ms123.common.data.JdoLayerImpl.java
private void setDefaultValues(Class clazz, Object o) throws Exception { debug("----->setDefaultValues.clazz:" + clazz + "/" + o); Field[] fields = clazz.getDeclaredFields(); for (int i = 0; i < fields.length; i++) { java.lang.annotation.Annotation[] anns = fields[i].getDeclaredAnnotations(); for (int j = 0; j < anns.length; j++) { try { Class atype = anns[j].annotationType(); if (!(anns[j] instanceof javax.jdo.annotations.Column)) { continue; }//from www . j ava 2 s .com Method methDf = atype.getDeclaredMethod("defaultValue"); //Method methAn = atype.getDeclaredMethod("allowsNull");//@@@MS ???? String df = (String) methDf.invoke(anns[j], new Object[0]); //String al = (String) methAn.invoke(anns[j], new Object[0]); if (df != null && df.length() > 0) { Class type = TypeUtils.getTypeForField(o, fields[i].getName()); Object v = ConvertUtils.convert(df, type); debug("setDefaultValues:" + fields[i].getName() + ":" + v + "/" + type); PropertyUtils.setProperty(o, fields[i].getName(), v); } } catch (Exception e) { debug("setDefaultValues.e:" + e); } } } }
From source file:org.ms123.common.data.MultiOperations.java
public static void populate(SessionContext sessionContext, Map sourceMap, Object destinationObj, Map hintsMap) { PersistenceManager pm = sessionContext.getPM(); if (hintsMap == null) { hintsMap = new HashMap(); }//from w ww . j av a 2 s .c om boolean noUpdate = Utils.getBoolean(hintsMap, "noUpdate", false); BeanMap destinationMap = new BeanMap(destinationObj); String entityName = m_inflector.getEntityName(destinationObj.getClass().getSimpleName()); debug("populate.sourceMap:" + sourceMap + ",destinationObj:" + destinationObj + ",destinationMap:" + destinationMap + "/hintsMap:" + hintsMap + "/entityName:" + entityName); if (sourceMap == null) { return; } debug("populate(" + entityName + ") is a persistObject:" + javax.jdo.JDOHelper.isPersistent(destinationObj) + "/" + javax.jdo.JDOHelper.isNew(destinationObj)); if (sourceMap.get("id") != null) { debug("populate(" + entityName + ") has id:" + sourceMap.get("id")); return; } Map permittedFields = sessionContext.getPermittedFields(entityName, "write"); Iterator<String> it = sourceMap.keySet().iterator(); while (it.hasNext()) { String propertyName = it.next(); boolean permitted = sessionContext.getPermissionService().hasAdminRole() || "team".equals(entityName) || sessionContext.isFieldPermitted(propertyName, entityName, "write"); if (!propertyName.startsWith("_") && !permitted) { debug("---->populate:field(" + propertyName + ") no write permission"); continue; } else { debug("++++>populate:field(" + propertyName + ") write permitted"); } String datatype = null; String edittype = null; if (!propertyName.startsWith("_")) { Map config = (Map) permittedFields.get(propertyName); if (config != null) { datatype = (String) config.get("datatype"); edittype = (String) config.get("edittype"); } } if (propertyName.equals(STATE_FIELD) && !sessionContext.getPermissionService().hasAdminRole()) { continue; } if ("auto".equals(edittype)) continue; String mode = null; Map hm = (Map) hintsMap.get(propertyName); if (hm != null) { Object m = hm.get("mode"); if (m != null && m instanceof String) { mode = (String) m; } if (mode == null) { m = hm.get("useit"); if (m != null && m instanceof String) { mode = (String) m; } } } if (mode == null) { mode = "replace"; } Class propertyClass = destinationMap.getType(propertyName); debug("\ttype:" + propertyClass + "(" + propertyName + "=" + sourceMap.get(propertyName) + ")"); if ("_ignore_".equals(sourceMap.get(propertyName))) { continue; } if (propertyClass == null) { debug("\t--- Warning property not found:" + propertyName); } else if (propertyClass.equals(java.util.Date.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); debug("\tDate found:" + propertyName + "=>" + value); Date date = null; if (value != null) { try { Long val = Long.valueOf(value); date = (Date) ConvertUtils.convert(val, Date.class); debug("\tdate1:" + date); } catch (Exception e) { try { DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); debug("\tdate2:" + date); } catch (Exception e1) { try { int space = value.indexOf(" "); if (space != -1) { value = value.substring(0, space) + "T" + value.substring(space + 1); DateTime dt = new DateTime(value); date = new Date(dt.getMillis()); } debug("\tdate3:" + date); } catch (Exception e2) { debug("\terror setting date:" + e); } } } } debug("\tsetting date:" + date); destinationMap.put(propertyName, date); } else if (propertyClass.equals(java.util.Map.class)) { info("!!!!!!!!!!!!!!!!!!!Map not implemented"); } else if (propertyClass.equals(java.util.List.class) || propertyClass.equals(java.util.Set.class)) { boolean isList = propertyClass.equals(java.util.List.class); boolean isSimple = false; if (datatype != null && datatype.startsWith("list_")) { isSimple = true; } try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + " fill with: " + sourceMap.get(propertyName) + ",list:" + destinationMap.get(propertyName) + "/mode:" + mode); Collection sourceList = isList ? new ArrayList() : new HashSet(); Object fromVal = sourceMap.get(propertyName); if (fromVal instanceof String && ((String) fromVal).length() > 0) { info("FromVal is StringSchrott, ignore"); continue; } if (sourceMap.get(propertyName) instanceof Collection) { sourceList = (Collection) sourceMap.get(propertyName); } if (sourceList == null) { sourceList = isList ? new ArrayList() : new HashSet(); } Collection destinationList = (Collection) PropertyUtils.getProperty(destinationObj, propertyName); debug("destinationList:" + destinationList); debug("sourceList:" + sourceList); if (destinationList == null) { destinationList = isList ? new ArrayList() : new HashSet(); PropertyUtils.setProperty(destinationObj, propertyName, destinationList); } if ("replace".equals(mode)) { boolean isEqual = false; if (isSimple) { isEqual = Utils.isCollectionEqual(destinationList, sourceList); if (!isEqual) { destinationList.clear(); } debug("\tisEqual:" + isEqual); } else { List deleteList = new ArrayList(); String namespace = sessionContext.getStoreDesc().getNamespace(); for (Object o : destinationList) { if (propertyType.getName().endsWith(".Team")) { int status = sessionContext.getTeamService().getTeamStatus(namespace, new BeanMap(o), null, sessionContext.getUserName()); debug("populate.replace.teamStatus:" + status + "/" + new HashMap(new BeanMap(o))); if (status != -1) { pm.deletePersistent(o); deleteList.add(o); } } else { pm.deletePersistent(o); deleteList.add(o); } } for (Object o : deleteList) { destinationList.remove(o); } } debug("populate.replace.destinationList:" + destinationList + "/" + propertyType.getName()); if (isSimple) { if (!isEqual) { for (Object o : sourceList) { destinationList.add(o); } } } else { for (Object o : sourceList) { Map childSourceMap = (Map) o; Object childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { childSourceMap.remove("id"); Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } debug("populated.add:" + new HashMap(new BeanMap(childDestinationObj))); destinationList.add(childDestinationObj); } } } else if ("remove".equals(mode)) { if (isSimple) { for (Object o : sourceList) { if (destinationList.contains(o)) { destinationList.remove(o); } } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object o = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (o != null) { destinationList.remove(o); pm.deletePersistent(o); } } } } else if ("add".equals(mode)) { if (isSimple) { for (Object o : sourceList) { destinationList.add(o); } } else { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap, "teamid"); if (childDestinationObj != null) { populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { childDestinationObj = propertyType.newInstance(); if (propertyType.getName().endsWith(".Team")) { Object desc = childSourceMap.get("description"); Object name = childSourceMap.get("name"); Object dis = childSourceMap.get("disabled"); String teamid = (String) childSourceMap.get("teamid"); Object ti = Utils.getTeamintern(sessionContext, teamid); if (desc == null) { childSourceMap.put("description", PropertyUtils.getProperty(ti, "description")); } if (name == null) { childSourceMap.put("name", PropertyUtils.getProperty(ti, "name")); } if (dis == null) { childSourceMap.put("disabled", false); } pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); PropertyUtils.setProperty(childDestinationObj, "teamintern", ti); } else { pm.makePersistent(childDestinationObj); populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } destinationList.add(childDestinationObj); } } } } else if ("assign".equals(mode)) { if (!isSimple) { for (Object ol : sourceList) { Map childSourceMap = (Map) ol; Object childDestinationObj = Utils.listContainsId(destinationList, childSourceMap); if (childDestinationObj != null) { debug("id:" + childSourceMap + " already assigned"); } else { Object id = childSourceMap.get("id"); Boolean assign = Utils.getBoolean(childSourceMap.get("assign")); Object obj = pm.getObjectById(propertyType, id); if (assign) { destinationList.add(obj); } else { destinationList.remove(obj); } } } } } } catch (Exception e) { e.printStackTrace(); debug("populate.list.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Boolean.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Boolean.class)); } catch (Exception e) { debug("populate.boolean.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Double.class)) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { destinationMap.put(propertyName, Double.valueOf(value)); } catch (Exception e) { debug("populate.double.failed:" + propertyName + "=>" + value + ";" + e); } } else if (propertyClass.equals(java.lang.Long.class)) { try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Long.class)); } catch (Exception e) { debug("populate.long.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if (propertyClass.equals(java.lang.Integer.class)) { debug("Integer:" + ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); try { destinationMap.put(propertyName, ConvertUtils.convert(sourceMap.get(propertyName), Integer.class)); } catch (Exception e) { debug("populate.integer.failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } } else if ("binary".equals(datatype) || propertyClass.equals(byte[].class)) { InputStream is = null; InputStream is2 = null; try { if (sourceMap.get(propertyName) instanceof FileItem) { FileItem fi = (FileItem) sourceMap.get(propertyName); String name = fi.getName(); byte[] bytes = IOUtils.toByteArray(fi.getInputStream()); if (bytes != null) { debug("bytes:" + bytes.length); } destinationMap.put(propertyName, bytes); is = fi.getInputStream(); is2 = fi.getInputStream(); } else if (sourceMap.get(propertyName) instanceof Map) { Map map = (Map) sourceMap.get(propertyName); String storeLocation = (String) map.get("storeLocation"); is = new FileInputStream(new File(storeLocation)); is2 = new FileInputStream(new File(storeLocation)); byte[] bytes = IOUtils.toByteArray(is); if (bytes != null) { debug("bytes2:" + bytes.length); } is.close(); destinationMap.put(propertyName, bytes); is = new FileInputStream(new File(storeLocation)); } else if (sourceMap.get(propertyName) instanceof String) { String value = (String) sourceMap.get(propertyName); if (value.startsWith("data:")) { int ind = value.indexOf(";base64,"); byte b[] = Base64.decode(value.substring(ind + 8)); destinationMap.put(propertyName, b); is = new ByteArrayInputStream(b); is2 = new ByteArrayInputStream(b); } else { } } else { debug("populate.byte[].no a FileItem:" + propertyName + "=>" + sourceMap.get(propertyName)); continue; } Tika tika = new Tika(); TikaInputStream stream = TikaInputStream.get(is); TikaInputStream stream2 = TikaInputStream.get(is2); String text = tika.parseToString(is); debug("Text:" + text); try { destinationMap.put("text", text); } catch (Exception e) { destinationMap.put("text", text.getBytes()); } //@@@MS Hardcoded try { Detector detector = new DefaultDetector(); MediaType mime = detector.detect(stream2, new Metadata()); debug("Mime:" + mime.getType() + "|" + mime.getSubtype() + "|" + mime.toString()); destinationMap.put("type", mime.toString()); sourceMap.put("type", mime.toString()); } catch (Exception e) { e.printStackTrace(); } } catch (Exception e) { e.printStackTrace(); debug("populate.byte[].failed:" + propertyName + "=>" + sourceMap.get(propertyName) + ";" + e); } finally { try { is.close(); is2.close(); } catch (Exception e) { } } } else { boolean ok = false; try { Class propertyType = TypeUtils.getTypeForField(destinationObj, propertyName); debug("propertyType:" + propertyType + "/" + propertyName); if (propertyType != null) { boolean hasAnn = propertyType.isAnnotationPresent(PersistenceCapable.class); debug("hasAnnotation:" + hasAnn); if (propertyType.newInstance() instanceof javax.jdo.spi.PersistenceCapable || hasAnn) { handleRelatedTo(sessionContext, sourceMap, propertyName, destinationMap, destinationObj, propertyType); Object obj = sourceMap.get(propertyName); if (obj != null && obj instanceof Map) { Map childSourceMap = (Map) obj; Object childDestinationObj = destinationMap.get(propertyName); if (childDestinationObj == null) { childDestinationObj = propertyType.newInstance(); destinationMap.put(propertyName, childDestinationObj); } populate(sessionContext, childSourceMap, childDestinationObj, hintsMap); } else { if (obj == null) { destinationMap.put(propertyName, null); } } ok = true; } } } catch (Exception e) { e.printStackTrace(); } if (!ok) { String value = Utils.getString(sourceMap.get(propertyName), destinationMap.get(propertyName), mode); try { if (noUpdate) { if (Utils.isEmptyObj(destinationMap.get(propertyName))) { destinationMap.put(propertyName, value); } } else { destinationMap.put(propertyName, value); } } catch (Exception e) { debug("populate.failed:" + propertyName + "=>" + value + ";" + e); } } } } }
From source file:org.ms123.common.system.call.BaseCallServiceImpl.java
public static Object convertTo(Object sourceObject, Class<?> targetClass) { try {/*from w w w . j a v a2 s . c o m*/ return ConvertUtils.convert(sourceObject, targetClass); } catch (Exception e) { e.printStackTrace(); } return null; }
From source file:org.onebusaway.siri.core.filters.ElementPathModuleDeliveryFilter.java
private Object convertValue(Object value, Class<?> targetType) { if (value == null) return value; Class<? extends Object> existingType = value.getClass(); if (targetType.isAssignableFrom(existingType)) return value; return ConvertUtils.convert(value, targetType); }
From source file:org.opencms.configuration.CmsSetNextRule.java
/** * Process the end of this element.<p> * //w ww. j av a2 s. c om * @param namespace the namespace URI of the matching element, or an empty string if the parser is not namespace * aware or the element has no namespace * @param name the local name if the parser is namespace aware, or just the element name otherwise * @throws Exception if something goes wrong */ @Override public void end(String namespace, String name) throws Exception { // Determine the target object for the method call: the parent object Object parent = digester.peek(1); Object child = digester.peek(0); // Retrieve or construct the parameter values array Object[] parameters = null; if (m_paramCount > 0) { parameters = (Object[]) digester.popParams(); if (LOG.isTraceEnabled()) { for (int i = 0, size = parameters.length; i < size; i++) { LOG.trace("[SetNextRuleWithParams](" + i + ")" + parameters[i]); } } // In the case where the target method takes a single parameter // and that parameter does not exist (the CallParamRule never // executed or the CallParamRule was intended to set the parameter // from an attribute but the attribute wasn't present etc) then // skip the method call. // // This is useful when a class has a "default" value that should // only be overridden if data is present in the XML. I don't // know why this should only apply to methods taking *one* // parameter, but it always has been so we can't change it now. if ((m_paramCount == 1) && (parameters[0] == null)) { return; } } else if (m_paramTypes.length != 0) { // Having paramCount == 0 and paramTypes.length == 1 indicates // that we have the special case where the target method has one // parameter being the body text of the current element. // There is no body text included in the source XML file, // so skip the method call if (m_bodyText == null) { return; } parameters = new Object[1]; parameters[0] = m_bodyText; if (m_paramTypes.length == 0) { m_paramTypes = new Class[1]; m_paramTypes[0] = String.class; } } else { // When paramCount is zero and paramTypes.length is zero it // means that we truly are calling a method with no parameters. // Nothing special needs to be done here. parameters = new Object[0]; } // Construct the parameter values array we will need // We only do the conversion if the param value is a String and // the specified paramType is not String. Object[] paramValues = new Object[m_paramTypes.length]; Class<?> propertyClass = child.getClass(); for (int i = 0; i < m_paramTypes.length; i++) { if (m_paramTypes[i] == propertyClass) { // implant the original child to set if Class matches: paramValues[i] = child; } else if ((parameters[i] == null) || ((parameters[i] instanceof String) && !String.class.isAssignableFrom(m_paramTypes[i]))) { // convert nulls and convert stringy parameters // for non-stringy param types if (parameters[i] == null) { paramValues[i] = null; } else { paramValues[i] = ConvertUtils.convert((String) parameters[i], m_paramTypes[i]); } } else { paramValues[i] = parameters[i]; } } if (parent == null) { StringBuffer sb = new StringBuffer(); sb.append("[SetNextRuleWithParams]{"); sb.append(digester.getMatch()); sb.append("} Call target is null ("); sb.append("targetOffset="); sb.append(m_targetOffset); sb.append(",stackdepth="); sb.append(digester.getCount()); sb.append(")"); throw new org.xml.sax.SAXException(sb.toString()); } // Invoke the required method on the top object if (LOG.isDebugEnabled()) { StringBuffer sb = new StringBuffer("[SetNextRuleWithParams]{"); sb.append(digester.getMatch()); sb.append("} Call "); sb.append(parent.getClass().getName()); sb.append("."); sb.append(m_methodName); sb.append("("); for (int i = 0; i < paramValues.length; i++) { if (i > 0) { sb.append(","); } if (paramValues[i] == null) { sb.append("null"); } else { sb.append(paramValues[i].toString()); } sb.append("/"); if (m_paramTypes[i] == null) { sb.append("null"); } else { sb.append(m_paramTypes[i].getName()); } } sb.append(")"); LOG.debug(sb.toString()); } Object result = null; if (m_useExactMatch) { // invoke using exact match result = MethodUtils.invokeExactMethod(parent, m_methodName, paramValues, m_paramTypes); } else { // invoke using fuzzier match result = MethodUtils.invokeMethod(parent, m_methodName, paramValues, m_paramTypes); } processMethodCallResult(result); }
From source file:org.openhie.openempi.util.TestConversions.java
public static void exploringBeanUtils() { Person person = new Person(); person.setAddress1("2930 Oak Shadow Drive"); person.setCity("Oak Hill"); PersonIdentifier id = new PersonIdentifier(); id.setIdentifier("1234"); IdentifierDomain domain = new IdentifierDomain(); domain.setIdentifierDomainName("testDomain"); domain.setNamespaceIdentifier("testDomain"); id.setIdentifierDomain(domain);/*from w ww . j a v a2 s . c om*/ person.addPersonIdentifier(id); Nationality nationality = new Nationality(); nationality.setNationalityCd(100); person.setNationality(nationality); person.setDateOfBirth(new java.util.Date()); ConvertingWrapDynaBean bean = new ConvertingWrapDynaBean(person); System.out.println("Build a dyna bean using my person:"); System.out.println(bean.get("address1")); System.out.println(bean.get("dateOfBirth")); System.out.println("Changing some of the values."); bean.set("givenName", "Odysseas"); bean.set("familyName", "Pentakalos"); System.out.println(bean.get("nationality.nationalityCd")); bean.set("nationality.nationalityCd", "150"); System.out.println("Value " + bean.get("nationality.nationalityCd") + " is of type " + bean.get("nationality.nationalityCd").getClass()); person = (Person) bean.getInstance(); System.out.println(person); List<String> properties = ConvertUtil.extractProperties(person); for (String property : properties) { System.out.println("Property name is: " + property); } // DynaProperty[] properties = bean.getDynaClass().getDynaProperties(); // for (DynaProperty property : properties) { // System.out.println("The map has the property: " + property.getName() + " which is mapped " + property.getType()); // if (property.getType().getName().startsWith("org.openhie")) { // WrapDynaClass dynaClass = WrapDynaClass.createDynaClass(property.getType()); // DynaProperty[] internalProperties = dynaClass.getDynaProperties(); // for (DynaProperty internalProperty : internalProperties) { // System.out.println("The map has the property: " + property.getName() + "." + internalProperty.getName()); // } // } // } // BeanMap beanMap = new BeanMap(person); // Set<String> properties = beanMap.keySet(); // for (String key : properties) { // System.out.println("The map has the property: " + key); // } org.apache.commons.beanutils.converters.DateConverter converter = new org.apache.commons.beanutils.converters.DateConverter(); converter.setPattern("yyyy.MM.dd HH:mm:ss z"); String[] patterns = converter.getPatterns(); for (String pattern : patterns) { System.out.println("Pattern is " + pattern); } Date now = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd HH:mm:ss z"); System.out.println(sdf.format(now)); ConvertUtils.register(converter, java.util.Date.class); ConvertUtils convertUtils = new ConvertUtils(); System.out.println(convertUtils.convert("2009.03.06 15:13:29 EST", java.util.Date.class)); try { BeanUtils.setProperty(person, "dateOfBirth", "2009.03.06 15:13:29 EST"); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InvocationTargetException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(bean.get("dateOfBirth")); System.out.println(bean.getDynaClass().getDynaProperty("dateOfBirth")); bean.set("dateOfBirth", "2009.03.06 15:13:29 EST"); System.out.println(bean.get("dateOfBirth")); }
From source file:org.openmobster.core.mobileObject.TestBeanSyntax.java
private void setNestedProperty(Object mobileBean, String nestedProperty, String value) throws Exception { StringTokenizer st = new StringTokenizer(nestedProperty, "."); Object courObj = mobileBean;//from w w w .j a v a 2 s . c o m while (st.hasMoreTokens()) { String token = st.nextToken(); PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (token.indexOf('[') != -1 && token.indexOf(']') != -1) { String indexedPropertyName = token.substring(0, token.indexOf('[')); metaData = PropertyUtils.getPropertyDescriptor(courObj, indexedPropertyName); } if (!st.hasMoreTokens()) { if (Collection.class.isAssignableFrom(metaData.getPropertyType()) || metaData.getPropertyType().isArray()) { //An IndexedProperty courObj = this.initializeIndexedProperty(courObj, token, metaData); } //Actually set the value of the property if (!metaData.getPropertyType().isArray()) { PropertyUtils.setNestedProperty(mobileBean, nestedProperty, ConvertUtils.convert(value, metaData.getPropertyType())); } else { PropertyUtils.setNestedProperty(mobileBean, nestedProperty, ConvertUtils.convert(value, metaData.getPropertyType().getComponentType())); } } else { if (Collection.class.isAssignableFrom(metaData.getPropertyType()) || metaData.getPropertyType().isArray()) { //An IndexedProperty courObj = this.initializeIndexedProperty(courObj, token, metaData); } else { //A Simple Property courObj = this.initializeSimpleProperty(courObj, token, metaData); } } } }
From source file:org.openmobster.core.mobileObject.xml.MobileObjectSerializer.java
private void setNestedProperty(Object mobileBean, String nestedProperty, String value, List<ArrayMetaData> objectMetaData) { try {//from w ww .j a v a 2s . co m StringTokenizer st = new StringTokenizer(nestedProperty, "."); Object courObj = mobileBean; StringBuilder propertyPath = new StringBuilder(); while (st.hasMoreTokens()) { String token = st.nextToken(); propertyPath.append("/" + token); PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (token.indexOf('[') != -1 && token.indexOf(']') != -1) { String indexedPropertyName = token.substring(0, token.indexOf('[')); metaData = PropertyUtils.getPropertyDescriptor(courObj, indexedPropertyName); } if (metaData == null) { log.error("******************************"); log.error("MetaData Null For: " + token); log.error("Field Not Found on the MobileBean"); log.error("******************************"); continue; } if (!st.hasMoreTokens()) { if (Collection.class.isAssignableFrom(metaData.getPropertyType()) || (metaData.getPropertyType() .isArray() && !metaData.getPropertyType().getComponentType().isAssignableFrom(byte.class))) { //An IndexedProperty this.initializeIndexedProperty(courObj, token, metaData, objectMetaData, propertyPath.toString()); if (metaData.getPropertyType().isArray()) { PropertyUtils.setNestedProperty(mobileBean, nestedProperty, ConvertUtils.convert(value, metaData.getPropertyType().getComponentType())); } else { PropertyUtils.setNestedProperty(mobileBean, nestedProperty, ConvertUtils.convert(value, metaData.getPropertyType())); } } else { //A Simple Property if (metaData.getPropertyType().isArray() && metaData.getPropertyType().getComponentType().isAssignableFrom(byte.class)) { BeanUtils.setProperty(mobileBean, nestedProperty, Utilities.decodeBinaryData(value)); } else { PropertyUtils.setNestedProperty(mobileBean, nestedProperty, ConvertUtils.convert(value, metaData.getPropertyType())); } } } else { if (Collection.class.isAssignableFrom(metaData.getPropertyType()) || metaData.getPropertyType().isArray()) { //An IndexedProperty courObj = this.initializeIndexedProperty(courObj, token, metaData, objectMetaData, propertyPath.toString()); } else { //A Simple Property courObj = this.initializeSimpleProperty(courObj, token, metaData); } } } } catch (Exception e) { log.info("---------------------------------------------------"); log.info("Blowing Up on---------" + nestedProperty); log.info("---------------------------------------------------"); log.error(this, e); throw new RuntimeException(e); } }
From source file:org.paxml.util.ReflectUtils.java
/** * Coerce object type./*from w w w. j a v a2 s. co m*/ * * @param <T> * the expected type * @param from * from object * @param expectedType * to object type * @return the to object */ public static <T> T coerceType(Object from, Class<? extends T> expectedType) { if (from == null) { return null; } Object targetValue = null; if (expectedType.isInstance(from)) { targetValue = from; } else if (expectedType.isEnum()) { for (Object e : expectedType.getEnumConstants()) { if (from.toString().equalsIgnoreCase(e.toString())) { targetValue = e; break; } } if (targetValue == null) { throw new PaxmlRuntimeException( "No enum named '" + from + "' is defined in class: " + expectedType); } } else if (List.class.equals(expectedType)) { targetValue = new ArrayList(); collect(from, (Collection) targetValue, true); } else if (Set.class.equals(expectedType)) { targetValue = new LinkedHashSet(); collect(from, (Collection) targetValue, true); } else if (isImplementingClass(expectedType, Collection.class, false)) { try { targetValue = expectedType.newInstance(); } catch (Exception e) { throw new PaxmlRuntimeException(e); } collect(from, (Collection) targetValue, true); } else if (Iterator.class.equals(expectedType)) { List list = new ArrayList(); collect(from, list, true); targetValue = list.iterator(); } else if (isImplementingClass(expectedType, Coerceable.class, false)) { try { Constructor c = expectedType.getConstructor(Object.class); targetValue = c.newInstance(from); } catch (Exception e) { throw new PaxmlRuntimeException(e); } } else if (from instanceof Map) { return mapToBean((Map) from, expectedType); } else { targetValue = ConvertUtils.convert(from.toString(), expectedType); } return (T) targetValue; }