Example usage for org.springframework.beans BeanUtils copyProperties

List of usage examples for org.springframework.beans BeanUtils copyProperties

Introduction

In this page you can find the example usage for org.springframework.beans BeanUtils copyProperties.

Prototype

public static void copyProperties(Object source, Object target, String... ignoreProperties)
        throws BeansException 

Source Link

Document

Copy the property values of the given source bean into the given target bean, ignoring the given "ignoreProperties".

Usage

From source file:org.ownchan.server.app.security.ContextUserImpl.java

public ContextUserImpl(DbUser dbUser) {
    Assert.notNull(dbUser, "a persisted user is required");
    BeanUtils.copyProperties(dbUser, this, UserTemplate.class);
    this.lastDbLoadTime = new Date();

    this.authorities = new HashSet<>();
    if (CollectionUtils.isNotEmpty(dbUser.getLinkedRoles())) {
        dbUser.getLinkedRoles().stream().forEach(role -> {
            this.authorities.add(new ContextUserAuthorityImpl(role));
            if (CollectionUtils.isNotEmpty(role.getLinkedPrivileges())) {
                role.getLinkedPrivileges().stream().map(ContextUserAuthorityImpl::new)
                        .forEach(this.authorities::add);
            }/*from  w  w  w  . j  ava 2  s.  c  o m*/
        });
    }
}

From source file:org.sakaiproject.messagebundle.impl.MessageBundleServiceImpl.java

/**
 * internal work for responding to a save or update request.  This method will add new bundles data
 * if it doesn't exist, otherwise updates the data preserving any current value if its been modified.
 * This approach allows for upgrades to automatically detect and persist new keys, as well as updating
 * any default values that flow in from an upgrade.
 * @param baseName/*from  w  w  w .jav  a  2  s  .co m*/
 * @param moduleName
 * @param newBundle
 * @param loc
 */
protected void saveOrUpdateInternal(String baseName, String moduleName, Map<String, String> newBundle,
        Locale loc) {
    String keyName = getIndexKeyName(baseName, moduleName, loc.toString());
    if (indexedList.contains(keyName)) {
        if (logger.isDebugEnabled())
            logger.debug("skip saveOrUpdate() as its already happened once for :" + keyName);
        return;
    }

    Set<Entry<String, String>> entrySet = newBundle.entrySet();
    Iterator<Entry<String, String>> entries = entrySet.iterator();

    while (entries.hasNext()) {
        Entry<String, String> entry = entries.next();
        String key = entry.getKey();
        MessageBundleProperty mbp = new MessageBundleProperty();
        mbp.setBaseName(baseName);
        mbp.setModuleName(moduleName);
        mbp.setLocale(loc.toString());
        mbp.setPropertyName(key);
        MessageBundleProperty existingMbp = getProperty(mbp);
        if (existingMbp != null) {
            //don"t update id or value, we don't want to loose that data
            BeanUtils.copyProperties(mbp, existingMbp, new String[] { "id", "defaultValue", "value" });
            if (logger.isDebugEnabled())
                logger.debug("updating message bundle data for : "
                        + getIndexKeyName(mbp.getBaseName(), mbp.getModuleName(), mbp.getLocale()));
            updateMessageBundleProperty(existingMbp);
        } else {
            mbp.setDefaultValue(entry.getValue());
            if (logger.isDebugEnabled())
                logger.debug("adding message bundle data for : "
                        + getIndexKeyName(mbp.getBaseName(), mbp.getModuleName(), mbp.getLocale()));
            updateMessageBundleProperty(mbp);
        }
    }
    indexedList.add(getIndexKeyName(baseName, moduleName, loc.toString()));
}

From source file:org.sakaiproject.messagebundle.impl.MessageBundleServiceImpl.java

public int importProperties(List<MessageBundleProperty> properties) {
    int rows = 0;
    for (MessageBundleProperty property : properties) {
        MessageBundleProperty loadedMbp = getProperty(property);
        if (loadedMbp != null) {
            BeanUtils.copyProperties(property, loadedMbp, new String[] { "id" });
            updateMessageBundleProperty(loadedMbp);
        } else {//from  www.  j  av a 2 s  .  com
            updateMessageBundleProperty(property);
        }

        rows++;
    }
    return rows;
}

From source file:org.talend.dataprep.conversions.BeanConversionService.java

/**
 * The {@link BeanUtils#copyProperties(java.lang.Object, java.lang.Object)} method does <b>NOT</b> check if parametrized type
 * are compatible when copying values, this helper method performs this additional check and ignore copy of those values.
 *
 * @param source The source bean (from which values are read).
 * @param converted The target bean (to which values are written).
 *///from  w  w w  .  j a  v a  2  s.c  o m
private static void copyBean(Object source, Object converted) {
    // Find property(ies) to ignore during copy.
    List<String> discardedProperties = new LinkedList<>();
    final BeanWrapper sourceBean = new BeanWrapperImpl(source);
    final BeanWrapper targetBean = new BeanWrapperImpl(converted);
    final PropertyDescriptor[] sourceProperties = sourceBean.getPropertyDescriptors();
    for (PropertyDescriptor sourceProperty : sourceProperties) {
        if (targetBean.isWritableProperty(sourceProperty.getName())) {
            final PropertyDescriptor targetProperty = targetBean
                    .getPropertyDescriptor(sourceProperty.getName());
            final Class<?> sourcePropertyType = sourceProperty.getPropertyType();
            final Class<?> targetPropertyType = targetProperty.getPropertyType();
            final Method readMethod = sourceProperty.getReadMethod();
            if (readMethod != null) {
                final Type sourceReturnType = readMethod.getGenericReturnType();
                final Method targetPropertyWriteMethod = targetProperty.getWriteMethod();
                if (targetPropertyWriteMethod != null) {
                    final Type targetReturnType = targetPropertyWriteMethod.getParameters()[0]
                            .getParameterizedType();
                    boolean valid = Object.class.equals(targetPropertyType)
                            || sourcePropertyType.equals(targetPropertyType)
                                    && sourceReturnType.equals(targetReturnType);
                    if (!valid) {
                        discardedProperties.add(sourceProperty.getName());
                    }
                }
            } else {
                discardedProperties.add(sourceProperty.getName());
            }
        }
    }

    // Perform copy
    BeanUtils.copyProperties(source, converted,
            discardedProperties.toArray(new String[discardedProperties.size()]));
}

From source file:org.waterforpeople.mapping.app.web.rest.CascadeNodeRestService.java

@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
@ResponseBody//from w  ww  . jav  a  2  s  .c  om
public Map<String, Object> saveExistingCascadeNode(@RequestBody CascadeNodePayload payLoad) {
    final CascadeNodeDto cascadeNodeDto = payLoad.getCascade_node();
    final Map<String, Object> response = new HashMap<String, Object>();
    CascadeNodeDto dto = null;
    RestStatusDto statusDto = new RestStatusDto();
    statusDto.setStatus("failed");

    // if the POST data contains a valid cascadeNodeDto, continue.
    // Otherwise, server will respond with 400 Bad Request
    if (cascadeNodeDto != null) {
        Long keyId = cascadeNodeDto.getKeyId();
        CascadeNode cr;

        // if the cascadeNodeDto has a key, try to get the CascadeNode.
        if (keyId != null) {
            cr = cascadeNodeDao.getByKey(keyId);
            // if we find the user, update it's properties
            if (cr != null) {
                // copy the properties, except the createdDateTime property,
                // because it is set in the Dao.
                BeanUtils.copyProperties(cascadeNodeDto, cr, new String[] { "createdDateTime" });
                cr = cascadeNodeDao.save(cr);
                dto = new CascadeNodeDto();
                BeanUtils.copyProperties(cr, dto);
                if (cr.getKey() != null) {
                    dto.setKeyId(cr.getKey().getId());
                }
                statusDto.setStatus("ok");
            }
        }
    }
    response.put("meta", statusDto);
    response.put("cascade_node", dto);
    return response;
}

From source file:org.waterforpeople.mapping.app.web.rest.UserRestService.java

@RequestMapping(method = RequestMethod.GET, value = "")
@ResponseBody/* w  w w. java  2  s.c o  m*/
public Map<String, List<UserDto>> listUsers(
        @RequestParam(value = "currUser", defaultValue = "") String currUser) {
    final Map<String, List<UserDto>> response = new HashMap<String, List<UserDto>>();
    List<UserDto> results = new ArrayList<UserDto>();

    // TODO check if this part works
    if ("true".equals(currUser)) {
        com.google.appengine.api.users.UserService userService = UserServiceFactory.getUserService();
        com.google.appengine.api.users.User currentUser = userService.getCurrentUser();
        if (currentUser != null) {
            UserDto dto = new UserDto();
            dto.setEmailAddress(currentUser.getEmail());
            dto.setUserName(currentUser.getFederatedIdentity());
            results.add(dto);
        }

    } else {
        List<User> users = userDao.list(Constants.ALL_RESULTS);
        if (users != null) {
            for (User u : users) {
                if ("0".equals(u.getPermissionList()) || Boolean.TRUE.equals(u.isSuperAdmin())) {
                    continue;
                }
                UserDto dto = new UserDto();
                BeanUtils.copyProperties(u, dto, new String[] { "config" });
                if (u.getKey() != null) {
                    dto.setKeyId(u.getKey().getId());
                }
                results.add(dto);
            }
        }
    }

    response.put("users", results);
    return response;
}

From source file:org.waterforpeople.mapping.app.web.rest.UserRestService.java

@RequestMapping(method = RequestMethod.GET, value = "/{id}")
@ResponseBody/* ww w . j a v a2 s  .  com*/
public Map<String, UserDto> findUser(@PathVariable("id") Long id) {
    final Map<String, UserDto> response = new HashMap<String, UserDto>();
    User u = userDao.getByKey(id);
    UserDto dto = null;
    if (u != null) {
        dto = new UserDto();
        BeanUtils.copyProperties(u, dto, new String[] { "config" });
        if (u.getKey() != null) {
            dto.setKeyId(u.getKey().getId());
        }
    }
    response.put("user", dto);
    return response;

}

From source file:org.waterforpeople.mapping.app.web.rest.UserRestService.java

@RequestMapping(method = RequestMethod.PUT, value = "/{id}")
@ResponseBody// w w w .ja v  a 2s  .c om
public Map<String, Object> saveExistingUser(@RequestBody UserPayload payLoad) {
    final UserDto userDto = payLoad.getUser();
    final Map<String, Object> response = new HashMap<String, Object>();
    UserDto dto = null;

    RestStatusDto statusDto = new RestStatusDto();
    statusDto.setStatus("failed");

    // if the POST data contains a valid userDto, continue.
    // Otherwise, server will respond with 400 Bad Request
    if (userDto != null) {
        Long keyId = userDto.getKeyId();
        User u;

        // if the userDto has a key, try to get the user.
        if (keyId != null) {
            u = userDao.getByKey(keyId);
            // if we find the user, update it's properties
            if (u != null) {
                // copy the properties, except the createdDateTime property,
                // because it is set in the Dao.
                BeanUtils.copyProperties(userDto, u, new String[] { "createdDateTime", "config" });

                if (u.getPermissionList().equals(String.valueOf(AppRole.SUPER_ADMIN.getLevel()))) {
                    u.setPermissionList(String.valueOf(AppRole.USER.getLevel()));
                }

                u = userDao.save(u);
                dto = new UserDto();
                BeanUtils.copyProperties(u, dto, new String[] { "config" });
                if (u.getKey() != null) {
                    dto.setKeyId(u.getKey().getId());
                }
                statusDto.setStatus("ok");
            }
        }
    }
    response.put("meta", statusDto);
    response.put("user", dto);
    return response;
}

From source file:org.waterforpeople.mapping.app.web.rest.UserRestService.java

@RequestMapping(method = RequestMethod.POST, value = "")
@ResponseBody/*from w w w. j  ava  2  s .c  o  m*/
public Map<String, Object> saveNewUser(@RequestBody UserPayload payLoad) {
    final UserDto userDto = payLoad.getUser();
    final Map<String, Object> response = new HashMap<String, Object>();
    UserDto dto = null;

    RestStatusDto statusDto = new RestStatusDto();
    statusDto.setStatus("failed");

    // if the POST data contains a valid userDto, continue.
    // Otherwise, server will respond with 400 Bad Request
    if (userDto != null) {
        User u = new User();

        // copy the properties, except the createdDateTime property, because
        // it is set in the Dao.
        BeanUtils.copyProperties(userDto, u, new String[] { "createdDateTime", "config" });

        if (u.getPermissionList().equals(String.valueOf(AppRole.SUPER_ADMIN.getLevel()))) {
            u.setPermissionList(String.valueOf(AppRole.USER.getLevel()));
        }

        u = userDao.save(u);

        dto = new UserDto();
        BeanUtils.copyProperties(u, dto, new String[] { "config" });
        if (u.getKey() != null) {
            dto.setKeyId(u.getKey().getId());
        }
        statusDto.setStatus("ok");
    }

    response.put("meta", statusDto);
    response.put("user", dto);
    return response;
}