List of usage examples for org.apache.commons.beanutils PropertyUtils getProperty
public static Object getProperty(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.
For more details see PropertyUtilsBean
.
From source file:com.infinities.skyport.async.impl.AsyncHandler.java
@Override protected Object handleInvocation(Object proxy, Method method, final Object[] args) throws Throwable { Object support = TaskType.getSupport(taskType, inner); if ("getSupport".equals(method.getName()) && args.length == 0) { return support; }/* www. j a v a2 s. com*/ final Method innerMethod = AsyncHandler.getMethod(support, method.getName(), method.getParameterTypes()); PoolSize poolSize = PoolSize.SHORT; String methodName = method.getName(); if (!AsyncResult.class.equals(method.getReturnType())) { return innerMethod.invoke(inner, args); } TaskEvent event = TaskEvent.getInitializedEvent(null, method.getName(), configurationId); taskEventHome.persist(event); TaskEventLog log = new TaskEventLog(event, new Date(), Status.Initiazing, "Task is initialized", null); taskEventLogHome.persist(log); try { EntityManagerHelper.commitAndClose(); } catch (Exception ex) { logger.warn("commit log failed, please check the database.", ex); throw ex; } // get pool size the method use. try { FunctionConfiguration functionConfiguration = (FunctionConfiguration) PropertyUtils .getProperty(configuration, methodName); poolSize = functionConfiguration.getPoolSize(); } catch (Exception e) { throwCause(e, false); throw new AssertionError("can't get here"); } DistributedExecutor pool = pools.getThreadPool(poolSize); // //save job; AsyncTaskImpl task = new AsyncTaskImpl(); task.setArgs(args); task.setMethodName(method.getName()); task.setServiceProvider(inner); task.setTaskType(taskType); task.setParameterTypes(method.getParameterTypes()); try { ListenableFuture<Object> future = pool.submit(task); AsyncResult<Object> asyncResult = new AsyncResult<Object>(future); return asyncResult; } catch (Exception e) { try { ThrowableWrapper wrapper = new ThrowableWrapper(e); commitLog(Status.Fail, event.getId(), "Task has been rejected", wrapper); logger.error("encounter exception while schedule a task", e); } catch (Exception ex) { logger.warn("unexpected exception in callback obReject event", ex); } throw e; } }
From source file:com.lioland.harmony.web.dao.ODBClass.java
private ODocument createODocument(ODBClass odbc) { System.out.println("Reading " + odbc.getClass() + "..."); System.out.println(odbc);/*from ww w. j a v a 2s. c o m*/ ODocument doc; try (ODatabaseRecord db = DBFactory.getDb()) { Class cls = odbc.getClass(); if (odbc.rid == null) { doc = new ODocument(cls.getSimpleName()); } else { System.out.println("retrieving document: " + odbc.rid); doc = getODocument(odbc.rid); } for (Field field : cls.getDeclaredFields()) { try { String fieldName = field.getName(); Object fieldValue = PropertyUtils.getProperty(odbc, fieldName); System.out.println("Setting field: " + fieldName); if (fieldValue instanceof List) { System.out.println("Found list"); List list = (List) fieldValue; System.out.println("Size: " + list.size()); List<ODocument> linkList = new ArrayList<>(); if (!list.isEmpty()) { for (Object ob : list) { if (ob instanceof ODBClass) { ODBClass od = (ODBClass) ob; od.loadObject(); linkList.add(createODocument(od)); fieldValue = linkList; } } } } if (fieldValue instanceof ODBClass) { System.out.println("Found ODB Class"); ODBClass odb = (ODBClass) fieldValue; odb.loadObject(); fieldValue = createODocument(odb); } if (fieldValue != null) { doc.field(fieldName, fieldValue); } } catch (IllegalArgumentException | IllegalAccessException | InvocationTargetException | NoSuchMethodException ex) { Logger.getLogger(ODBClass.class.getName()).log(Level.SEVERE, null, ex); } } } return doc; }
From source file:com.yougou.merchant.api.common.MerchantLogTools.java
public static String buildMerchantBasicDataOperationNotes(SupplierVo source, SupplierVo target) throws Exception { if (target == null) { throw new NullPointerException("target"); }// w ww . java 2 s. co m if (source == null) { return "?"; } StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : BASIC_DATA_TRANSLATABLE_FIELDS.entrySet()) { Object o1 = PropertyUtils.getProperty(source, entry.getKey()); Object o2 = PropertyUtils.getProperty(target, entry.getKey()); if (!ObjectUtils.equals(o1, o2)) { if (StringUtils.equals("isInputYougouWarehouse", entry.getKey())) { CooperationModel[] cooperationModels = CooperationModel.values(); o1 = cooperationModels[(Integer) o1].getDescription(); o2 = cooperationModels[(Integer) o2].getDescription(); } else if (StringUtils.equals("shipmentType", entry.getKey())) { o1 = ObjectUtils.equals(NumberUtils.INTEGER_ONE, o1) ? "" : ""; o2 = ObjectUtils.equals(NumberUtils.INTEGER_ONE, o2) ? "" : ""; } sb.append(MessageFormat.format("{0}??{1}?{2}{3}", entry.getValue(), o1, o2, LINE_SEPARATOR)); } } return sb.toString(); }
From source file:info.magnolia.cms.util.NodeMapWrapper.java
/** * Shortcut for Content.getNodeData(name).getString() or Content.getNodeData(name).getName(). * @see java.util.Map#get(Object)// ww w .j ava 2s .c o m */ @Override public Object get(Object key) { try { if (!getWrappedContent().hasNodeData((String) key)) { // support the old lower case value if ("uuid".equalsIgnoreCase((String) key)) { key = "UUID"; } if (hasProperty(key)) { try { return PropertyUtils.getProperty(this.getWrappedContent(), (String) key); } catch (Exception e) { log.error("can't read property " + key + " from the node " + this.getWrappedContent(), e); } } } } catch (RepositoryException e) { // should really not happen log.error("can't check for node data {" + key + "}", e); } NodeData nodeData = getWrappedContent().getNodeData((String) key); Object value; int type = nodeData.getType(); if (type == PropertyType.DATE) { value = nodeData.getDate(); } else if (type == PropertyType.BINARY) { // only file path is supported FileProperties props = new FileProperties(getWrappedContent(), (String) key); value = props.getProperty(FileProperties.PATH); } else if (nodeData.isMultiValue() == NodeData.MULTIVALUE_TRUE) { Value[] values = nodeData.getValues(); String[] valueStrings = new String[values.length]; for (int j = 0; j < values.length; j++) { try { valueStrings[j] = values[j].getString(); } catch (RepositoryException e) { log.debug(e.getMessage()); } } value = valueStrings; } else { try { value = info.magnolia.link.LinkUtil.convertLinksFromUUIDPattern(nodeData.getString(), LinkTransformerManager.getInstance().getBrowserLink(handle)); } catch (LinkException e) { log.warn("Failed to parse links with from " + nodeData.getName(), e); value = nodeData.getString(); } } return value; }
From source file:ca.sqlpower.testutil.TestUtils.java
/** * Gets all the settable properties on the given target object * which are not in the given ignore set, and stuffs them into a Map. * // w w w .j av a 2 s . c o m * @param target The object to change the properties of * @param propertiesToIgnore The properties of target not to modify or read * @return The aforementioned stuffed map */ public static Map<String, Object> getAllInterestingProperties(Object target, Set<String> propertiesToIgnore) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { Map<String, Object> newDescription = new HashMap<String, Object>(); PropertyDescriptor[] props = PropertyUtils.getPropertyDescriptors(target); for (int i = 0; i < props.length; i++) { if (PropertyUtils.isReadable(target, props[i].getName()) && props[i].getReadMethod() != null && !propertiesToIgnore.contains(props[i].getName())) { newDescription.put(props[i].getName(), PropertyUtils.getProperty(target, props[i].getName())); } } return newDescription; }
From source file:com.tonbeller.wcf.convert.SelectConverterBase.java
/** * @see com.tonbeller.wcf.convert.NodeConverter#convert(Formatter, Object, Element) *///ww w . j a v a2 s . co m public void convert(Formatter fmt, Object bean, Element elem) throws ConvertException, IllegalAccessException, NoSuchMethodException, InvocationTargetException { // no model reference? nothing to do String modelReference = Select.getModelReference(elem); if (modelReference.length() == 0) return; // get a formatter String type = Select.getType(elem); String formatString = Select.getFormatString(elem); FormatHandler handler = fmt.getHandler(type); if (handler == null) throw new FormatException("no handler found for type: " + type); // retrieve values from the bean property Object o = PropertyUtils.getProperty(bean, modelReference); Object[] values = handler.toObjectArray(o); if (values == null) values = new Object[0]; // deselect all items List items = Select.getItems(elem); for (Iterator it = items.iterator(); it.hasNext();) Item.setSelected((Element) it.next(), false); // for each value, find the corresponding item and select it for (int i = 0; i < values.length; i++) { Object beanValue = values[i]; boolean found = false; search: for (Iterator it = items.iterator(); it.hasNext();) { Element item = (Element) it.next(); Object itemValue = handler.parse(Item.getValue(item), formatString); if (itemValue.equals(beanValue)) { Item.setSelected(item, true); found = true; break search; } } if (!found) { String mesg = "No item has a value of \"" + beanValue + "\"."; showMissing(elem, mesg); } } }
From source file:net.kamhon.ieagle.util.CollectionUtil.java
/** * This function used to convert particular properties in Object to array. This function mainly used to response * Client in JSON object//from w w w .ja v a 2 s . c o m * * * @param locale * @param objects * @param propertiesNames * @param isSetNullToEmptyString * @return */ public static Object[][] to2DArrayForStruts(Locale locale, List<?> objects, String[] propertiesNames, boolean isSetNullToEmptyString) { String dateTimeFormat = ""; if (isEmpty(objects)) { return new Object[0][0]; } List<Object[]> result = new ArrayList<Object[]>(); for (Object object : objects) { List<Object> record = new ArrayList<Object>(); for (String propertyName : propertiesNames) { boolean hasResult = false; Object propValue = null; try { propValue = PropertyUtils.getProperty(object, propertyName); processPropertiesForStruts(object, record, propertyName, propValue); hasResult = true; } catch (NestedNullException ex) { // if nested bean referenced is null record.add(""); hasResult = true; } catch (Exception ex) { if (locale == null) throw new DataException(ex); } if (hasResult == false && propValue == null && locale != null) { try { String methodName = "get" + propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1); propValue = MethodUtils.invokeExactMethod(object, methodName, locale); processPropertiesForStruts(object, record, propertyName, propValue); } catch (Exception ex) { throw new DataException(ex); } } } result.add(record.toArray(new Object[0])); } return result.toArray(new Object[1][1]); }
From source file:com.tonbeller.wcf.convert.EditCtrlConverter.java
/** * initializes the value attribute of element from a bean property. *//*from w w w . j ava2 s. co m*/ public void convert(Formatter formatter, Object bean, Element element) throws IllegalAccessException, NoSuchMethodException, InvocationTargetException { try { String model = EditCtrl.getModelReference(element); if (model.length() == 0) return; String type = EditCtrl.getType(element); FormatHandler handler = formatter.getHandler(type); if (handler == null) throw new FormatException("no handler found for type: " + type); Object value = PropertyUtils.getProperty(bean, model); String pattern = EditCtrl.getFormatString(element); String strValue = handler.format(value, pattern); EditCtrl.setValue(element, strValue); } catch (IllegalAccessException e) { XoplonNS.setAttribute(element, "error", e.getMessage()); throw e; } catch (NoSuchMethodException e) { XoplonNS.setAttribute(element, "error", e.getMessage()); throw e; } catch (InvocationTargetException e) { XoplonNS.setAttribute(element, "error", e.getMessage()); throw e; } catch (FormatException e) { XoplonNS.setAttribute(element, "error", e.getMessage()); throw e; } }
From source file:com.mycollab.vaadin.web.ui.MultiSelectComp.java
protected ItemSelectionComp<T> buildItem(final T item) { String itemName = ""; if (!"".equals(propertyDisplayField)) { try {//from ww w . j a v a2 s . com itemName = (String) PropertyUtils.getProperty(item, propertyDisplayField); } catch (final Exception e) { e.printStackTrace(); } } else { itemName = item.toString(); } final ItemSelectionComp<T> chkItem = new ItemSelectionComp<>(item, itemName); chkItem.setImmediate(true); chkItem.addValueChangeListener(valueChangeEvent -> { final Boolean value = chkItem.getValue(); if (value && !selectedItems.contains(item)) { selectedItems.add(item); } else { selectedItems.remove(item); } displaySelectedItems(); }); return chkItem; }
From source file:com.troyhisted.inputfield.field.DynaFieldTest.java
/** * Ensure a BigDecimal property can be retrieved using {@link BeanUtils}. * * @throws InvocationTargetException/*from www . ja v a2s. c om*/ * @throws IllegalAccessException * @throws NoSuchMethodException */ @Test public void testGetBeanBigDecimalProperty() throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { final Field<BigDecimal> field = this.construct(BigDecimal.class); field.value(new BigDecimal("12.34")); Assert.assertEquals("12.34", BeanUtils.getProperty(field, "value")); Assert.assertEquals(new BigDecimal("12.34"), PropertyUtils.getProperty(field, "value")); }