List of usage examples for org.apache.commons.beanutils PropertyUtils setNestedProperty
public static void setNestedProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Sets the value of the (possibly nested) property of the specified name, for the specified bean, with no type conversions.
For more details see PropertyUtilsBean
.
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 ww w . j a v a2 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 w w . ja va2 s.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.rti.zcore.dar.remote.ReportHelper.java
/** * Update report value and saves report to an Excel file. * @param identifier/*from w w w .j a v a 2 s . c o m*/ * @param reportName * @param value * @param isFacilityReport * @return */ public static String updateReport(String identifier, String reportName, String value, Boolean isFacilityReport) throws FileNotFoundException { String result = ""; WebContext exec = WebContextFactory.get(); String username = null; SessionUtil zeprs_session = null; Site site = null; String siteAbbrev = null; try { username = exec.getHttpServletRequest().getUserPrincipal().getName(); } catch (NullPointerException e) { // unit testing - it's ok... username = "demo"; } HttpSession session = exec.getSession(); try { zeprs_session = (SessionUtil) session.getAttribute("zeprs_session"); } catch (Exception e) { // unit testing - it's ok... } try { ClientSettings clientSettings = zeprs_session.getClientSettings(); site = clientSettings.getSite(); siteAbbrev = site.getAbbreviation(); } catch (SessionUtil.AttributeNotFoundException e) { log.error(e); } catch (NullPointerException e) { // it's ok - unit testing siteAbbrev = "test"; } String parentField = null; String childField = null; if (identifier.equals("Save") || identifier.equals("SaveNext")) { } else { String[] identArray = identifier.split("\\."); parentField = identArray[0]; childField = identArray[1]; } Register report = null; String className = "org.rti.zcore.dar.report." + StringManipulation.fixClassname(reportName); Class clazz = null; try { clazz = Class.forName(className); } catch (ClassNotFoundException e) { log.error(e); } try { report = (Register) clazz.newInstance(); } catch (InstantiationException e) { log.error(e); } catch (IllegalAccessException e) { log.error(e); } if (identifier.equals("Save") || identifier.equals("SaveNext") || value != null) { Integer valueInt = null; report = SessionUtil.getInstance(session).getReports().get(reportName); String totalIdent = ""; String reportFileName = report.getReportFileName(); String pathXml = Constants.ARCHIVE_PATH + site.getAbbreviation() + "/reports/" + reportFileName + ".xml"; String pathExcel = Constants.ARCHIVE_PATH + site.getAbbreviation() + "/reports/" + reportFileName + ".xls"; String bdate = report.getBeginDate().toString(); String edate = report.getEndDate().toString(); String siteId = String.valueOf(report.getSiteId()); String jsessionId = session.getId(); String[] identifierArray = identifier.split("\\."); int len = identifierArray.length; String keyForMap = null; try { if (identifier.equals("Save")) { result = "Report saved at " + pathExcel; } else if (identifier.equals("SaveNext")) { String reportId = null; if (reportName.equals("CDRRArtReport")) { if ((isFacilityReport != null) && (isFacilityReport == Boolean.TRUE)) { reportId = "7"; result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId + "&isCombinedReport=1&isFacilityReport=1"; } else { // Skipping CDRROIReport reportId = "6"; result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId + "&isCombinedReport=1"; } } else if (reportName.equals("CDRROIReport")) { reportId = "6"; result = "/dar/ChooseReportAction.do;jsessionid=" + jsessionId + "?bdate=" + bdate + "&edate=" + edate + "&siteId=" + siteId + "&report=" + reportId + "&isCombinedReport=1&isFacilityReport=1"; } else { if ((isFacilityReport != null) && (isFacilityReport == Boolean.TRUE)) { result = "/dar/reports/combined/gen.do;jsessionid=" + jsessionId + "?isFacilityReport=1"; } else { result = "/dar/reports/combined/gen.do;jsessionid=" + jsessionId; } } } else { try { valueInt = Integer.valueOf(value); } catch (NumberFormatException e) { try { throw new PersistenceException( "This input field requires an integer value (e.g.: 55). You entered : " + value, e, false); } catch (PersistenceException e1) { return result = identifier + "=" + "Error:" + e1.getMessage(); } } if (identifier.contains("regimenReportMap")) { keyForMap = identifierArray[len - 1]; // should be newEstimatedArtPatients. String parentObjectName = identifier .replace("." + identifierArray[len - 2] + "." + keyForMap, ""); try { Object parent = null; parent = PropertyUtils.getNestedProperty(report, parentObjectName); PropertyUtils.setMappedProperty(parent, "regimenReportMap", keyForMap, valueInt); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else if (identifier.contains("stockReportMap")) { keyForMap = identifierArray[len - 2]; //String propertyName = identifierArray[len-1]; // parentObjectName should be stockReportMap //String parentObjectName = identifier.replace("." + keyForMap + "." + childField, ""); try { PropertyUtils.setNestedProperty(report, identifier, valueInt); //Object parent = PropertyUtils.getNestedProperty(report, parentObjectName); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { PropertyUtils.setProperty(report, identifier, valueInt); } //valueInt = (Integer) PropertyUtils.getProperty(report, identifier); /*HashMap<String, Integer> regimenReportMap = report.get regimenReportMap.put(key, amount);*/ // CDRR (Stock) Reports if (parentField.equals("stockReportMap")) { String propertyField = identifierArray[2]; if (propertyField.equals("quantityRequiredNewPatients")) { String quantityRequiredResupplyIdent = identifier.replace(propertyField, "quantityRequiredResupply"); Integer quantityRequiredResupply = 0; if (PropertyUtils.getNestedProperty(report, quantityRequiredResupplyIdent) != null) { quantityRequiredResupply = (Integer) PropertyUtils.getNestedProperty(report, quantityRequiredResupplyIdent); } Integer totalQuantityRequired = quantityRequiredResupply + valueInt; String totalQuantityRequiredIdent = identifier.replace(propertyField, "totalQuantityRequired"); try { PropertyUtils.setNestedProperty(report, totalQuantityRequiredIdent, valueInt); } catch (Exception e) { e.printStackTrace(); } result = identifier + "=" + valueInt + ";" + totalQuantityRequiredIdent + "=" + totalQuantityRequired; } else { result = "0=0;" + identifier + "=" + valueInt; } // Regimen report } else if (parentField.equals("newEstimatedArtPatients")) { //String quantityRequiredResupplyIdent = "artRegimenReport." + childField; Integer quantityRequiredResupply = 0; /*if (PropertyUtils.getProperty(report, quantityRequiredResupplyIdent) != null) { quantityRequiredResupply = (Integer) PropertyUtils.getProperty(report, quantityRequiredResupplyIdent); }*/ if (PropertyUtils.getMappedProperty(report, "regimenReportMap", keyForMap) != null) { //value = regimenReportMap.get("regimen" + regimenCode); quantityRequiredResupply = (Integer) PropertyUtils.getMappedProperty(report, "regimenReportMap", keyForMap); } totalIdent = "totalEstimatedArtPatients." + childField + "." + keyForMap; Integer totalQuantityRequired = quantityRequiredResupply + valueInt; //String parentObjectName = identifier.replace("." + identifierArray[len-2] + "." + keyForMap, ""); //Object parent = PropertyUtils.getNestedProperty(report, parentObjectName); Object parent = PropertyUtils.getNestedProperty(report, "totalEstimatedArtPatients"); PropertyUtils.setMappedProperty(parent, "regimenReportMap", keyForMap, totalQuantityRequired); //PropertyUtils.setProperty(report, totalIdent, totalQuantityRequired); result = identifier + "=" + valueInt + ";" + totalIdent + "=" + totalQuantityRequired; } else if (parentField.equals("totalQuantityRequired")) { result = "0=0;" + identifier + "=" + valueInt; } } try { ReportOutput.outputReport(reportName, report, clazz, pathXml, pathExcel, null); } catch (FileNotFoundException e) { result = identifier + "=" + valueInt + ";" + totalIdent + "=" + "Error: the Excel file for this report is open. Please close."; } catch (IOException e) { log.debug(e); } catch (WrappedRuntimeException e) { log.error(e); //e.printStackTrace(); } catch (TransformerException e) { log.error(e); } } catch (IllegalAccessException e) { log.debug(e); } catch (InvocationTargetException e) { log.debug(e); } catch (NoSuchMethodException e) { log.debug(e); } //BeanUtils.setProperty(parent, childField, value); } else { result = identifier + "=" + "Error: No value entered."; } return result; }
From source file:org.tequila.model.JMetaPojo.java
@Override public void injectPojoProperty(String propName, Object propValue) throws MetaPojoException { try {//from w ww. ja v a2s.c o m // Pone la propiedad al servicio con get('propName') PropertyUtils.setNestedProperty(this, propName, propValue); PropertyUtils.setNestedProperty(this, "name", propName); PropertyUtils.setNestedProperty(this, "type", propValue.getClass()); declaredFields.put(propName, this); } catch (Exception ex) { throw new MetaPojoException("Error al inyectar la propiedad '[" + propName + ", " + propValue + "']", ex); } }
From source file:org.tequila.model.JMetaPojo.java
@Override public void injectFieldProperty(String fieldName, String propertyName, Object propertyValue) { Object fieldObj = null;// ww w . j av a 2 s. c o m try { // 1.validar que exista el field y obtenerlo fieldObj = PropertyUtils.getNestedProperty(this, fieldName); // 2. Metapojo a partir del objeto field JMetaPojo metaField = new JMetaPojo(fieldObj); // 3. inyectar propiedad al field(la hace accesible por medio de get() y la pone en sus dynaProperties) PropertyUtils.setNestedProperty(metaField, propertyName, propertyValue); //metaField.createInjectedObject(); // 4. borrar el field viejo del pojo, TODO: Obtener sus annotations this.removeProperty(fieldName); // 5. inyectar nuevo field al pojo (la hace accesible por medio de get() y la pone en sus dynaProperties) //this.injectPojoProperty(fieldName, metaField); PropertyUtils.setNestedProperty(this, fieldName, metaField); // TODO: crear un nuevo declared Field para no aplastar posibles name y type originales PropertyUtils.setNestedProperty(metaField, "name", fieldName); PropertyUtils.setNestedProperty(metaField, "type", fieldObj.getClass()); declaredFields.put(fieldName, metaField); } catch (Exception ex) { throw new MetaPojoException( "No existe el field '" + fieldName + "' " + "dentro de la clase '" + sourceObject + "'", ex); } }
From source file:org.tequila.model.JMetaPojo.java
@Override public Object createInjectedObject() throws MetaPojoException { try {/* w w w . j a v a2 s .co m*/ // se crea a partir del objeto original para preservar el nombre de clase y otros atributos, // lo nico que cambiara son sus declaredFields JMetaPojo clazz = new JMetaPojo(sourceObject.getClass()); // crear los declaredFields Field[] oldDeclaredFields = sourceObject.getClass().getDeclaredFields(); for (Field f : oldDeclaredFields) { if (!declaredFields.containsKey(f.getName())) { declaredFields.put(f.getName(), new JMetaPojo(f)); } } // Modificar los declaredFields del objeto original clazz.removeProperty("declaredFields"); PropertyUtils.setNestedProperty(clazz, "declaredFields", declaredFields.values().toArray()); // reemplazar el objeto class del MetaPojo this.removeProperty("class"); PropertyUtils.setNestedProperty(this, "class", clazz); } catch (Exception ex) { throw new MetaPojoException("Error al crear el objeto inyectado", ex); } return this; }
From source file:test.openmobster.device.agent.frameworks.mobileObject.TestBeanUtils.java
public void testPropertySetting() throws Exception { Object pojo = Thread.currentThread().getContextClassLoader() .loadClass("test.openmobster.device.agent.frameworks.mobileObject.MockPOJO").newInstance(); //Set Simple Property String simpleProperty = "value"; PropertyUtils.setProperty(pojo, simpleProperty, "parent"); //Set Nested Property String nestedProperty = "child.value"; StringTokenizer st = new StringTokenizer(nestedProperty, "."); Object courObj = pojo;/*from w w w . j ava2 s. c o m*/ while (st.hasMoreTokens()) { String token = st.nextToken(); if (!st.hasMoreTokens()) { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); PropertyUtils.setNestedProperty(pojo, nestedProperty, ConvertUtils.convert("child", metaData.getPropertyType())); } else { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (PropertyUtils.getProperty(courObj, token) == null) { Object nestedObj = metaData.getPropertyType().newInstance(); PropertyUtils.setProperty(courObj, token, nestedObj); courObj = nestedObj; } else { courObj = PropertyUtils.getProperty(courObj, token); } } } //Set Nested Property non-string nestedProperty = "child.id"; st = new StringTokenizer(nestedProperty, "."); courObj = pojo; while (st.hasMoreTokens()) { String token = st.nextToken(); if (!st.hasMoreTokens()) { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); PropertyUtils.setNestedProperty(pojo, nestedProperty, ConvertUtils.convert("123", metaData.getPropertyType())); } else { PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); if (PropertyUtils.getProperty(courObj, token) == null) { Object nestedObj = metaData.getPropertyType().newInstance(); PropertyUtils.setProperty(courObj, token, nestedObj); courObj = nestedObj; } else { courObj = PropertyUtils.getProperty(courObj, token); } } } //Set Indexed Property //String indexedProperty = "childArray[0]"; //st = new StringTokenizer(indexedProperty, "."); //courObj = pojo; //while(st.hasMoreTokens()) //{ // String token = st.nextToken(); // if(!st.hasMoreTokens()) // { // PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); // PropertyUtils.setIndexedProperty(pojo, indexedProperty, ConvertUtils.convert("child://0", metaData.getPropertyType())); // } // else // { /*if(token.indexOf('[') != -1) { token = token.substring(0, token.indexOf('[')); }*/ // PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token); // if(PropertyUtils.getProperty(courObj, token) == null) // { // Object nestedObj = metaData.getPropertyType().newInstance(); // PropertyUtils.setProperty(courObj, token, nestedObj); // courObj = nestedObj; // } // else // { // courObj = PropertyUtils.getProperty(courObj, token); // } // } //} //Assert String[] childArray = ((MockPOJO) pojo).getChildArray(); assertEquals("Value does not match", ((MockPOJO) pojo).getValue(), "parent"); assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getValue(), "child"); assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getId(), 123); //assertEquals("Value does not match", childArray[0], "child://0"); }