List of usage examples for org.apache.commons.beanutils PropertyUtils isWriteable
public static boolean isWriteable(Object bean, String name)
Return true
if the specified property name identifies a writeable property on the specified bean; otherwise, return false
.
For more details see PropertyUtilsBean
.
From source file:de.alpharogroup.lang.object.MergeObjectExtensions.java
/** * Merge the given property to the given 'to' object with the given 'with' object. * * @param <TO>// w ww .j av a 2 s . c o m * the generic type of the object to merge in * @param <WITH> * the generic type of the object to merge with * @param toObject * the object to merge in * @param withObject * the object to merge with * @param propertyDescriptor * the property descriptor * @throws InvocationTargetException * if the property accessor method throws an exception * @throws IllegalAccessException * if the caller does not have access to the property accessor method */ public static final <TO, WITH> void mergeProperty(final TO toObject, final WITH withObject, final PropertyDescriptor propertyDescriptor) throws IllegalAccessException, InvocationTargetException { if (PropertyUtils.isReadable(toObject, propertyDescriptor.getName()) && PropertyUtils.isWriteable(toObject, propertyDescriptor.getName())) { final Method getter = propertyDescriptor.getReadMethod(); final Object value = getter.invoke(withObject); if (!value.isDefaultValue()) { final Method setter = propertyDescriptor.getWriteMethod(); setter.invoke(toObject, value); } } }
From source file:com.afeng.common.utils.reflection.MyBeanUtils.java
/** * ?/*w w w . j a v a 2s . c om*/ * ??? * * @param databean * @param tobean * @throws NoSuchMethodException * copy */ public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); // String type = origDescriptors[i].getPropertyType().toString(); if ("class".equals(name)) { continue; // No point in trying to set an object's class } if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) { try { Object value = PropertyUtils.getSimpleProperty(databean, name); if (value != null) { copyProperty(tobean, name, value); } } catch (IllegalArgumentException ie) { ; // Should not happen } catch (Exception e) { ; // Should not happen } } } }
From source file:com.eryansky.common.utils.reflection.MyBeanUtils.java
/** * ?//from ww w. j a v a 2 s . c o m * ??? * * @param databean * @param tobean * @throws NoSuchMethodException * copy */ public static void copyBeanNotNull2Bean(Object databean, Object tobean) throws Exception { PropertyDescriptor origDescriptors[] = PropertyUtils.getPropertyDescriptors(databean); for (int i = 0; i < origDescriptors.length; i++) { String name = origDescriptors[i].getName(); // String type = origDescriptors[i].getPropertyType().toString(); if ("class".equals(name)) { continue; // No point in trying to set an object's class } if (PropertyUtils.isReadable(databean, name) && PropertyUtils.isWriteable(tobean, name)) { try { Object value = PropertyUtils.getSimpleProperty(databean, name); if (value != null) { copyProperty(tobean, name, value); } } catch (java.lang.IllegalArgumentException ie) { ; // Should not happen } catch (Exception e) { ; // Should not happen } } } }
From source file:edu.northwestern.bioinformatics.studycalendar.domain.tools.hibernate.ScheduledActivityStateType.java
public void setPropertyValue(Object component, int property, Object value) throws HibernateException { String name = getPropertyNames()[property]; if (PropertyUtils.isWriteable(component, name)) { try {/*w w w . j a va2 s . c om*/ PropertyUtils.setProperty(component, name, value); } catch (NoSuchMethodException e) { throw new HibernateException( "Failed to set property " + name + " on " + component + " with value " + value, e); } catch (IllegalAccessException e) { throw new HibernateException( "Failed to set property " + name + " on " + component + " with value " + value, e); } catch (InvocationTargetException e) { throw new HibernateException( "Failed to set property " + name + " on " + component + " with value " + value, e); } } }
From source file:de.iritgo.aktario.jdbc.JDBCManager.java
/** * Initialize the <code>JDBCManager</code>. * * This method creates the data sources specified in the server * configuration./* www . j a va 2s. c om*/ */ public void init() { dataSources = new HashMap(); try { Configuration config = Engine.instance().getConfiguration(); for (DatasourceConfig datasourceConfig : config.getDataSources()) { DataSource ds = (DataSource) Class.forName(datasourceConfig.getDataSourceClass()).newInstance(); if (PropertyUtils.isWriteable(ds, "driverClassName")) { PropertyUtils.setProperty(ds, "driverClassName", datasourceConfig.getDriverClass()); } if (PropertyUtils.isWriteable(ds, "username")) { PropertyUtils.setProperty(ds, "username", datasourceConfig.getUser()); } if (PropertyUtils.isWriteable(ds, "password")) { PropertyUtils.setProperty(ds, "password", datasourceConfig.getPassword()); } if (PropertyUtils.isWriteable(ds, "url")) { PropertyUtils.setProperty(ds, "url", datasourceConfig.getUrl()); } dataSources.put(datasourceConfig.getId(), ds); if (defaultDataSource == null) { defaultDataSource = ds; } Log.logInfo("persist", "JDBCManager", "Created datasource '" + datasourceConfig.getId() + "'"); } JDBCIDGenerator persistentIdGenerator = new JDBCIDGenerator(2, 2, 1000); persistentIdGenerator.load(); Engine.instance().installPersistentIDGenerator(persistentIdGenerator); DefaultIDGenerator transientIdGenerator = new DefaultIDGenerator((long) 1, (long) 2); Engine.instance().installTransientIDGenerator(transientIdGenerator); } catch (Exception x) { Log.logError("persist", "JDBCManager", "Error while creating the datasources: " + x); } Engine.instance().getEventRegistry().addListener("objectcreated", this); Engine.instance().getEventRegistry().addListener("objectmodified", this); Engine.instance().getEventRegistry().addListener("objectrequested", this); Engine.instance().getEventRegistry().addListener("objectremoved", this); }
From source file:com.litemvc.LiteMvcFilter.java
@SuppressWarnings("unchecked") private boolean tryToExecuteMethod(HttpServletRequest request, HttpServletResponse response, Matcher matcher, Binding binding, Object handler) throws Exception { Method[] methods = binding.getHandlerClass().getMethods(); for (Method method : methods) { if (isMappedMethod(request, method, binding)) { Class<?>[] parmTypes = method.getParameterTypes(); int matchCount = 1; ArrayList<Object> args = new ArrayList<Object>(); for (Class<?> clazz : parmTypes) { if (clazz.equals(HttpServletRequest.class)) { args.add(request);//from w ww. j a va 2s . com } if (clazz.equals(HttpServletResponse.class)) { args.add(response); } if (clazz.equals(String.class)) { args.add(matcher.group(matchCount)); matchCount++; } } for (Object oParmName : request.getParameterMap().keySet()) { String parmName = (String) oParmName; if (PropertyUtils.isWriteable(handler, parmName)) { BeanUtils.setProperty(handler, parmName, request.getParameter(parmName)); } } boolean isError = false; String result = null; try { result = (String) method.invoke(handler, args.toArray()); } catch (Exception e) { Throwable cause = e; if (e instanceof InvocationTargetException) { InvocationTargetException ite = (InvocationTargetException) e; cause = ite.getCause(); } if (exceptionsMap.containsKey(cause.getClass())) { result = exceptionsMap.get(cause.getClass()); isError = true; } else { throw e; } } if (result == null) { return true; } Action action = null; if (!isError) { // we only check global results in case of an error. action = binding.getAction(result); } if (action == null) { action = globalResults.get(result); } if (action == null) { throw new UnmappedResultException(result, isError); } if (action instanceof TemplateAction) { TemplateAction templateAction = (TemplateAction) action; String templateName = templateAction.getTemplateName(); if (templateAction.isEvaluate()) { JexlContext jc = JexlHelper.createContext(); jc.getVars().put("handler", handler); templateName = "" + templateAction.getExpression().evaluate(jc); } processTemplate(request, response, templateName, handler); return true; } if (action instanceof DispatcherAction) { request.setAttribute("handler", handler); DispatcherAction location = (DispatcherAction) action; request.getRequestDispatcher(location.getLocation()).forward(request, response); return true; } if (action instanceof RedirectAction) { RedirectAction redirectAction = (RedirectAction) action; String location = redirectAction.getLocation(); if (redirectAction.isEvaluate()) { JexlContext jc = JexlHelper.createContext(); jc.getVars().put("handler", handler); location = "" + redirectAction.getExpression().evaluate(jc); } response.sendRedirect(location); return true; } if (!customActionProcessor(binding, request, response, action)) { throw new RuntimeException("unkown action type: " + action.getClass().getName()); } return true; } } return false; }
From source file:com.feilong.commons.core.bean.BeanUtilTest.java
/** * Demo normal java beans.//from w w w . j a v a 2s .c om * * @throws Exception * the exception */ @Test public void testDemoNormalJavaBeans() throws Exception { log.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "=")); // data setup Address addr1 = new Address("CA1234", "xxx", "Los Angeles", "USA"); Address addr2 = new Address("100000", "xxx", "Beijing", "China"); Address[] addrs = new Address[2]; addrs[0] = addr1; addrs[1] = addr2; Customer cust = new Customer(123, "John Smith", addrs); // accessing the city of first address String cityPattern = "addresses[0].city"; String name = (String) PropertyUtils.getSimpleProperty(cust, "name"); String city = (String) PropertyUtils.getProperty(cust, cityPattern); Object[] rawOutput1 = new Object[] { "The city of customer ", name, "'s first address is ", city, "." }; log.debug(StringUtils.join(rawOutput1)); // setting the zipcode of customer's second address String zipPattern = "addresses[1].zipCode"; if (PropertyUtils.isWriteable(cust, zipPattern)) {//PropertyUtils log.debug("Setting zipcode ..."); PropertyUtils.setProperty(cust, zipPattern, "200000");//PropertyUtils } String zip = (String) PropertyUtils.getProperty(cust, zipPattern);//PropertyUtils Object[] rawOutput2 = new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip, "." }; log.debug(StringUtils.join(rawOutput2)); }
From source file:com.feilong.core.bean.BeanUtilTest.java
/** * Demo normal java beans.//www . ja v a 2 s . c o m * * @throws Exception * the exception */ @Test public void testDemoNormalJavaBeans() throws Exception { LOGGER.debug(StringUtils.center(" demoNormalJavaBeans ", 40, "=")); // data setup Customer customer = new Customer(123, "John Smith", toArray(new Address("CA1234", "xxx", "Los Angeles", "USA"), new Address("100000", "xxx", "Beijing", "China"))); // accessing the city of first address String name = (String) PropertyUtils.getSimpleProperty(customer, "name"); String city = (String) PropertyUtils.getProperty(customer, "addresses[0].city"); LOGGER.debug(StringUtils .join(new Object[] { "The city of customer ", name, "'s first address is ", city, "." })); // setting the zipcode of customer's second address String zipPattern = "addresses[1].zipCode"; if (PropertyUtils.isWriteable(customer, zipPattern)) {//PropertyUtils LOGGER.debug("Setting zipcode ..."); PropertyUtils.setProperty(customer, zipPattern, "200000");//PropertyUtils } String zip = (String) PropertyUtils.getProperty(customer, zipPattern);//PropertyUtils LOGGER.debug(StringUtils .join(new Object[] { "The zipcode of customer ", name, "'s second address is now ", zip, "." })); }
From source file:com.qrmedia.commons.persistence.hibernate.clone.HibernateEntityBeanCloner.java
private static Collection<String> calculateTargetedFieldNames(Object entity, boolean preserveIdFields) { Collection<String> targetedFieldNames = new ArrayList<String>(); Class<?> entityClass = entity.getClass(); for (Field field : ClassUtils.getAllDeclaredFields(entityClass)) { String fieldName = field.getName(); // ignore static members and members without a valid getter and setter if (!Modifier.isStatic(field.getModifiers()) && PropertyUtils.isReadable(entity, fieldName) && PropertyUtils.isWriteable(entity, fieldName)) { targetedFieldNames.add(field.getName()); }/* ww w . j ava2 s . c o m*/ } /* * Assume that, in accordance with recommendations, entities are using *either* JPA property * *or* field access. Guess the access type from the location of the @Id annotation, as * Hibernate does. */ Set<Method> idAnnotatedMethods = ClassUtils.getAnnotatedMethods(entityClass, Id.class); boolean usingFieldAccess = idAnnotatedMethods.isEmpty(); // ignore fields annotated with @Version and, optionally, @Id targetedFieldNames.removeAll(usingFieldAccess ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Version.class)) : getPropertyNames(ClassUtils.getAnnotatedMethods(entityClass, Version.class))); if (!preserveIdFields) { targetedFieldNames.removeAll(usingFieldAccess ? getFieldNames(ClassUtils.getAllAnnotatedDeclaredFields(entityClass, Id.class)) : getPropertyNames(idAnnotatedMethods)); } return targetedFieldNames; }
From source file:com.wavemaker.json.AlternateJSONTransformer.java
private static Object toObjectInternal(JSONState jsonState, JSONObject obj, Object root, FieldDefinition fieldDefinition, TypeState typeState, int arrayLevel, Stack<String> setterQueue) throws InstantiationException, IllegalAccessException, InvocationTargetException, NoSuchMethodException {/*from ww w .j av a 2 s. c o m*/ if (fieldDefinition == null) { throw new NullArgumentException("fieldDefinition"); } else if (fieldDefinition.getTypeDefinition() == null) { throw new WMRuntimeException(MessageResource.JSON_TYPEDEF_REQUIRED); } else if (!(fieldDefinition.getTypeDefinition() instanceof ObjectTypeDefinition)) { throw new WMRuntimeException(MessageResource.JSON_OBJECTTYPEDEF_REQUIRED, fieldDefinition.getTypeDefinition(), fieldDefinition.getTypeDefinition().getClass()); } ObjectTypeDefinition otd = (ObjectTypeDefinition) fieldDefinition.getTypeDefinition(); Object instance = otd.newInstance(); for (Object entryO : obj.entrySet()) { Entry<?, ?> entry = (Entry<?, ?>) entryO; String key = (String) entry.getKey(); FieldDefinition nestedFieldDefinition = otd.getFields().get(key); if (nestedFieldDefinition == null) { throw new WMRuntimeException(MessageResource.JSON_NO_PROP_MATCHES_KEY, key, fieldDefinition); } if (!PropertyUtils.isWriteable(instance, key)) { logger.warn(MessageResource.JSON_NO_WRITE_METHOD.getMessage(fieldDefinition, key)); continue; } // setter list support setterQueue.push(key); jsonState.getSettersCalled().add(getPropertyFromQueue(setterQueue)); Object paramValue = toObjectInternal(jsonState, entry.getValue(), root, nestedFieldDefinition, typeState, 0, setterQueue); PropertyUtils.setProperty(instance, key, paramValue); // end setter list support setterQueue.pop(); } return instance; }