List of usage examples for org.apache.commons.beanutils PropertyUtils getNestedProperty
public static Object getNestedProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return 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.okj.commons.web.taglib.Functions.java
/** * /* w ww . ja v a 2 s. c o m*/ * @param array * @param separator * @param propertyName * @return */ public static String join(Object array, String separator, String propertyName) { List arr = new ArrayList(); if (array != null) { if (array.getClass().isArray()) { // arr.addAll(Arrays.asList(array)); } else if (array instanceof List) { //List for (int i = 0, n = ((List) array).size(); i < n; i++) { Object bean = ((List) array).get(i); try { arr.add(PropertyUtils.getNestedProperty(bean, propertyName)); } catch (Exception ex) { logger.error(ex); } } } else if (array instanceof Map) { //Map Set set = ((Map) array).entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Object bean = it.next(); try { arr.add(PropertyUtils.getNestedProperty(bean, propertyName)); } catch (Exception ex) { logger.error(ex); } } } else if (array instanceof Set) { //Set Iterator it = ((Set) array).iterator(); while (it.hasNext()) { Object bean = it.next(); try { arr.add(PropertyUtils.getNestedProperty(bean, propertyName)); } catch (Exception ex) { logger.error(ex); } } } else if (array instanceof String) { // arr.addAll(Arrays.asList(StringUtils.split((String) array, separator))); } } return StringUtils.join(arr, separator); }
From source file:org.openhie.openempi.util.ConvertingWrapDynaBean.java
/** * In addition to be able to retrieve properties stored in the record using * the built-in capabilities of the BeansUtils interface, we also added the * capability of retrieving a value from a property that has a one-to-many * relationship to the base object./* w w w. jav a 2 s .c o m*/ * * For example, we want to be able to retrieve one of the identifiers associated * with a person object and person has a one-to-many association with person * identifiers. To access a specific identifier using the identifier domain * as the key to the search, you need to use the following syntax in the * addressing of the property. * * basePropertyName:searchKey:property * basePropertyName is the name of the property in the base object that has * the one-to-many association. This property should be of type Set. * searchKey: is the string to use to identify the one of multiple possible * values in the set. * property: the attribute from the instance of the object in the set that * should be returned. * */ @SuppressWarnings("rawtypes") public Object get(String name) { Object value = null; try { if (name.indexOf(':') >= 0) { int posOfColon = name.indexOf(':'); String key = name.substring(0, posOfColon); value = PropertyUtils.getNestedProperty(instance, key); if (value instanceof java.util.Set) { java.util.Set set = (java.util.Set) value; int secondColon = name.indexOf(':', posOfColon + 1); String searchKey = name.substring(posOfColon + 1, secondColon); for (Object val : set) { if (val.toString().indexOf(searchKey) >= 0) { String propertyName = name.substring(secondColon + 1, name.length()); Object pval = PropertyUtils.getNestedProperty(val, propertyName); return pval; } } return null; } } value = PropertyUtils.getNestedProperty(instance, name); } catch (InvocationTargetException ite) { Throwable cause = ite.getTargetException(); throw new IllegalArgumentException("Error reading property '" + name + "' nested exception - " + cause); } catch (Throwable t) { throw new IllegalArgumentException("Error reading property '" + name + "', exception - " + t); } return (value); }
From source file:org.openmrs.module.reporting.common.BeanPropertyComparator.java
/** * @see Comparator#compare(Object, Object) *///from w ww. j a v a 2 s.co m @SuppressWarnings({ "unchecked" }) @Override public int compare(Object left, Object right) { try { for (String token : sortSpecification.split(",")) { String[] values = token.trim().split(" "); String property = values[0]; boolean sortAsc = (values.length == 1 || !values[1].equalsIgnoreCase("desc")); Object valueLeft = PropertyUtils.getNestedProperty(left, property); Object valueRight = PropertyUtils.getNestedProperty(right, property); //We put NULLs at the bottom. if (valueLeft == null) return 1; if (valueRight == null) return -1; if (!valueLeft.equals(valueRight)) { int ret = ((Comparable) valueLeft).compareTo(valueRight); if (!sortAsc) { ret = (ret == 1 ? -1 : 1); } return ret; } //else values are equal. Try next sort property } } catch (Exception ex) { throw new IllegalArgumentException("Unable to compare " + left + " and " + right + " using sort specification: " + sortSpecification); } return 0; }
From source file:org.photovault.replication.ValueChange.java
@Override public boolean conflictsWith(FieldChange ch) { if (!(ch instanceof ValueChange)) { return false; }/* w w w .j a v a 2s . c o m*/ ValueChange vc = (ValueChange) ch; Iterator<Map.Entry<String, Object>> thisIter = propChanges.entrySet().iterator(); Iterator<Map.Entry<String, Object>> thatIter = vc.propChanges.entrySet().iterator(); /* * If either of the property maps contains either * - property with different value or * - subproperty of a property that exists in the other map * return false */ Map.Entry<String, Object> thisEntry = thisIter.next(); Map.Entry<String, Object> thatEntry = thatIter.next(); boolean thisReady = false; boolean thatReady = false; while (!thisReady || !thatReady) { String thisKey = thisEntry.getKey(); String thatKey = thatEntry.getKey(); boolean moveThis = false; boolean moveThat = false; try { if (thisKey.equals(thatKey)) { /* * Same property set in both changes. If the values differ, * there is a conflict, otherwise move to next element. */ if (!thisEntry.getValue().equals(thatEntry.getValue())) { // Same property with different value return true; } moveThis = moveThat = true; } else if (thatKey.startsWith(thisKey)) { String subPropName = thatKey.substring(thisKey.length()); Object subPropValue = PropertyUtils.getNestedProperty(thisEntry.getValue(), subPropName); if (!thatEntry.getValue().equals(subPropValue)) { return true; } moveThat = true; } else if (thisKey.startsWith(thatKey)) { String subPropName = thisKey.substring(thatKey.length()); Object subPropValue = PropertyUtils.getNestedProperty(thatEntry.getValue(), subPropName); if (!thisEntry.getValue().equals(subPropValue)) { return true; } moveThis = true; } } catch (IllegalAccessException ex) { log.error(ex); return true; } catch (InvocationTargetException ex) { log.error(ex); return true; } catch (NoSuchMethodException ex) { log.error(ex); return true; } if (!moveThis && !moveThat) { if (thisKey.compareTo(thatKey) < 0) { moveThis = true; } else { moveThat = true; } } if (moveThis || thatReady) { if (thisIter.hasNext()) { thisEntry = thisIter.next(); } else { thisReady = true; } } if (moveThat || thisReady) { if (thatIter.hasNext()) { thatEntry = thatIter.next(); } else { thatReady = true; } } } return false; }
From source file:org.photovault.replication.ValueChange.java
Object getSubProperty(String propName) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { String key = (propName != null && propName.length() > 0) ? name + "." + propName : name; if (propChanges.containsKey(key)) { return propChanges.get(key); }/*w ww . j a v a2 s. c o m*/ int lastPartStart = propName.lastIndexOf("."); Object p = null; if (lastPartStart >= 0) { p = getSubProperty(propName.substring(0, lastPartStart)); } else { p = propChanges.get(name); } if (p != null) { return PropertyUtils.getNestedProperty(p, propName.substring(lastPartStart + 1)); } return null; }
From source file:org.rippleosi.patient.labresults.search.LabResultDetailsTransformer.java
private List<Map<String, Object>> extractLabResults(Map<String, Object> input) { try {//from w ww . j av a 2s. c o m return (List<Map<String, Object>>) PropertyUtils.getNestedProperty(input, "test_panel.items"); } catch (Exception ex) { LOGGER.debug("{}: {}", ex.getClass().getName(), ex.getMessage(), ex); return Collections.emptyList(); } }
From source file:org.rippleosi.patient.labresults.search.TestResultTransformer.java
private String getValueAsString(Map<String, Object> input, String path) { try {//from ww w .jav a 2s.co m Object value = PropertyUtils.getNestedProperty(input, path); if (value != null) { return value.toString(); } } catch (Exception ex) { LOGGER.debug("{}: {}", ex.getClass().getName(), ex.getMessage(), ex); } return null; }
From source file:org.rti.zcore.dar.remote.ReportHelper.java
/** * Update report value and saves report to an Excel file. * @param identifier/*from w ww . ja va 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.sqsh.variables.PropertyVariable.java
@Override public String toString() { try {/*from ww w.j a va 2 s. co m*/ Object o = getManager().getBean(bean); Object val = PropertyUtils.getNestedProperty(o, property); if (val == null) { return null; } return val.toString(); } catch (Throwable e) { if (quiet == true) { return null; } return "Cannot read variable '" + getName() + "': " + e.getMessage() + " (" + e.getClass().getName() + ")"; } }
From source file:org.tequila.model.JMetaPojo.java
@Override public void injectFieldProperty(String fieldName, String propertyName, Object propertyValue) { Object fieldObj = null;/*from ww w. ja v 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); } }