List of usage examples for org.apache.commons.beanutils PropertyUtils getPropertyType
public static Class getPropertyType(Object bean, String name) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Return the Java Class representing the property type of the specified property, or null
if there is no such property for the specified bean.
For more details see PropertyUtilsBean
.
From source file:com.lzsoft.rules.core.RulesEngine.java
protected boolean evaluateRule(Object objs, String ruleElmtName) throws Exception { // Get the RuleImplElmt RuleImplElmt ruleImplElmt = getRuleImpElmtByName(ruleElmtName); List<PropertyElmt> proElmts = ruleImplElmt.getPropertyElmts(); int c = 0;// w ww . j ava 2 s .com if (objs.getClass().getName().toLowerCase().indexOf("list") >= 0) { int c1 = 0; for (Object obj : (List) objs) { if (obj.getClass().getName().equals(ruleImplElmt.getClazz())) { for (PropertyElmt propertyElmt : proElmts) { Object objValue = PropertyUtils.getProperty(obj, propertyElmt.getField());// ?mappingfieldname?? Class clazz = PropertyUtils.getPropertyType(obj, propertyElmt.getField());// ?mappingfieldname??? boolean currentRule = MUtil.matchField(objValue, clazz.getSimpleName(), propertyElmt); if ("and".equalsIgnoreCase(ruleImplElmt.getPropertylogic())) { if (!currentRule) { return false; } c++; } else if ("or".equalsIgnoreCase(ruleImplElmt.getPropertylogic()) || null == ruleImplElmt.getPropertylogic()) { if (currentRule) { return true; } } } } } } else { if (objs.getClass().getName().equals(ruleImplElmt.getClazz())) { for (PropertyElmt propertyElmt : proElmts) { Object objValue = PropertyUtils.getProperty(objs, propertyElmt.getField());// ?mappingfieldname?? Class clazz = PropertyUtils.getPropertyType(objs, propertyElmt.getField());// ?mappingfieldname??? boolean currentRule = MUtil.matchField(objValue, clazz.getSimpleName(), propertyElmt); if ("and".equalsIgnoreCase(ruleImplElmt.getPropertylogic())) { if (!currentRule) { return false; } c++; } else if ("or".equalsIgnoreCase(ruleImplElmt.getPropertylogic()) || null == ruleImplElmt.getPropertylogic()) { if (currentRule) { return true; } } } } else { // System.out.println(objs+" rule-invoke name="+ruleElmtName); return false; } } return c == proElmts.size() ? true : false; /* * // Get the rule Rule rule = ruleFactory.getRule(ruleImplElmt); * * // Evaluate rule boolean evaluation = ruleEvaluator.passesRule(rule, * ruleArgs); * * // If isInverse, invert the evaluation if (ruleElmt.isInverse()) { * evaluation = !evaluation; } * * return evaluation; */ }
From source file:com.sun.faces.config.ManagedBeanFactory.java
/** * <li><p> Call the property getter, if it exists.</p></li> * <p/>/*w ww. ja va 2s. c o m*/ * <li><p>If the getter returns null or doesn't exist, create a * java.util.ArrayList(), otherwise use the returned Object (an array or * a java.util.List).</p></li> * <p/> * <li><p>If a List was returned or created in step 2), add all * elements defined by nested <value> elements in the order * they are listed, converting values defined by nested * <value> elements to the type defined by * <value-class>. If a <value-class> is not defined, use * the value as-is (i.e., as a java.lang.String). Add null for each * <null-value> element.</p></li> * <p/> * <li><p> If an array was returned in step 2), create a * java.util.ArrayList and copy all elements from the returned array to * the new List, auto-boxing elements of a primitive type. Add all * elements defined by nested <value> elements as described in step * 3).</p></li> * <p/> * <li><p> If a new java.util.List was created in step 2) and the * property is of type List, set the property by calling the setter * method, or log an error if there is no setter method.</p></li> * <p/> * <li><p> If a new java.util.List was created in step 4), convert * the * List to array of the same type as the property and set the * property by * calling the setter method, or log an error if there * is no setter * method.</p></li> */ private void setArrayOrListPropertiesIntoBean(Object bean, ManagedPropertyBean property) throws Exception { Object result = null; boolean getterIsNull = true, getterIsArray = false; List valuesForBean = null; Class valueType = java.lang.String.class, propertyType = null; String propertyName = property.getPropertyName(); try { // see if there is a getter result = PropertyUtils.getProperty(bean, propertyName); getterIsNull = (null == result) ? true : false; propertyType = PropertyUtils.getPropertyType(bean, propertyName); getterIsArray = propertyType.isArray(); } catch (NoSuchMethodException nsme) { // it's valid to not have a getter. } // the property has to be either a List or Array if (!getterIsArray) { if (null != propertyType && !java.util.List.class.isAssignableFrom(propertyType)) { throw new FacesException( Util.getExceptionMessageString(Util.MANAGED_BEAN_CANNOT_SET_LIST_ARRAY_PROPERTY_ID, new Object[] { propertyName, managedBean.getManagedBeanName() })); } } // // Deal with the possibility of the getter returning existing // values. // // if the getter returned non-null if (!getterIsNull) { // if what it returned was an array if (getterIsArray) { valuesForBean = new ArrayList(); for (int i = 0, len = Array.getLength(result); i < len; i++) { // add the existing values valuesForBean.add(Array.get(result, i)); } } else { // if what it returned was not a List if (!(result instanceof List)) { // throw an exception throw new FacesException( Util.getExceptionMessageString(Util.MANAGED_BEAN_EXISTING_VALUE_NOT_LIST_ID, new Object[] { propertyName, managedBean.getManagedBeanName() })); } valuesForBean = (List) result; } } else { // getter returned null result = valuesForBean = new ArrayList(); } // at this point valuesForBean contains the existing values from // the bean, or no values if the bean had no values. In any // case, we can proceed to add values from the config file. valueType = copyListEntriesFromConfigToList(property.getListEntries(), valuesForBean); // at this point valuesForBean has the values to be set into the // bean. if (getterIsArray) { // convert back to Array result = Array.newInstance(valueType, valuesForBean.size()); for (int i = 0, len = valuesForBean.size(); i < len; i++) { if (valueType == Boolean.TYPE) { Array.setBoolean(result, i, ((Boolean) valuesForBean.get(i)).booleanValue()); } else if (valueType == Byte.TYPE) { Array.setByte(result, i, ((Byte) valuesForBean.get(i)).byteValue()); } else if (valueType == Double.TYPE) { Array.setDouble(result, i, ((Double) valuesForBean.get(i)).doubleValue()); } else if (valueType == Float.TYPE) { Array.setFloat(result, i, ((Float) valuesForBean.get(i)).floatValue()); } else if (valueType == Integer.TYPE) { Array.setInt(result, i, ((Integer) valuesForBean.get(i)).intValue()); } else if (valueType == Character.TYPE) { Array.setChar(result, i, ((Character) valuesForBean.get(i)).charValue()); } else if (valueType == Short.TYPE) { Array.setShort(result, i, ((Short) valuesForBean.get(i)).shortValue()); } else if (valueType == Long.TYPE) { Array.setLong(result, i, ((Long) valuesForBean.get(i)).longValue()); } else { Array.set(result, i, valuesForBean.get(i)); } } } else { result = valuesForBean; } if (getterIsNull || getterIsArray) { PropertyUtils.setProperty(bean, propertyName, result); } }
From source file:com.sun.faces.config.ManagedBeanFactory.java
/** * <li><p>Call the property getter, if it exists.</p></li> * <p/>// w w w . j av a 2s .c om * <li><p>If the getter returns null or doesn't exist, create a * java.util.HashMap(), otherwise use the returned * java.util.Map.</p></li> * <p/> * <li><p>Add all entries defined by nested <map-entry> * elements in the order they are listed, converting key values * defined by nested <key> elements to the type defined by * <key-class> and entry values defined by nested * <value> elements to the type defined by * <value-class>. If <key-class> and/or * <value-class> are not defined, use the value as-is (i.e., * as a java.lang.String). Add null for each <null-value> * element.</p></li> * <p/> * <li><p>If a new java.util.Map was created in step 2), set the * property by calling the setter method, or log an error if there * is no setter method.</p></li> */ private void setMapPropertiesIntoBean(Object bean, ManagedPropertyBean property) throws Exception { Map result = null; boolean getterIsNull = true; Class propertyType = null; String propertyName = property.getPropertyName(); try { // see if there is a getter result = (Map) PropertyUtils.getProperty(bean, propertyName); getterIsNull = (null == result) ? true : false; propertyType = PropertyUtils.getPropertyType(bean, propertyName); } catch (NoSuchMethodException nsme) { // it's valid to not have a getter. } if (null != propertyType && !java.util.Map.class.isAssignableFrom(propertyType)) { throw new FacesException(Util.getExceptionMessageString(Util.MANAGED_BEAN_CANNOT_SET_MAP_PROPERTY_ID, new Object[] { propertyName, managedBean.getManagedBeanName() })); } if (getterIsNull) { result = new java.util.HashMap(property.getMapEntries().getMapEntries().length); } // at this point result contains the existing entries from the // bean, or no entries if the bean had no entries. In any case, // we can proceed to add values from the config file. copyMapEntriesFromConfigToMap(property.getMapEntries(), result); if (getterIsNull) { PropertyUtils.setProperty(bean, propertyName, result); } }
From source file:edu.ku.brc.specify.tasks.subpane.wb.TemplateEditor.java
/** * Gets the Table class for a FieldInfo. * @param fieldInfo the fieldInfo// w ww.j a v a2s .co m * @return the class of it's owning table info object */ protected Class<?> getTableClass(final FieldInfo fieldInfo) { Class<?> tableClass = null; try { Object newDbObj = fieldInfo.getTableinfo().getClassObj().newInstance(); tableClass = PropertyUtils.getPropertyType(newDbObj, fieldInfo.getFieldInfo().getName()); } catch (Exception e) { edu.ku.brc.af.core.UsageTracker.incrHandledUsageCount(); edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(TemplateEditor.class, e); // we can't determine the class of the DB mapping, so assume String log.warn("Exception while looking up field type. Assuming java.lang.String.", e); tableClass = String.class; } return tableClass; }
From source file:net.sourceforge.vulcan.web.struts.actions.ManagePluginAction.java
public final ActionForward add(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final PluginConfigForm configForm = (PluginConfigForm) form; final String target = configForm.getTarget(); final BeanWrapper bw = new BeanWrapperImpl(form); final Class<?> type = PropertyUtils.getPropertyType(form, target).getComponentType(); final int i; Object[] array = (Object[]) bw.getPropertyValue(target); if (array == null) { array = (Object[]) Array.newInstance(type, 1); i = 0;// w w w. j a va 2s . co m } else { i = array.length; Object[] tmp = (Object[]) Array.newInstance(type, i + 1); System.arraycopy(array, 0, tmp, 0, i); array = tmp; } array[i] = stateManager.getPluginManager().createObject(configForm.getPluginId(), type.getName()); bw.setPropertyValue(target, array); configForm.setFocus(target + "[" + i + "]"); configForm.introspect(request); setHelpAttributes(request, configForm); return mapping.findForward("configure"); }
From source file:net.sourceforge.vulcan.web.struts.actions.ManagePluginAction.java
public final ActionForward remove(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { final PluginConfigForm configForm = (PluginConfigForm) form; final String target = configForm.getTarget(); final String[] split = target.split("\\["); final String arrayProperty = split[0]; final int index = Integer.parseInt(split[1].substring(0, split[1].length() - 1)); final BeanWrapper bw = new BeanWrapperImpl(form); final Class<?> type = PropertyUtils.getPropertyType(form, arrayProperty).getComponentType(); Object[] array = (Object[]) bw.getPropertyValue(arrayProperty); Object[] tmp = (Object[]) Array.newInstance(type, array.length - 1); System.arraycopy(array, 0, tmp, 0, index); System.arraycopy(array, index + 1, tmp, index, array.length - index - 1); bw.setPropertyValue(arrayProperty, tmp); configForm.putBreadCrumbsInRequest(request); return mapping.findForward("configure"); }
From source file:net.sourceforge.vulcan.web.struts.forms.PluginConfigForm.java
public void introspect(HttpServletRequest request) throws IntrospectionException, IllegalAccessException, InvocationTargetException, NoSuchMethodException, InstantiationException { Class<?> cls = null;//w ww . j a v a2 s . co m if ("pluginConfig".equals(focus)) { cls = pluginConfig.getClass(); this.breadCrumbs.clear(); this.breadCrumbs.add("Setup"); if (isProjectPlugin()) { this.breadCrumbs.add("Projects"); this.breadCrumbs.add(projectName); this.breadCrumbs.add(this.pluginConfig.getPluginName()); } else { this.breadCrumbs.add("Plugins"); this.breadCrumbs.add(this.pluginConfig.getPluginName()); } } else { cls = PropertyUtils.getPropertyType(this, focus); if (cls.isArray()) { cls = cls.getComponentType(); } } final String prefix = focus + "."; final PropertyDescriptor[] pds; if (PluginConfigDto.class.isAssignableFrom(cls)) { final PluginConfigDto pluginConfig = (PluginConfigDto) getFocusObject(); final List<PropertyDescriptor> tmp = pluginConfig.getPropertyDescriptors(request.getLocale()); pds = tmp.toArray(new PropertyDescriptor[tmp.size()]); if (pluginConfig instanceof PluginProfileDto) { ((PluginProfileDto) pluginConfig).checkPoint(); } } else { final BeanInfo beanInfo = Introspector.getBeanInfo(cls); Introspector.flushFromCaches(cls); pds = beanInfo.getPropertyDescriptors(); } if (isNested()) { for (PropertyDescriptor pd : propertyDescriptors) { if (focus.startsWith(pd.getName())) { breadCrumbs.add(pd.getDisplayName()); } } } types.clear(); choices.clear(); propertyDescriptors.clear(); hiddenPasswords.clear(); for (PropertyDescriptor pd : pds) { final String name = prefix + pd.getName(); final PropertyDescriptor cp = new PropertyDescriptor(pd.getName(), pd.getReadMethod(), pd.getWriteMethod()); cp.setShortDescription(pd.getShortDescription()); cp.setDisplayName(pd.getDisplayName()); cp.setName(name); propertyDescriptors.add(cp); types.put(name, getTypeAndPrepare(name, pd)); } putBreadCrumbsInRequest(request); }
From source file:nl.strohalm.cyclos.services.settings.BaseSettingsHandler.java
/** * Populate a settings object, using a Map of converters, and a Map of values. Only 2 levels of beans are supported, ie, xxxSettings.x.y. If there * were a nested bean on x, making it be xxxSettings.x.y.z, z would be ignored *///from w w w .j a v a 2 s.co m private void populate(final Object settings, final Map<String, String> values) { for (final Map.Entry<String, Converter<?>> entry : converters.entrySet()) { final String name = entry.getKey(); final Converter<?> converter = entry.getValue(); if (values.containsKey(name)) { final String value = values.get(name); final Object realValue = converter.valueOf(value); // Check if there is a nested object if (name.contains(".")) { final String first = PropertyHelper.firstProperty(name); // No bean: instantiate it if (PropertyHelper.get(settings, first) == null) { try { final Class<?> type = PropertyUtils.getPropertyType(settings, first); final Object bean = type.newInstance(); PropertyHelper.set(settings, first, bean); } catch (final Exception e) { LOGGER.warn("Error while setting nested settings bean", e); throw new IllegalStateException(); } } } PropertyHelper.set(settings, name, realValue); } } }
From source file:nl.strohalm.cyclos.utils.csv.CSVReader.java
/** * Reads a single object from a SCV line *///w w w .j a v a2 s. c o m @SuppressWarnings({ "unchecked", "rawtypes" }) public List<E> read(final BufferedReader in) throws CSVParseException { int linesIndex = 0; final List<E> list = new LinkedList<E>(); try { List<String> values; while ((values = readLine(in)) != null) { linesIndex++; // Ignore the header lines if (headerLines >= linesIndex) { continue; } final E object = elementClass.newInstance(); final int size = Math.min(columns.size(), values.size()); for (int i = 0; i < size; i++) { final Column column = columns.get(i); final String property = column.getProperty(); if (property == null) { continue; } final Class type = PropertyUtils.getPropertyType(object, property); final String stringValue = values.get(i); final Object objectValue = PropertyHelper.getAsObject(type, stringValue, column.getConverter()); PropertyHelper.set(object, property, objectValue); } list.add(object); } return list; } catch (final Exception e) { throw new CSVParseException(linesIndex); } }
From source file:nz.co.senanque.messaging.GenericEndpoint.java
private void unpackRoot(Element element, Object context) { ValidationSessionHolder validationSessonHolder = new ValidationSessionHolderImpl(getValidationEngine()); validationSessonHolder.bind(context); try {//from w ww .j a va2 s.c om @SuppressWarnings("unchecked") Iterator<Text> itr = (Iterator<Text>) element .getDescendants(new ContentFilter(ContentFilter.TEXT | ContentFilter.CDATA)); while (itr.hasNext()) { Text text = itr.next(); String name = getName(text); if (name.equals("id") || name.equals("version")) { continue; } try { Class<?> targetType = PropertyUtils.getPropertyType(context, name); Object value = ConvertUtils.convert(text.getValue(), targetType); PropertyUtils.setProperty(context, name, value); log.debug("name {} value {}", name, text.getValue()); } catch (IllegalAccessException e) { // Ignore these and move on log.debug("{} {}", name, e.getMessage()); } catch (InvocationTargetException e) { // Ignore these and move on log.debug("{} {}", name, e.getTargetException().toString()); } catch (NoSuchMethodException e) { // Ignore these and move on log.debug("{} {}", name, e.getMessage()); } } } finally { validationSessonHolder.close(); } }