Example usage for org.apache.commons.beanutils BeanUtils populate

List of usage examples for org.apache.commons.beanutils BeanUtils populate

Introduction

In this page you can find the example usage for org.apache.commons.beanutils BeanUtils populate.

Prototype

public static void populate(Object bean, Map properties) 

Source Link

Usage

From source file:de.iteratec.turm.servlets.TurmServlet.java

/**
 * Parameters that are contained in the current request are used to fill
 * a given Java Bean. This is similar to the way Struts fills its ActionForms.
 * //w ww. ja va  2s . c  o m
 * @param request The current Serlvet Request
 * @param bean A JavaBean that is to be populated.
 * @throws TurmException If the JavaBean could not be populated.
 */
@SuppressWarnings("unchecked")
protected final void populate(HttpServletRequest request, Object bean) throws TurmException {
    HashMap<String, String[]> map = new HashMap<String, String[]>();
    Enumeration<String> names = request.getParameterNames();
    while (names.hasMoreElements()) {
        String name = names.nextElement();
        map.put(name, request.getParameterValues(name));
    }
    try {
        BeanUtils.populate(bean, map);
    } catch (IllegalAccessException e) {
        throw new TurmException("error.internal", e);
    } catch (InvocationTargetException e) {
        throw new TurmException("error.internal", e);
    }
}

From source file:com.square.client.gwt.server.test.StringConverterTest.java

@SuppressWarnings("unchecked")
private RemotePagingCriteriasDto<?> recupererCriteres(Map<String, String> map, Object criteres) {
    try {/*from  w  ww .  j a va2  s.  co m*/
        BeanUtils.populate(criteres, map);
        final RemotePagingCriteriasDto<?> criterias = new RemotePagingCriteriasDto(criteres, 0,
                Integer.MAX_VALUE);
        BeanUtils.populate(criterias, map);
        return criterias;
    } catch (IllegalAccessException e) {
        e.printStackTrace();
        throw new TechnicalException(Messages.getString("StringConverterTest.63"));
    } catch (InvocationTargetException e) {
        e.printStackTrace();
        throw new TechnicalException(Messages.getString("StringConverterTest.64"));
    }
}

From source file:jdao.JDAO.java

public static DataSource createDataSourceByProperties(String file, DataSource dataSource,
        Properties properties) {/* w  w w  .  j av a2s.com*/
    try {
        adjustPropertiesForEnvParameters(properties);
        if (dataSource == null) {
            if (properties.containsKey("jdaoDriverClassName")) {
                Class.forName(properties.getProperty("jdaoDriverClassName"));
            }
            if (properties.containsKey("jdaoDataSourceClassName")) {
                dataSource = (DataSource) Thread.currentThread().getContextClassLoader()
                        .loadClass(properties.getProperty("jdaoDataSourceClassName")).newInstance();
            } else {
                return (BasicDataSource) BasicDataSourceFactory.createDataSource(properties);
            }
        }
        BeanUtils.populate(dataSource, (Map) properties);
    } catch (Exception xe) {
        log("Error processing datasource: " + file, xe);
        return null;
    }
    return dataSource;
}

From source file:jdao.JDAO.java

public static DataSource createDataSourceByProperties(Class clazz, Properties properties) {
    try {//  w w w.j a v a  2s  . co  m
        adjustPropertiesForEnvParameters(properties);
        DataSource dataSource = null;
        dataSource = (DataSource) clazz.newInstance();
        BeanUtils.populate(dataSource, (Map) properties);
        return dataSource;
    } catch (Exception xe) {
        log("Error processing datasource class: " + clazz.getCanonicalName(), xe);
        return null;
    }
}

From source file:com.bjond.utilities.MiscUtils.java

/**
 * Meant to work like angular.extend()://from  w w w. ja v a2  s  .c  o  m
 * 
 * https://docs.angularjs.org/api/ng/function/angular.extend
 * @param o1 destination object
 * @param o2 source object
 * @return returns the 01
 * @throws Exception if introspection fails.
 */
public static Object extend(final Object o1, final Object o2) throws Exception {

    if (o2 != null) {
        val o2Properties = getNonNullProperties(o2);
        BeanUtils.populate(o1, o2Properties);
    }

    return o1;
}

From source file:fr.paris.lutece.plugins.extend.web.component.ResourceExtenderComponentManager.java

/**
 * {@inheritDoc}//from   ww  w  .  j a  v a 2 s. com
 */
@Override
public void doSaveConfig(ResourceExtenderDTO resourceExtender, HttpServletRequest request)
        throws ExtendErrorException {
    if (resourceExtender != null) {
        IResourceExtenderComponent component = getResourceExtenderComponent(resourceExtender.getExtenderType());

        if (component != null) {
            IExtenderConfig config = component.getConfig(resourceExtender.getIdExtender());

            // If the config is not found, then create it
            if (config == null) {
                IResourceExtender extender = _resourceExtenderService
                        .getResourceExtender(resourceExtender.getExtenderType());

                if (extender != null) {
                    extender.doCreateResourceAddOn(resourceExtender);
                    config = component.getConfig(resourceExtender.getIdExtender());
                }
            }

            if (config != null) {
                try {
                    BeanUtils.populate(config, request.getParameterMap());
                } catch (IllegalAccessException e) {
                    AppLogService.error("Unable to fetch data from request", e);
                } catch (InvocationTargetException e) {
                    AppLogService.error("Unable to fetch data from request", e);
                }

                // Check mandatory fields
                Set<ConstraintViolation<IExtenderConfig>> constraintViolations = BeanValidationUtil
                        .validate(config);

                if (constraintViolations.size() > 0) {
                    Object[] params = { ExtendUtils.buildStopMessage(constraintViolations) };

                    throw new ExtendErrorException(I18nService.getLocalizedString(MESSAGE_STOP_GENERIC_MESSAGE,
                            params, request.getLocale()));
                }

                component.doSaveConfig(request, config);
            }
        }
    }
}

From source file:com.impetus.ankush.common.service.MonitoringManager.java

/**
 * Gets the object list.//from  w ww. j  av  a  2 s .  com
 * 
 * @param <S>
 *            the generic type
 * @param targetClass
 *            the target class
 * @param infoList
 *            the info list
 * @return the object list
 * @throws InstantiationException
 *             the instantiation exception
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
private <S> List<S> getObjectList(Class<S> targetClass, List<Map<String, Object>> infoList)
        throws InstantiationException, IllegalAccessException, InvocationTargetException {
    // Creating the resultant list object.
    List<S> result = new ArrayList<S>(infoList.size());

    // populating values in the list object from map.
    for (Map<String, Object> info : infoList) {
        // creating target class object.
        S status = targetClass.newInstance();
        // populating object with map values.
        BeanUtils.populate(status, info);
        // adding object in result list.
        result.add(status);
    }
    return result;
}

From source file:com.xpn.xwiki.render.macro.rss.RSSMacro.java

/**
 * Transform the input parameters into <code>RSSMacroParameters</code> object.
 * /*from   w  ww  . j  a  v a2 s . c om*/
 * @param parameter the parameters as prepared by the Radeox system.
 * @throws java.lang.IllegalArgumentException if the 'feed' named parameter is missing, or is a malformed URL, or if
 *             any of the other parameter values are not of the correct types. Note that unknown parameters will
 *             simply be ignored, and all parameters must be passed using names.
 * @return a parameters helper object
 * @see RSSMacroParameters
 */
private RSSMacroParameters processParameters(MacroParameter parameter)
        throws java.lang.IllegalArgumentException {
    Map<String, String> paramMap = new HashMap<String, String>();
    RSSMacroParameters paramObj = new RSSMacroParameters();
    String feedURLString = parameter.get("feed");
    if (feedURLString == null) {
        throw new IllegalArgumentException(
                "Requires at least one named parameter,'feed', a URL of an RSS feed.");
    }
    try {
        paramObj.setFeed(feedURLString);
    } catch (MalformedURLException ex) {
        Logger.warn("Invalid feed URL: " + feedURLString);
        throw new IllegalArgumentException("Invalid feed URL: " + feedURLString);
    }
    for (int i = 0; i < PARAM_NAMES.length; i++) {
        String paramName = parameter.get(PARAM_NAMES[i]);
        if (paramName != null) {
            paramMap.put(PARAM_NAMES[i], paramName);
        }
    }
    try {
        BeanUtils.populate(paramObj, paramMap);
    } catch (NoClassDefFoundError e) {
        throw new IllegalStateException("Some libraries are not installed: " + e.getMessage());
    } catch (Exception ex) {
        throw new IllegalArgumentException("Error processing arguments: " + ex.getMessage());
    }

    return paramObj;
}

From source file:fr.paris.lutece.plugins.extend.modules.comment.web.CommentApp.java

/**
 * Do add comment./*from   ww  w.  j av  a2s  . c o m*/
 * 
 * @param request the request
 * @param strIdExtendableResource the str id extendable resource
 * @param strExtendableResourceType the str extendable resource type
 * @return The page to display, or null to display the default page
 * @throws SiteMessageException the site message exception
 */
private XPage doAddComment(HttpServletRequest request, String strIdExtendableResource,
        String strExtendableResourceType) throws SiteMessageException {
    Comment comment = new Comment();

    try {
        BeanUtils.populate(comment, request.getParameterMap());
    } catch (IllegalAccessException e) {
        AppLogService.error("Unable to fetch data from request", e);
    } catch (InvocationTargetException e) {
        AppLogService.error("Unable to fetch data from request", e);
    }

    // Check mandatory fields
    Set<ConstraintViolation<Comment>> constraintViolations = BeanValidationUtil.validate(comment);

    if (constraintViolations.size() > 0) {
        Object[] params = { buildStopMessage(constraintViolations) };

        SiteMessageService.setMessage(request, MESSAGE_STOP_GENERIC_MESSAGE, params, SiteMessage.TYPE_STOP);
    }

    if (StringUtils.isBlank(comment.getName()) || StringUtils.isBlank(comment.getComment())
            || StringUtils.isBlank(comment.getEmail())) {
        SiteMessageService.setMessage(request, Messages.MANDATORY_FIELDS, SiteMessage.TYPE_STOP);
    }

    // Test the captcha
    if (_bIsCaptchaEnabled) {
        CaptchaSecurityService captchaService = new CaptchaSecurityService();

        if (!captchaService.validate(request)) {
            SiteMessageService.setMessage(request, MESSAGE_ERROR_BAD_JCAPTCHA, SiteMessage.TYPE_STOP);
        }
    }

    CommentExtenderConfig config = getConfigService().find(CommentResourceExtender.EXTENDER_TYPE_COMMENT,
            strIdExtendableResource, strExtendableResourceType);

    if (config != null) {
        comment.setIpAddress(SecurityUtil.getRealIp(request));
        comment.setIdExtendableResource(strIdExtendableResource);
        comment.setExtendableResourceType(strExtendableResourceType);
        comment.setPublished(!config.isModerated());
        if (!config.getAuthorizeSubComments()) {
            comment.setIdParentComment(0);
        }
        boolean bIsCreated = false;

        try {
            getCommentService().create(comment);
            bIsCreated = true;
        } catch (Exception ex) {
            // Something wrong happened... a database check might be needed
            AppLogService.error(ex.getMessage() + " when creating a comment ", ex);
            // Revert
            getCommentService().remove(comment.getIdComment());

            SiteMessageService.setMessage(request, CommentConstants.MESSAGE_ERROR_GENERIC_MESSAGE,
                    SiteMessage.TYPE_ERROR);
        }

        if (bIsCreated) {
            // Add to the resource extender history
            getResourceExtenderHistoryService().create(CommentResourceExtender.EXTENDER_TYPE_COMMENT,
                    strIdExtendableResource, strExtendableResourceType, request);

            // Notify the mailing list
            sendCommentNotification(request, comment, config);

            XPage page = new XPage();
            page.setTitle(I18nService.getLocalizedString(CommentConstants.PROPERTY_XPAGE_ADD_COMMENT_PAGE_TITLE,
                    request.getLocale()));
            page.setPathLabel(I18nService.getLocalizedString(
                    CommentConstants.PROPERTY_XPAGE_ADD_COMMENT_PAGE_LABEL, request.getLocale()));

            String strPostBackUrl = (String) request.getSession()
                    .getAttribute(ExtendPlugin.PLUGIN_NAME + CommentConstants.SESSION_COMMENT_POST_BACK_URL);
            if (strPostBackUrl == null) {
                strPostBackUrl = JSP_URL_DEFAULT_POST_BACK;
            }
            String strFromUrl = request.getParameter(CommentConstants.PARAMETER_FROM_URL);
            if (FROM_SESSION.equals(strFromUrl)) {
                strFromUrl = (String) request.getSession()
                        .getAttribute(ExtendPlugin.PLUGIN_NAME + CommentConstants.PARAMETER_FROM_URL);
            }
            if (strFromUrl != null) {
                strFromUrl = strFromUrl.replaceAll(CONSTANT_AND_HTML, CONSTANT_AND);
            }
            Map<String, Object> model = new HashMap<String, Object>();
            model.put(CommentConstants.MARK_MESSAGE_COMMENT_CREATED, config.getMessageCommentCreated());
            model.put(CommentConstants.MARK_ID_EXTENDABLE_RESOURCE, strIdExtendableResource);
            model.put(CommentConstants.MARK_EXTENDABLE_RESOURCE_TYPE, strExtendableResourceType);
            model.put(CommentConstants.PARAMETER_ID_COMMENT,

                    comment.getIdParentComment() == 0 ? comment.getIdComment() : comment.getIdParentComment());
            model.put(CommentConstants.PARAMETER_POST_BACK_URL, strPostBackUrl);
            model.put(CommentConstants.MARK_RETURN_TO_COMMENT_LIST,
                    Boolean.parseBoolean(request.getParameter(CommentConstants.MARK_RETURN_TO_COMMENT_LIST)));
            model.put(CommentConstants.PARAMETER_FROM_URL, strFromUrl);

            HtmlTemplate template = AppTemplateService.getTemplate(TEMPLATE_XPAGE_MESSAGE_COMMENT_CREATED,
                    request.getLocale(), model);

            page.setContent(template.getHtml());

            return page;
        }
        return null;
    }
    SiteMessageService.setMessage(request, CommentConstants.MESSAGE_ERROR_GENERIC_MESSAGE,
            SiteMessage.TYPE_ERROR);
    return null;
}

From source file:com.aw.swing.mvp.Presenter.java

private Presenter setBackBean(E backBean, boolean clear) {
    TimeObserver time = new TimeObserver("setting backBean");
    time.empezar();/* w  w w. j ava2  s . c o  m*/
    this.backBean = backBean;
    initializeBackBean(backBean, clear);
    if (backBeanAttributes.size() > 0) {
        try {
            BeanUtils.populate(backBean, backBeanAttributes);
        } catch (Throwable e) {
            new AWSystemException("Problems setting attributes to:<" + backBean + ">", e);
        }
    }
    time.terminar();
    return this;
}