List of usage examples for org.apache.commons.beanutils PropertyUtils setProperty
public static void setProperty(Object bean, String name, Object value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException
Set 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.sqewd.open.dal.core.persistence.csv.CSVPersister.java
@SuppressWarnings({ "unchecked", "rawtypes" }) protected void setFieldValue(final AbstractEntity entity, final Field fd, final Object value) throws Exception { Object pvalue = value;/*from ww w . ja va2s.c o m*/ if (fd.getType().equals(String.class)) { pvalue = value; } else if (fd.getType().equals(Date.class)) { pvalue = DateUtils.fromString((String) value); } else if (EnumPrimitives.isPrimitiveType(fd.getType())) { EnumPrimitives pt = EnumPrimitives.type(fd.getType()); switch (pt) { case ECharacter: pvalue = ((String) value).charAt(0); break; case EShort: pvalue = Short.parseShort((String) value); break; case EInteger: pvalue = Integer.parseInt((String) value); break; case ELong: pvalue = Long.parseLong((String) value); break; case EFloat: pvalue = Float.parseFloat((String) value); break; case EDouble: pvalue = Double.parseDouble((String) value); break; default: throw new Exception("Unsupported primitive type [" + pt.name() + "]"); } } else if (fd.getType().isEnum()) { Class ecls = fd.getType(); pvalue = Enum.valueOf(ecls, (String) value); } else if (pvalue.getClass().isAnnotationPresent(Entity.class)) { pvalue = value; } else throw new Exception("Field type [" + fd.getType().getCanonicalName() + "] is not supported."); PropertyUtils.setProperty(entity, fd.getName(), pvalue); }
From source file:net.openkoncept.vroom.VroomController.java
private void processRequestSubmit(HttpServletRequest request, HttpServletResponse response, Map paramMap) throws ServletException { // change the URI below with the actual page who invoked the request. String uri = request.getParameter(CALLER_URI); String id = request.getParameter(ID); String method = request.getParameter(METHOD); String beanClass = request.getParameter(BEAN_CLASS); String var = request.getParameter(VAR); String scope = request.getParameter(SCOPE); if (paramMap != null) { uri = (String) ((ArrayList) paramMap.get(CALLER_URI)).get(0); id = (String) ((ArrayList) paramMap.get(ID)).get(0); method = (String) ((ArrayList) paramMap.get(METHOD)).get(0); beanClass = (String) ((ArrayList) paramMap.get(BEAN_CLASS)).get(0); var = (String) ((ArrayList) paramMap.get(VAR)).get(0); scope = (String) ((ArrayList) paramMap.get(SCOPE)).get(0); }//from w ww . ja va 2s . c o m Object beanObject; String outcome = null; // call form method... try { Class clazz = Class.forName(beanClass); Class elemClass = clazz; String eId, eProperty, eBeanClass, eVar, eScope, eFormat; // Setting values to beans before calling the method... List<Element> elements = VroomConfig.getInstance().getElements(uri, id, method, beanClass, var, scope); for (Element e : elements) { eId = e.getId(); eProperty = (e.getProperty() != null) ? e.getProperty() : eId; eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass; eVar = (e.getVar() != null) ? e.getVar() : var; eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope; eFormat = e.getFormat(); if (!elemClass.getName().equals(eBeanClass)) { try { elemClass = Class.forName(eBeanClass); } catch (ClassNotFoundException ex) { throw new ServletException("Failed to load class for element [" + eId + "]", ex); } } if (elemClass != null) { try { Object obj = getObjectFromScope(request, elemClass, eVar, eScope); if (PropertyUtils.isWriteable(obj, eProperty)) { Class propType = PropertyUtils.getPropertyType(obj, eProperty); Object[] paramValues = request.getParameterValues(eId); Object value = null; value = getParameterValue(propType, eId, paramValues, eFormat, paramMap); PropertyUtils.setProperty(obj, eProperty, value); } } catch (InstantiationException ex) { throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex); } catch (IllegalAccessException ex) { throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex); } } } // Calling the method... beanObject = getObjectFromScope(request, clazz, var, scope); Class[] signature = new Class[] { HttpServletRequest.class, HttpServletResponse.class }; Method m = clazz.getMethod(method, signature); Object object = m.invoke(beanObject, new Object[] { request, response }); // Getting updating values from beans to pass as postback for the forward calls. Map<String, Object> postbackMap = new HashMap<String, Object>(); for (Element e : elements) { eId = e.getId(); eProperty = (e.getProperty() != null) ? e.getProperty() : eId; eBeanClass = (e.getBeanClass() != null) ? e.getBeanClass() : beanClass; eVar = (e.getVar() != null) ? e.getVar() : var; eScope = (e.getBeanClass() != null) ? e.getScope().value() : scope; eFormat = e.getFormat(); if (!elemClass.getName().equals(eBeanClass)) { try { elemClass = Class.forName(eBeanClass); } catch (ClassNotFoundException ex) { throw new ServletException("Failed to load class for element [" + eId + "]", ex); } } if (elemClass != null) { try { Object obj = getObjectFromScope(request, elemClass, eVar, eScope); if (PropertyUtils.isReadable(obj, eProperty)) { // Class propType = PropertyUtils.getPropertyType(obj, eProperty); // Object[] paramValues = request.getParameterValues(eId); // Object value = null; // value = getParameterValue(propType, eId, paramValues, eFormat, paramMap); // PropertyUtils.setProperty(obj, eProperty, value); Object value = PropertyUtils.getProperty(obj, eProperty); postbackMap.put(eId, value); } } catch (InstantiationException ex) { throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex); } catch (IllegalAccessException ex) { throw new ServletException("Failed to create object of type [" + eBeanClass + "]", ex); } } } if (object == null || object instanceof String) { outcome = (String) object; Navigation n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, outcome); if (n == null) { n = VroomConfig.getInstance().getNavigation(uri, id, method, beanClass, var, scope, "default"); } if (n != null) { String url = n.getUrl(); if (url == null) { url = "/"; } url = url.replaceAll("#\\{contextPath}", request.getContextPath()); if (n.isForward()) { String ctxPath = request.getContextPath(); if (url.startsWith(ctxPath)) { url = url.substring(ctxPath.length()); } PrintWriter pw = response.getWriter(); VroomResponseWrapper responseWrapper = new VroomResponseWrapper(response); RequestDispatcher rd = request.getRequestDispatcher(url); rd.forward(request, responseWrapper); StringBuffer sbHtml = new StringBuffer(responseWrapper.toString()); VroomHtmlProcessor.addHeadMetaTags(sbHtml, uri, VroomConfig.getInstance()); VroomHtmlProcessor.addHeadLinks(sbHtml, uri, VroomConfig.getInstance()); VroomHtmlProcessor.addRequiredScripts(sbHtml, request); VroomHtmlProcessor.addInitScript(sbHtml, uri, request); VroomHtmlProcessor.addHeadScripts(sbHtml, uri, VroomConfig.getInstance(), request); VroomHtmlProcessor.addStylesheets(sbHtml, uri, VroomConfig.getInstance(), request); // Add postback values to webpage through javascript... VroomHtmlProcessor.addPostbackScript(sbHtml, uri, request, postbackMap); String html = sbHtml.toString().replaceAll("#\\{contextPath}", request.getContextPath()); response.setContentLength(html.length()); pw.print(html); } else { response.sendRedirect(url); } } else { throw new ServletException("No navigation found for outcome [" + outcome + "]"); } } } catch (ClassNotFoundException ex) { throw new ServletException("Invocation Failed for method [" + method + "]", ex); } catch (InstantiationException ex) { throw new ServletException("Invocation Failed for method [" + method + "]", ex); } catch (IllegalAccessException ex) { throw new ServletException("Invocation Failed for method [" + method + "]", ex); } catch (NoSuchMethodException ex) { throw new ServletException("Invocation Failed for method [" + method + "]", ex); } catch (InvocationTargetException ex) { throw new ServletException("Invocation Failed for method [" + method + "]", ex); } catch (IOException ex) { throw new ServletException("Navigation Failed for outcome [" + outcome + "]", ex); } }
From source file:com.bstek.dorado.idesupport.template.RuleTemplate.java
private static void applyProperty(Object source, Object target, String propertyName) throws Exception { Object value = PropertyUtils.getProperty(source, propertyName); if (value != null && PropertyUtils.getProperty(target, propertyName) == null) PropertyUtils.setProperty(target, propertyName, value); }
From source file:gr.abiss.calipso.controller.AbstractServiceBasedRestController.java
protected void applyCurrentPrincipal(T resource) { Field[] fields = FieldUtils.getFieldsWithAnnotation(this.service.getDomainClass(), ApplyCurrentPrincipal.class); //ApplyPrincipalUse predicate = this.service.getDomainClass().getAnnotation(CurrentPrincipalIdPredicate.class); if (fields.length > 0) { ICalipsoUserDetails principal = this.service.getPrincipal(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; ApplyCurrentPrincipal applyRule = field.getAnnotation(ApplyCurrentPrincipal.class); // if property is not already set try { if (PropertyUtils.getProperty(resource, field.getName()) == null) { boolean skipApply = this.hasAnyRoles(applyRule.ignoreforRoles()); // if role is not ignored if (!skipApply) { String id = principal != null ? principal.getId() : null; if (id != null) { User user = new User(); user.setId(id); LOGGER.info("Applying principal to field: " + field.getName() + ", value: " + id); PropertyUtils.setProperty(resource, field.getName(), user); } else { LOGGER.warn( "User is anonymous, cannot apply principal to field: " + field.getName()); }//from w w w .j a v a 2 s . c o m } else { LOGGER.info("Skipping setting principal to field: " + field.getName()); } } } catch (Exception e) { throw new RuntimeException("Failed to apply ApplyCurrentPrincipal annotation", e); } } } }
From source file:com.p6spy.engine.spy.XADataSourceTest.java
public void setXADSProperties(XADataSource ds, String url, String userName, String password) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException { if (url.contains(":derby:") || url.contains(":sqlfire:")) { PropertyUtils.setProperty(ds, "databaseName", "p6spy_xds"); PropertyUtils.setProperty(ds, "createDatabase", "create"); return;//from ww w.j a va 2 s . c om } else if (url.contains(":firebirdsql:")) { PropertyUtils.setProperty(ds, "databaseName", url.replace("jdbc:firebirdsql:", "")); } else if (PropertyUtils.isWriteable(ds, "URL")) { PropertyUtils.setProperty(ds, "URL", url); } else if (PropertyUtils.isWriteable(ds, "Url")) { PropertyUtils.setProperty(ds, "Url", url); } else if (PropertyUtils.isWriteable(ds, "url")) { PropertyUtils.setProperty(ds, "url", url); } else if (PropertyUtils.isWriteable(ds, "serverName") && PropertyUtils.isWriteable(ds, "portNumber") && PropertyUtils.isWriteable(ds, "databaseName") && URL_PATTERN.matcher(url).matches()) { final Matcher matcher = URL_PATTERN.matcher(url); if (!matcher.matches()) { throw new IllegalArgumentException("url in incorrect format: " + url); } final String host = matcher.group(2); final String port = matcher.group(3); final String db = matcher.group(4); PropertyUtils.setProperty(ds, "serverName", host); if (null != port && !port.isEmpty()) { PropertyUtils.setProperty(ds, "portNumber", Integer.parseInt(port)); } PropertyUtils.setProperty(ds, "databaseName", db); } else { throw new IllegalArgumentException( "Datasource imlpementation not supported by tests (yet) (for url setting): " + ds); } if (PropertyUtils.isWriteable(ds, "userName")) { PropertyUtils.setProperty(ds, "userName", userName); } else if (PropertyUtils.isWriteable(ds, "user")) { PropertyUtils.setProperty(ds, "user", userName); } else { throw new IllegalArgumentException( "Datasource imlpementation not supported by tests (yet) (for username setting): " + ds); } if (PropertyUtils.isWriteable(ds, "password")) { PropertyUtils.setProperty(ds, "password", password); } else { throw new IllegalArgumentException( "Datasource imlpementation not supported by tests (yet) (for password setting): " + ds); } }
From source file:com.feilong.core.bean.PropertyUtil.java
/** * {@link PropertyUtils#setProperty(Object, String, Object)} ?bean(<b>??</b>). * /*w w w . j av a2 s.co m*/ * <p> * no matter which property reference format is used, with no type conversions. * </p> * * <h3>:</h3> * * <blockquote> * * <pre class="code"> * * User newUser = new User(); * PropertyUtil.setProperty(newUser, "name", "feilong"); * LOGGER.info(JsonUtil.format(newUser)); * * </pre> * * <b>:</b> * * <pre class="code"> * { * "age": 0, * "name": "feilong" * } * </pre> * * </blockquote> * * <h3>?:</h3> * * <blockquote> * * <ol> * <li> <code>bean</code> null, {@link NullPointerException}</li> * <li> <code>propertyName</code> null, {@link NullPointerException}</li> * <li> <code>propertyName</code> blank, {@link IllegalArgumentException}</li> * <li><code>bean</code> <code>propertyName</code>??,,see * {@link PropertyUtilsBean#setSimpleProperty(Object, String, Object) setSimpleProperty} Line2078</li> * <li>Date,<span style="color:red">??converter</span></li> * </ol> * </blockquote> * * @param bean * Bean whose property is to be modified * @param propertyName * ?? (can be nested/indexed/mapped/combo),?? <a href="../BeanUtil.html#propertyName">propertyName</a> * @param value * Value to which this property is to be set * @see org.apache.commons.beanutils.BeanUtils#setProperty(Object, String, Object) * @see org.apache.commons.beanutils.PropertyUtils#setProperty(Object, String, Object) * @see BeanUtil#setProperty(Object, String, Object) */ public static void setProperty(Object bean, String propertyName, Object value) { Validate.notNull(bean, "bean can't be null!"); Validate.notBlank(propertyName, "propertyName can't be null!"); try { PropertyUtils.setProperty(bean, propertyName, value); } catch (Exception e) { throw new BeanUtilException(e); } }
From source file:hudson.maven.MavenModuleSet.java
/** * @since 1.491/*w w w . ja v a2s . c om*/ */ public Object readResolve() { // backward compatibility, maven-plugin used to have a dependency to the config-file-provider plugin Plugin plugin = null; if (StringUtils.isNotBlank(this.settingConfigId) || StringUtils.isNotBlank(this.globalSettingConfigId)) { plugin = Jenkins.getInstance().getPlugin("config-file-provider"); if (plugin == null || !plugin.getWrapper().isEnabled()) { LOGGER.severe(Messages.MavenModuleSet_readResolve_missingConfigProvider()); } } if (this.alternateSettings != null) { this.settings = new FilePathSettingsProvider(alternateSettings); this.alternateSettings = null; } else if (plugin != null && StringUtils.isNotBlank(this.settingConfigId)) { try { Class<? extends SettingsProvider> legacySettings = plugin.getWrapper().classLoader .loadClass("org.jenkinsci.plugins.configfiles.maven.job.MvnSettingsProvider") .asSubclass(SettingsProvider.class); SettingsProvider newInstance = legacySettings.newInstance(); PropertyUtils.setProperty(newInstance, "settingsConfigId", this.settingConfigId); this.settings = newInstance; this.settingConfigId = null; } catch (Exception e) { // The PluginUpdateMonitor is also informing the admin about the update (via hudson.maven.PluginImpl.init()) LOGGER.severe(Messages.MavenModuleSet_readResolve_updateConfigProvider(settingConfigId)); e.printStackTrace(); } } if (plugin != null && StringUtils.isNotBlank(this.globalSettingConfigId)) { try { Class<? extends GlobalSettingsProvider> legacySettings = plugin.getWrapper().classLoader .loadClass("org.jenkinsci.plugins.configfiles.maven.job.MvnGlobalSettingsProvider") .asSubclass(GlobalSettingsProvider.class); GlobalSettingsProvider newInstance = legacySettings.newInstance(); PropertyUtils.setProperty(newInstance, "settingsConfigId", this.globalSettingConfigId); this.globalSettings = newInstance; this.globalSettingConfigId = null; } catch (Exception e) { // The PluginUpdateMonitor is also informing the admin about the update (via hudson.maven.PluginImpl.init()) LOGGER.severe(Messages.MavenModuleSet_readResolve_updateConfigProvider(globalSettingConfigId)); e.printStackTrace(); } } return this; }
From source file:de.micromata.genome.util.types.Converter.java
/** * Copy convert big decimal.// w ww. j a v a2 s.c o m * * @param source the source * @param sourceName the source name * @param target the target * @param targetName the target name * @return true, if successful */ public static boolean copyConvertBigDecimal(Object source, String sourceName, Object target, String targetName) { try { Object so = PropertyUtils.getProperty(source, sourceName); BigDecimal bd = null; if (so instanceof BigDecimal) { bd = (BigDecimal) so; } else { String s = (String) so; s = s.replace(',', '.'); bd = new BigDecimal(s); } PropertyUtils.setProperty(target, targetName, bd); return true; } catch (Throwable ex) { // NOSONAR "Illegal Catch" framework return false; } }
From source file:com.all.tracker.controllers.DownloadMetricsController.java
public <T> T setFeatures(String[] features, Class<T> clazz) throws InstantiationException, IllegalAccessException { if (clazz == null || features == null || features.length == 0) { log.error("exception when try to create a SyncAble entity"); return null; }//from w w w. j ava 2 s. c o m T obj = clazz.newInstance(); for (String item : features) { String[] feature = splitMetrics(item, charset_inside); if (feature.length == 2) { if (PropertyUtils.isWriteable(obj, feature[0])) { try { PropertyUtils.setProperty(obj, feature[0], feature[1]); } catch (InvocationTargetException e) { log.error(e.getMessage()); } catch (NoSuchMethodException e) { log.error(e.getMessage()); } } } } return obj; }
From source file:com.tonbeller.wcf.form.FormComponent.java
/** * restores all editable properties from the bookmark state. Editable * properties are addressed via the <code>modelReference</code> * attribute in the DOM./*from www . j ava 2 s . c o m*/ */ public void setBookmarkState(Object state) { if (!bookmarkable) return; if (!(state instanceof Map)) return; super.setBookmarkState(state); Map map = (Map) state; try { DOMXPath dx = new DOMXPath("//*[@modelReference]"); for (Iterator it = dx.selectNodes(getDocument()).iterator(); it.hasNext();) { Element elem = (Element) it.next(); if ("false".equals(elem.getAttribute("bookmark"))) continue; // Properties may be added and removed over time. // So we react gentle if setting of a property fails try { String ref = XoplonCtrl.getModelReference(elem); Object value = map.get(ref); if (value != null) PropertyUtils.setProperty(bean, ref, value); } catch (IllegalAccessException e1) { logger.error(null, e1); } catch (InvocationTargetException e1) { logger.error(null, e1); logger.error(null, e1.getTargetException()); } catch (NoSuchMethodException e1) { logger.warn(null, e1); } } } catch (JaxenException e) { logger.error(null, e); } }