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) throws BeansException 

Source Link

Document

Copy the property values of the given source bean into the target bean.

Usage

From source file:org.kuali.kfs.module.tem.service.impl.TravelerServiceImpl.java

/**
 *
 * @see org.kuali.kfs.module.tem.document.service.TravelDocumentService#copyTravelerDetailEmergencyContact(java.util.List, java.lang.String)
 *//*from   w  w  w. ja  v  a2  s .  c  om*/
@Override
public List<TravelerDetailEmergencyContact> copyTravelerDetailEmergencyContact(
        List<TravelerDetailEmergencyContact> emergencyContacts, String documentNumber) {
    List<TravelerDetailEmergencyContact> newEmergencyContacts = new ArrayList<TravelerDetailEmergencyContact>();
    if (emergencyContacts != null) {
        for (TravelerDetailEmergencyContact emergencyContact : emergencyContacts) {
            TravelerDetailEmergencyContact newEmergencyContact = new TravelerDetailEmergencyContact();
            BeanUtils.copyProperties(emergencyContact, newEmergencyContact);
            newEmergencyContact.setDocumentNumber(documentNumber);
            newEmergencyContact.setVersionNumber(new Long(1));
            newEmergencyContact.setObjectId(null);
            newEmergencyContact.setId(null);
            newEmergencyContacts.add(newEmergencyContact);
        }
    }
    return newEmergencyContacts;
}

From source file:org.kuali.kfs.module.tem.service.impl.TravelerServiceImpl.java

/**
 * @see org.kuali.kfs.module.tem.service.TravelerService#convertToTemProfileFromCustomer(org.kuali.kfs.integration.ar.AccountsReceivableCustomer)
 *///w ww. j  a v a2 s  .  c o m
@Override
public TemProfileFromCustomer convertToTemProfileFromCustomer(AccountsReceivableCustomer person) {
    TemProfileFromCustomer retval = new TemProfileFromCustomer();

    final AccountsReceivableCustomerAddress address = getAddressFor(person);

    BeanUtils.copyProperties(person, retval);
    BeanUtils.copyProperties(address, retval);

    return retval;
}

From source file:org.kuali.mobility.writer.controllers.WriterEditArticleController.java

/**
 *
 *//* w  w  w  . j  a  v a2  s. com*/
@RequestMapping(value = "/maintainArticle")
public String maintainArticle(HttpServletRequest request, @ModelAttribute("article") Article articleObj,
        @RequestParam(value = "uploadVideo", required = false) MultipartFile videoFile,
        @RequestParam(value = "uploadImage", required = false) MultipartFile imageFile,
        @RequestParam(value = "pageAction", required = true) int pageAction,
        @RequestParam(value = "topicId", required = true) long topicId,
        @RequestParam(value = "articleId", required = false) Long articleId,
        @RequestParam(value = "removeImage", required = false, defaultValue = "false") boolean removeImage,
        @RequestParam(value = "removeVideo", required = false, defaultValue = "false") boolean removeVideo,
        @PathVariable("instance") String instance, Model uiModel) {

    User user = (User) request.getSession().getAttribute(Constants.KME_USER_KEY);

    Article article = null;
    if (articleId != null) {
        article = this.service.getArticle(articleId);
    }

    /*
     * If an article for the submitted id does not exist we can submit that object.
     * If an article for the submitted id DOES exist, we need to get the latest copy
     * from the database, update the object, and persist
     */
    if (article != null) {
        /* Copy all the fields from the submitted article object to the one
         * we need to persist */
        Article original = this.service.getArticle(articleId);
        BeanUtils.copyProperties(articleObj, article);
        article.setId(original.getId());
        article.setVideo(original.getVideo());
        article.setImage(original.getImage());
        article.setVersionNumber(original.getVersionNumber());
    } else {
        article = articleObj;
    }

    /*
     * If no journalist name has been set yet, then this user
     * is the journalist.
     */
    if (article.getJournalist() == null) {
        article.setJournalist(user.getDisplayName() == null ? user.getLoginName() : user.getDisplayName());
        article.setJournalistId(user.getLoginName());
    }
    /*
     * if the user is the editor we have to set the editor field.
     */
    if (WriterPermissions.getEditorExpression(instance).evaluate(user)) {
        article.setEditorId(user.getLoginName());
    } else {
        article.setEditorId(null);
    }
    article.setTimestamp(new Date());
    article.setToolInstance(instance);

    int newState = pageAction;
    /*
     * If we are rejecting an article, we are first going to save the 
     * article in the current editor's list. The next page will complete
     * setting the status to rejected, to avoid rejected articles without
     * a reason when the user cancels the Article Rejection Screen.
     */
    if (pageAction == Article.STATUS_REJECTED) {
        newState = Article.STATUS_SAVED;
    }

    /**
     * If the article was submitted and saved, we need to preserve that state
     */
    if (newState == Article.STATUS_SAVED && article.getStatus() == Article.STATUS_SUBMITTED_SAVED) {
        article.setStatus(Article.STATUS_SUBMITTED_SAVED);
    } else {
        article.setStatus(newState);
    }
    Topic topic = service.getTopic(topicId);
    article.setTopic(topic);

    /* Flag if there was a problem saving the media, we do not want the user to loose changes to
     * the article if something went wrong saving the media */
    boolean mediaFailure = false;

    if (removeImage) {
        article = service.removeMedia(article, Media.MEDIA_TYPE_IMAGE);
    } else if (imageFile != null && !imageFile.isEmpty()) {
        Media image = service.uploadMediaData(imageFile, Media.MEDIA_TYPE_IMAGE);
        if (image != null) {
            article = service.updateMedia(article, image);
        } else {
            LOG.warn("There was an error saving the new image for the article");
            mediaFailure = true;
        }
    }

    if (removeVideo) {
        article = service.removeMedia(article, Media.MEDIA_TYPE_VIDEO);
    } else if (videoFile != null && !videoFile.isEmpty()) {
        Media video = service.uploadMediaData(videoFile, Media.MEDIA_TYPE_VIDEO);
        article = service.updateMedia(article, video);
    }

    article = service.maintainArticle(article);
    // After persisting the content of the article, we inform the user of the media problem
    if (mediaFailure) {
        uiModel.addAttribute("backURL", "/writer/" + instance + "/editArticle/" + article.getId());
        uiModel.addAttribute("errorMessage", "writer.errorUploadingMedia");
        uiModel.addAttribute("errorTitle", "writer.somethingWentWrong");
        return "error";
    }
    /*
     * Send notification for new article
     */
    if (pageAction == Article.STATUS_PUBLISHED) {
        publishService.publishArticle(article, user); // Async
    }

    if (pageAction == Article.STATUS_SAVED) {// save action
        return "redirect:/writer/" + instance + "/savedArticles";
    } else if (pageAction == Article.STATUS_PUBLISHED) {// publish action
        return "redirect:/writer/" + instance + "/viewArticle?articleId=" + article.getId();
    } else if (pageAction == Article.STATUS_REJECTED) {// publish action
        return "redirect:/writer/" + instance + "/rejectArticle?articleId=" + article.getId();
    }
    return "redirect:/writer/" + instance + "/admin";
}

From source file:org.kuali.student.cm.course.service.impl.CourseMaintainableImpl.java

@SuppressWarnings("deprecation")
@Override// w  w  w.  j a  va  2  s  .  com
protected boolean performAddLineValidation(ViewModel viewModel, Object newLine, String collectionId,
        String collectionPath) {
    boolean returnValue = super.performAddLineValidation(viewModel, newLine, collectionId, collectionPath);
    // if return value is false then something failed in the parent class so just return false
    if (!returnValue) {
        return false;
    }

    if (newLine instanceof CourseCreateUnitsContentOwner) {
        MaintenanceDocumentForm modelForm = (MaintenanceDocumentForm) viewModel;
        CourseInfoWrapper courseInfoWrapper = (CourseInfoWrapper) modelForm.getDocument()
                .getNewMaintainableObject().getDataObject();

        for (CourseCreateUnitsContentOwner unitsContentOwner : courseInfoWrapper.getUnitsContentOwner()) {
            if (StringUtils.isBlank(unitsContentOwner.getOrgId())) {
                return false;
            }
        }
    } else if (newLine instanceof LoCategoryInfo) {
        LoCategoryInfo loCategoryInfo = (LoCategoryInfo) newLine;

        boolean isCategoryAlreadyExist = false;

        if (StringUtils.isNotBlank(loCategoryInfo.getName())) {

            String categoryType = loCategoryInfo.getTypeKey();
            String categoryName = loCategoryInfo.getName();

            //If it's a new category, then user has to select the type. For the one selected from autosuggest,
            //name always include the type in the format "<name> - <type>". We need to split that to get the
            //name and type here
            if (StringUtils.isBlank(categoryType)) {
                categoryType = StringUtils.substringAfterLast(loCategoryInfo.getName(), "-").trim();
                categoryName = StringUtils.substringBeforeLast(loCategoryInfo.getName(), "-").trim();
            }

            //Check if Category is an existing one or a new.
            if (StringUtils.isNotBlank(categoryName)) {
                List<LoCategoryInfoWrapper> loCategoryInfoWrapper = searchForLoCategories(categoryName);
                if (loCategoryInfoWrapper != null && !loCategoryInfoWrapper.isEmpty()) {
                    //Check against the each existing category and its type
                    for (LoCategoryInfoWrapper loCategoryInfoWrap : loCategoryInfoWrapper) {
                        if (loCategoryInfoWrap.getName().equals(categoryName)
                                && loCategoryInfoWrap.getTypeName().equals(categoryType)) {
                            //get the complete category record
                            LoCategoryInfo origLoCat = (LoCategoryInfo) loCategoryInfoWrap;
                            BeanUtils.copyProperties(origLoCat, loCategoryInfo);
                            isCategoryAlreadyExist = true;
                            break;
                        }
                    }
                }

                if (!isCategoryAlreadyExist) {
                    //if category doesn't exist then create newly.
                    loCategoryInfo.setStateKey(CurriculumManagementConstants.STATE_KEY_ACTIVE);
                    loCategoryInfo.setLoRepositoryKey(
                            CurriculumManagementConstants.KUALI_LO_REPOSITORY_KEY_SINGLE_USE);
                    try {
                        LoCategoryInfo savedLoCat = getLearningObjectiveService().createLoCategory(
                                loCategoryInfo.getTypeKey(), loCategoryInfo,
                                ContextUtils.createDefaultContextInfo());
                        BeanUtils.copyProperties(savedLoCat, loCategoryInfo);
                    } catch (DataValidationErrorException e) {
                        LOG.error(
                                "An error occurred while trying to create a duplicate Learning Objective Category",
                                e);
                    } catch (Exception e) {
                        LOG.error("An error occurred while trying to create a new Learning Objective Category",
                                e);
                    }
                }

                try {
                    //Get the type info
                    TypeInfo typeInfo = getLearningObjectiveService().getLoCategoryType(
                            loCategoryInfo.getTypeKey(), ContextUtils.createDefaultContextInfo());
                    loCategoryInfo.setName((new StringBuilder().append(loCategoryInfo.getName()).append(" - ")
                            .append(typeInfo.getName()).toString()));
                } catch (Exception e) {
                    LOG.error("An error occurred while retrieving the LoCategoryType", e);
                }
            } else {
                return false;
            }
        } else {
            return false;
        }
    }
    return true;
}

From source file:org.kuali.student.cm.course.service.impl.CourseMaintainableImpl.java

protected void populateOutComesOnWrapper() {

    CourseInfoWrapper courseInfoWrapper = (CourseInfoWrapper) getDataObject();
    courseInfoWrapper.getCreditOptionWrappers().clear();

    for (ResultValuesGroupInfo rvg : courseInfoWrapper.getCourseInfo().getCreditOptions()) {

        ResultValuesGroupInfoWrapper rvgWrapper = new ResultValuesGroupInfoWrapper();
        BeanUtils.copyProperties(rvg, rvgWrapper);
        rvgWrapper.setResultValuesGroupInfo(rvg);

        if (StringUtils.equals(rvg.getTypeKey(), LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_MULTIPLE)) {

            StringBuilder resultValue = new StringBuilder("");
            List<String> resultValueList = new ArrayList<String>();

            for (String rvKey : rvg.getResultValueKeys()) {
                String value = StringUtils.strip(rvKey,
                        LrcServiceConstants.RESULT_VALUE_KEY_CREDIT_DEGREE_PREFIX);
                resultValueList.add(StringUtils.remove(value, ".0")); // This can be only be integer at ui.
            }/*from   w ww.j ava  2  s.c  o m*/

            // Sort the values to be displayed at ui
            Collections.sort(resultValueList);
            rvgWrapper.getUiHelper().setResultValue(StringUtils.join(resultValueList, ","));

        } else if (StringUtils.equals(rvg.getTypeKey(),
                LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_RANGE)) {

            String minValue = StringUtils.remove(rvg.getResultValueRange().getMinValue(), ".0"); // This can be only be integer at ui.
            String maxValue = StringUtils.remove(rvg.getResultValueRange().getMaxValue(), ".0"); // This can be only be integer at ui.

            rvgWrapper.getUiHelper().setResultValue(minValue + "-" + maxValue);
        } else if (StringUtils.equals(rvg.getTypeKey(),
                LrcServiceConstants.RESULT_VALUES_GROUP_TYPE_KEY_FIXED)) {
            rvgWrapper.getUiHelper()
                    .setResultValue(StringUtils.remove(rvg.getResultValueRange().getMinValue(), ".0"));
        }
        courseInfoWrapper.getCreditOptionWrappers().add(rvgWrapper);
    }

    Collections.sort(courseInfoWrapper.getCreditOptionWrappers(),
            new Comparator<ResultValuesGroupInfoWrapper>() {
                public int compare(ResultValuesGroupInfoWrapper a, ResultValuesGroupInfoWrapper b) {
                    if (a.getTypeKey() == null) {
                        return 1;
                    } else if (b.getTypeKey() == null) {
                        return -1;
                    }
                    return a.getTypeKey().compareToIgnoreCase(b.getTypeKey());
                }
            });

    initializeOutcome(courseInfoWrapper);

}

From source file:org.kuali.student.cm.course.service.impl.CourseMaintainableImpl.java

/**
 * This method creates <class>CourseJointInfoWrapper</class> instances from <class>CourseJointInfo</class> instance
 *//*  w  w  w  . j  ava2  s .c  o m*/
protected void populateJointCourseOnWrapper() {

    CourseInfoWrapper courseInfoWrapper = (CourseInfoWrapper) getDataObject();
    courseInfoWrapper.getCourseJointWrappers().clear();

    for (final CourseJointInfo jointInfo : courseInfoWrapper.getCourseInfo().getJoints()) {
        CourseJointInfoWrapper jointInfoWrapper = new CourseJointInfoWrapper();
        BeanUtils.copyProperties(jointInfo, jointInfoWrapper);
        jointInfoWrapper.setCourseCode(jointInfo.getSubjectArea() + jointInfo.getCourseNumberSuffix());
        courseInfoWrapper.getCourseJointWrappers().add(jointInfoWrapper);
    }
    if (courseInfoWrapper.getCourseJointWrappers().isEmpty()) {
        List<CourseJointInfoWrapper> courseJointInfoList = courseInfoWrapper.getCourseJointWrappers();
        courseJointInfoList.add(new CourseJointInfoWrapper());
        courseInfoWrapper.setCourseJointWrappers(courseJointInfoList);
    }

}

From source file:org.kuali.student.r2.common.validator.DefaultValidatorImpl.java

public void validateField(List<ValidationResultInfo> results, FieldDefinition field,
        ObjectStructureHierarchy objStruct, ConstraintDataProvider dataProvider, Stack<String> elementStack,
        Object rootData, ObjectStructureDefinition rootObjectStructure, ContextInfo contextInfo) {

    Object value = dataProvider.getValue(field.getName());

    // Handle null values in field
    if (value == null || "".equals(value.toString().trim())) {
        processConstraint(results, field, objStruct, value, dataProvider, elementStack, rootData,
                rootObjectStructure, contextInfo);
        return; // no need to do further processing
    }//from  w  w w  .j a  v a 2  s. co m

    /*
     * For complex object structures only the following constraints apply 1. TypeStateCase 2. MinOccurs 3. MaxOccurs
     */
    if (DataType.COMPLEX.equals(field.getDataType())) {
        ObjectStructureHierarchy nestedObjStruct = new ObjectStructureHierarchy();
        nestedObjStruct.setParentObjectStructureHierarchy(objStruct);

        if (null != field.getDataObjectStructure()) {
            nestedObjStruct.setObjectStructure(field.getDataObjectStructure());
        }

        elementStack.push(field.getName());
        // beanPathStack.push(field.isDynamic()?"attributes("+field.getName()+")":field.getName());

        if (value instanceof Collection) {

            String xPathForCollection = getElementXpath(elementStack) + "/*";

            int i = 0;
            for (Object o : (Collection<?>) value) {
                elementStack.push(Integer.toString(i));
                // beanPathStack.push(!beanPathStack.isEmpty()?beanPathStack.pop():""+"["+i+"]");
                processNestedObjectStructure(results, o, nestedObjStruct, field, elementStack, rootData,
                        rootObjectStructure, dataProvider, contextInfo);
                // beanPathStack.pop();
                // beanPathStack.push(field.isDynamic()?"attributes("+field.getName()+")":field.getName());
                elementStack.pop();
                i++;
            }
            if (field.getMinOccurs() != null && field.getMinOccurs() > ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPathForCollection, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.minOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }

            Integer maxOccurs = tryParse(field.getMaxOccurs());
            if (maxOccurs != null && maxOccurs < ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPathForCollection, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.maxOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }
        } else {
            if (null != value) {
                processNestedObjectStructure(results, value, nestedObjStruct, field, elementStack, rootData,
                        rootObjectStructure, dataProvider, contextInfo);
            } else {
                if (field.getMinOccurs() != null && field.getMinOccurs() > 0) {
                    ValidationResultInfo val = new ValidationResultInfo(getElementXpath(elementStack), value);
                    if (field.getLabelKey() != null) {
                        val.setError(getMessage(field.getLabelKey(), contextInfo));
                    } else {
                        val.setError(getMessage("validation.required", contextInfo));
                    }
                    results.add(val);
                }
            }
        }

        // beanPathStack.pop();
        elementStack.pop();

    } else { // If non complex data type

        if (value instanceof Collection) {

            if (((Collection<?>) value).isEmpty()) {
                processConstraint(results, field, objStruct, "", dataProvider, elementStack, rootData,
                        rootObjectStructure, contextInfo);
            }

            int i = 0;
            for (Object o : (Collection<?>) value) {
                // This is tricky, change the field name to the index in the elementStack(this is for lists of non
                // complex types)
                elementStack.push(field.getName());
                FieldDefinition tempField = new FieldDefinition();
                BeanUtils.copyProperties(field, tempField);
                tempField.setName(Integer.toBinaryString(i));
                processConstraint(results, tempField, objStruct, o, dataProvider, elementStack, rootData,
                        rootObjectStructure, contextInfo);
                elementStack.pop();
                i++;
            }

            String xPath = getElementXpath(elementStack) + "/" + field.getName() + "/*";
            if (field.getMinOccurs() != null && field.getMinOccurs() > ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPath, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.minOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }

            Integer maxOccurs = tryParse(field.getMaxOccurs());
            if (maxOccurs != null && maxOccurs < ((Collection<?>) value).size()) {
                ValidationResultInfo valRes = new ValidationResultInfo(xPath, value);
                valRes.setError(MessageUtils.interpolate(getMessage("validation.maxOccurs", contextInfo),
                        toMap(field)));
                results.add(valRes);
            }
        } else {
            processConstraint(results, field, objStruct, value, dataProvider, elementStack, rootData,
                    rootObjectStructure, contextInfo);
        }

    }
}

From source file:org.nebula.console.service.InstanceService.java

private GetEventsResponse getEvents(NebulaMgmtClient nebulaMgmtClient, String instanceId, int currentPage,
        int pageSize) throws Exception {

    GetEventsResponse response = nebulaServiceFacade.getEvents(nebulaMgmtClient, instanceId, currentPage,
            pageSize);//from w  w  w.  j  a va  2 s  .  c  o  m

    if (response.getEvents().size() == 0) {
        GetHistoryEventsResponse getHistoryEventsResponse = nebulaServiceFacade
                .getHistoryEvents(nebulaMgmtClient, instanceId, currentPage, pageSize);
        BeanUtils.copyProperties(getHistoryEventsResponse, response);
    }

    return response;
}

From source file:org.okj.im.SimpleWebQQClient.java

/**
 * @see org.okj.im.WebQQClient#loadFriend(java.lang.String)
 *///from   w  ww.  ja  va  2 s. co  m
@Override
public Member loadFriend(String account) {
    ActionContext context = new ActionContext(BizCode.QQ_LOAD_FRIEND);
    Member sample = new Member();
    sample.getAccount().setAccount(account);
    context.addAttribute(ActionContextKeys.MEMBER_KEY, sample);
    boolean success = executeActions(context);
    if (success) {
        Member friend = (Member) context.getAttribute(ActionContextKeys.FRIEND_KEY);
        //ActionContext,?bean?
        Member nFriend = new Member();
        BeanUtils.copyProperties(friend, nFriend);
        return nFriend;
    }
    return null;
}

From source file:org.okj.im.SimpleWebQQClient.java

/** 
 * @see org.okj.im.WebQQClient#loadFriendSignature(java.lang.String)
 *///w  w  w . ja va 2  s.  c o m
@Override
public Member loadFriendSignature(String account) {
    ActionContext context = new ActionContext(BizCode.QQ_LOAD_FRIEND_SIGNATURE);
    Member sample = new Member();
    sample.getAccount().setAccount(account);
    context.addAttribute(ActionContextKeys.MEMBER_KEY, sample);
    boolean success = executeActions(context);
    if (success) {
        Member friend = (Member) context.getAttribute(ActionContextKeys.FRIEND_KEY);
        //ActionContext,?bean?
        Member nFriend = new Member();
        BeanUtils.copyProperties(friend, nFriend);
        return nFriend;
    }
    return null;
}