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:it.geosolutions.unredd.onlinestats.ppio.JAXBStatisticConfigurationPPIO.java

private Object populate(Map m, Class c) throws InstantiationException, IllegalAccessException,
        InvocationTargetException, NoSuchMethodException {
    Object o = c.newInstance();/*from w ww. j av  a 2s. c o m*/
    for (Object eo : m.entrySet()) {
        Entry e = (Entry) eo;
        Object v = e.getValue();
        Class<?> ec = v.getClass();
        if (Map.class.isAssignableFrom(ec)) {
            PropertyUtilsBean pub = new PropertyUtilsBean();
            String ek = (String) e.getKey();
            PropertyDescriptor pd = pub.getPropertyDescriptor(o, ek);
            Class pt = pd.getPropertyType();
            if (List.class.isAssignableFrom(pt)) {
                Class k = Object.class;
                if (ek.equals("classifications")) {
                    k = ClassificationLayer.class;
                    //} else if (ek.equals("topics")) {
                    //   k = String.class;
                    //} else if (ek.equals("stats")) {
                    //   k = StatsType.class;
                }
                List l = new ArrayList();
                // This is the point where I give up.
                Object ojeto = populate((Map) e.getValue(), k);
                l.add(ojeto);
                m.put(ek, l);
            } else {
                Object p = populate((Map) e.getValue(), pt);
                m.put(ek, p);
            }
        }
    }
    BeanUtils.populate(o, m);
    return o;
}

From source file:com.icesoft.faces.webapp.parser.ELSetPropertiesRule.java

public void begin(Attributes attributes) throws Exception {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HashMap values = new HashMap();
    Object top = digester.peek();

    for (int i = 0; i < attributes.getLength(); i++) {
        String name = attributes.getLocalName(i);
        if ("".equals(name)) {
            name = attributes.getQName(i);
        }//from  w ww  .  j  a v a 2 s .com
        String value = attributes.getValue(i);

        //take a guess at the types of the JSF 1.2 tag members
        //we are probably better off doing this reflectively
        if (name != null) {
            values.put(name, value);
            if (("id".equals(name)) || ("name".equals(name)) || ("var".equals(name))) {
                values.put(name, value);
            } else if (top instanceof UIComponentTag) {
                //must be a JSF 1.1 tag
                values.put(name, value);
            } else if ("action".equals(name)) {
                values.put(name, getMethodExpression(facesContext, name, value, null));
            } else if ("validator".equals(name)) {
                values.put(name, getMethodExpression(facesContext, name, value, null));
            } else if ("actionListener".equals(name)) {
                values.put(name, getMethodExpression(facesContext, name, value, ActionEvent.class));
            } else if ("valueChangeListener".equals(name)) {
                values.put(name, getMethodExpression(facesContext, name, value, ValueChangeEvent.class));
            } else {
                values.put(name, getValueExpression(facesContext, name, value));
            }
            if (top instanceof javax.faces.webapp.UIComponentELTag) {
                //special case for 
                //com.sun.faces.taglib.jsf_core.ParameterTag
                //and potentially others
                if ("name".equals(name)) {
                    values.put(name, getValueExpression(facesContext, name, value));
                } else if ("locale".equals(name)) {
                    values.put(name, getValueExpression(facesContext, name, value));
                }
            } else {
                //reflection based code as mentioned above.  More likely
                //to be correct, but performance may not be as good,
                //so only applying it in a specific case
                if ("name".equals(name)) {
                    Method setNameMethod = null;
                    try {
                        setNameMethod = top.getClass().getMethod("setName",
                                new Class[] { ValueExpression.class });
                    } catch (Exception e) {
                    }
                    if (null != setNameMethod) {
                        values.put(name, getValueExpression(facesContext, name, value));
                    }
                }

            }

        }
    }

    BeanUtils.populate(top, values);
}

From source file:com.adito.core.actions.AbstractMultiFormDispatchAction.java

private static SubActionWrapper getSubActionWrapper(ActionMapping mapping, ActionForm form,
        ActionMapping subMapping, HttpServletRequest request, int index) throws ClassNotFoundException,
        IllegalAccessException, InstantiationException, InvocationTargetException {
    String formName = subMapping.getName();
    ActionForm subForm = getActionForm(subMapping, request);

    FormBeanConfig formBean = mapping.getModuleConfig().findFormBeanConfig(formName);
    String className = formBean == null ? null : formBean.getType();
    if (className == null)
        return null;

    if (subForm == null || !className.equals(subForm.getClass().getName()))
        subForm = (ActionForm) Class.forName(className).newInstance();

    if ("request".equals(mapping.getScope()))
        request.setAttribute(formName, subForm);
    else/*from   w ww. ja va2 s.com*/
        request.getSession().setAttribute(formName, subForm);

    subForm.reset(mapping, request);

    /*
     * We dont want to try and populate all forms on a post, only the one
     * that has requested it. For this the form must have a hidden parameter
     * with the name of 'subForm' and the value being the form name to
     * populate
     */
    AbstractMultiFormDispatchForm dispatchForm = (AbstractMultiFormDispatchForm) form;
    if (formName.equals(dispatchForm.getSubForm())) {
        dispatchForm.setSelectedTab(dispatchForm.getTabName(index));
        BeanUtils.populate(subForm, request.getParameterMap());
    }

    return new SubActionWrapper(subForm, subMapping);
}

From source file:com.javaeeeee.dropbookmarks.resources.BookmarksResource.java

/**
 * A method to modify an existing bookmark data.
 *
 * @param id the id of the bookmark to be modified.
 * @param jsonData Modifications in JSON format.
 * @param user Authenticated user with whose bookmarks we work.
 * @return Bookmark with modified fields or throws an exception if bookmark
 * was not found./*from  w ww . ja va 2 s . c o m*/
 */
@PUT
@Path("/{id}")
@UnitOfWork
public Bookmark modifyBookmark(@PathParam("id") IntParam id, String jsonData, @Auth User user) {

    Bookmark bookmark = findBookmarkOrTrowException(id, user);

    // Update bookmark data
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, String> changeMap = null;
    try {
        changeMap = objectMapper.readValue(jsonData, HashMap.class);
        purgeMap(changeMap);
        BeanUtils.populate(bookmark, changeMap);
        return bookmarkDAO.save(bookmark);
    } catch (IOException | IllegalAccessException | InvocationTargetException ex) {
        LOGGER.warn(WRONG_BODY_DATA_FORMAT, ex);
        throw new WebApplicationException(WRONG_BODY_DATA_FORMAT, ex, Response.Status.BAD_REQUEST);
    } finally {
        if (changeMap != null) {
            changeMap.clear();
        }
    }
}

From source file:com.sjtu.icare.modules.gero.webservice.GeroRestController.java

@Transactional
@RequestMapping(method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
public Object postGero(@RequestBody String inJson) {
    // ??? Map/* w  w  w  .j  a  v  a 2 s.  c  o m*/
    Map<String, Object> tempRquestParamMap = ParamUtils.getMapByJson(inJson, logger);
    Map<String, Object> requestParamMap = MapListUtils.convertMapToCamelStyle(tempRquestParamMap);
    requestParamMap.put("registerDate", DateUtils.getDateTime());

    try {
        if (requestParamMap.get("name") == null || requestParamMap.get("city") == null
                || requestParamMap.get("district") == null)
            throw new Exception();

        if (requestParamMap.get("contactId") != null
                && StringUtils.isBlank((CharSequence) requestParamMap.get("contactId")))
            throw new Exception();
        // ??
        // TODO
    } catch (Exception e) {
        String otherMessage = "[" + inJson + "]";
        String message = ErrorConstants.format(ErrorConstants.GERO_POST_PARAM_INVALID, otherMessage);
        logger.error(message);
        throw new RestException(HttpStatus.BAD_REQUEST, message);
    }

    // ? JSON
    BasicReturnedJson basicReturnedJson = new BasicReturnedJson();

    // ??
    try {

        GeroEntity requestGeroEntity = new GeroEntity();
        BeanUtils.populate(requestGeroEntity, requestParamMap);
        geroService.insertGero(requestGeroEntity);

    } catch (Exception e) {
        String otherMessage = "[" + e.getMessage() + "]";
        String message = ErrorConstants.format(ErrorConstants.GERO_POST_SERVICE_FAILED, otherMessage);
        logger.error(message);
        throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, message);
    }

    return basicReturnedJson.getMap();

}

From source file:hermes.browser.dialog.GeneralRendererConfigPanel.java

public void initState() {
    configChanges.clear();/*ww  w .  ja va  2 s .co m*/

    for (final MessageRenderer renderer : HermesBrowser.getRendererManager().getRenderers()) {
        try {
            final String className = renderer.getClass().getName();
            final Map properties = BeanUtils.describe(renderer);
            final MessageRenderer.Config rendererConfig = renderer.getConfig() != null ? renderer.getConfig()
                    : renderer.createConfig();

            if (rendererConfig != null) {
                BeanUtils.populate(rendererConfig, properties);

                final ConfigDialogProxy proxy = new ConfigDialogProxy() {
                    public Config getConfig() {
                        return rendererConfig;
                    }

                    public void setDirty() {
                        dialog.setDirty();
                    }
                };

                configChanges.put(className, proxy);
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}

From source file:com.ge.apm.service.data.DataService.java

@Transactional
public String postData(String tablename, List<Map> list) throws IllegalAccessException, InstantiationException,
        NoSuchMethodException, InvocationTargetException {
    if (tablename == null)
        return "{\"code\":\"1\",\"msg\":\"please input table_name\"}";
    if (list == null || list.isEmpty())
        return "{\"code\":\"1\",\"msg\":\"no data post\"}";
    String tableName = tablename.toLowerCase();
    String talbeClassName = "com.ge.apm.domain." + tabelNameToClassName(tableName);
    String daoName = "com.ge.apm.dao." + tabelNameToClassName(tableName) + "Repository";
    Class<?> dao = getDao(daoName);
    Class<?> table = getDao(talbeClassName);
    if (dao == null || table == null)
        return "{\"code\":\"1\",\"msg\":\"save failed\"}";
    int fortimes = list.size() / 50 + 1;//
    for (int j = 0; j < fortimes; j++) {
        List<Map> subList = list.subList(j * 50, (j + 1) * 50 < list.size() ? (j + 1) * 50 : list.size());
        List saveList = new ArrayList();
        for (int i = 0; i < subList.size(); i++) {
            Object obj = table.newInstance();
            BeanUtils.populate(obj, subList.get(i));
            BeanUtils.setProperty(obj, "id", null);
            saveList.add(obj);//w w w  . j  a va2s  .c o  m
        }
        dao.getMethod("save", Iterable.class).invoke(WebUtil.getBean(dao), saveList);
    }
    return "{\"code\":\"0\",\"msg\":\"save success\"}";//?
}

From source file:fr.paris.lutece.plugins.directory.business.DirectoryHome.java

/**
 * Returns an instance of a directory whose identifier is specified in parameter
 *
 * @param nKey The entry primary key/*from w  w w.  j ava 2 s.  c o  m*/
 * @param plugin the Plugin
 * @return an instance of directory
 */
public static Directory findByPrimaryKey(int nKey, Plugin plugin) {
    Directory directory = _dao.load(nKey, plugin);
    Map<String, Object> mapAttributes = DirectoryAttributeHome.findByPrimaryKey(nKey);

    try {
        BeanUtils.populate(directory, mapAttributes);
    } catch (IllegalAccessException e) {
        AppLogService.error(e);
    } catch (InvocationTargetException e) {
        AppLogService.error(e);
    }

    return directory;
}

From source file:adminServlets.AddProductServlet.java

private void insertProduct(HttpServletRequest request, HttpServletResponse response) {

    try {//from  w  ww.java2s  .c  om
        Product product = new Product();
        Flower flower = null;
        ArrayList<Flower> listFlowers = new ArrayList<>();
        ArrayList<String> listOfFlowers = new ArrayList<>();
        for (Map.Entry<String, String> entry : paramaters.entrySet()) {
            String key = entry.getKey();
            if (key.contains("flower")) {
                listOfFlowers.add(entry.getValue());
            }
        }
        for (String listFlower : listOfFlowers) {
            flower = new Flower();
            flower.setName(listFlower);
            listFlowers.add(flower);
        }
        BeanUtils.populate(product, paramaters);
        product.setFlowers(listFlowers);
        ProductService productService = new ProductService();
        if (productService.addProduct(product, imgPaths)) {

            try {
                response.sendRedirect("/FlowerCart/AdminView/ProductAddition.jsp?add=true");
            } catch (IOException ex) {
                Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
            }
        } else {
            try {
                response.sendRedirect("/FlowerCart/AdminView/ProductAddition.jsp?add=false");
            } catch (IOException ex) {
                Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    } catch (IllegalAccessException | InvocationTargetException ex) {
        Logger.getLogger(AddProductServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:com.javaeeeee.controllers.BookmarksController.java

/**
 * A method to edit a bookmark./*w w w .j a va 2 s  . com*/
 *
 * @param username
 * @param bookmarkId
 * @param json
 * @return ResponseEntity containing the patched bookmark, if found, and
 * status code.
 * @throws java.io.IOException
 * @throws java.lang.reflect.InvocationTargetException
 * @throws com.javaeeeee.exception.BookmarkNotFoundException
 * @throws java.lang.IllegalAccessException
 */
@RequestMapping(value = "/{bookmarkId}", method = RequestMethod.PUT)
public ResponseEntity<Bookmark> editBookmark(@PathVariable(value = "username") String username,
        @PathVariable(value = "bookmarkId") int bookmarkId, @RequestBody String json)
        throws IOException, BookmarkNotFoundException, IllegalAccessException, InvocationTargetException {

    Optional<Bookmark> optional = bookmarksRepository.findByIdAndUserUsername(bookmarkId, username);
    if (optional.isPresent()) {
        ObjectMapper mapper = new ObjectMapper();
        Map<String, String> changeMap = mapper.readValue(json, HashMap.class);
        Bookmark bookmark = optional.get();
        BeanUtils.populate(bookmark, changeMap);
        bookmark = bookmarksRepository.save(bookmark);
        return new ResponseEntity<>(bookmark, HttpStatus.OK);
    } else {
        throw new BookmarkNotFoundException("Bookmark not found id = " + bookmarkId);
    }

}