Example usage for org.apache.commons.beanutils PropertyUtils getMappedProperty

List of usage examples for org.apache.commons.beanutils PropertyUtils getMappedProperty

Introduction

In this page you can find the example usage for org.apache.commons.beanutils PropertyUtils getMappedProperty.

Prototype

public static Object getMappedProperty(Object bean, String name)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Return the value of the specified mapped property of the specified bean, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:com.rolex.explore.beanutils.service.BeanUtilsSpecificService.java

public void exploreBeanUtil() {

    SampleBean bean = new SampleBean();

    String property1 = "name";

    String property2 = "currentAddress.city";

    String property3 = "previousAddresses[0].city";

    String property4 = "previousAddresses[3].city";

    String property5 = "vehicleLicenseModel(R60)";

    Place place1 = new Place("Sentosa", "Singapore");
    Place place2 = new Place("Colombo", "Sri Lanka");
    List<Place> places = new ArrayList<Place>();
    places.add(place1);//from   ww  w .ja va 2s  .  com
    places.add(place2);

    String property6 = "yearlyPlacesVisited(2000)";

    String property7 = "placesVisited";

    String property8 = "placesVisited[0]";

    TourismAward award = new TourismAward("World Award Committee", "USA");

    String property9 = "yearlyPlacesVisited(2000)[0].tourismAwards[0]";

    try {
        PropertyUtils.setSimpleProperty(bean, property1, "Rolex Rolex");
        String value1 = (String) PropertyUtils.getSimpleProperty(bean, property1);
        System.out.println("###Reverse1:   " + value1);

        PropertyUtils.setNestedProperty(bean, property2, "Hoffman Estates");
        String value2 = (String) PropertyUtils.getNestedProperty(bean, property2);
        System.out.println("###Reverse2:   " + value2);

        PropertyUtils.setNestedProperty(bean, property3, "Schaumburg");
        String value3 = (String) PropertyUtils.getNestedProperty(bean, property3);
        System.out.println("###Reverse3:   " + value3);

        PropertyUtils.setNestedProperty(bean, property4, "Des Plaines");
        String value4 = (String) PropertyUtils.getNestedProperty(bean, property4);
        System.out.println("###Reverse4:   " + value4);

        Address[] arrayValue1 = (Address[]) PropertyUtils.getSimpleProperty(bean, "previousAddresses");
        System.out.println("###ReverseArray:   " + Arrays.toString(arrayValue1));

        PropertyUtils.setMappedProperty(bean, property5, "Sonata");
        String value5 = (String) PropertyUtils.getMappedProperty(bean, property5);
        System.out.println("###Reverse5:   " + value5);

        PropertyUtils.setMappedProperty(bean, property6, places);
        List<Place> value6 = (List<Place>) PropertyUtils.getMappedProperty(bean, property6);
        System.out.println("###Reverse6:   " + value6.get(0));

        PropertyUtils.setSimpleProperty(bean, property7, places);
        List<Place> value7 = (List<Place>) PropertyUtils.getSimpleProperty(bean, property7);
        System.out.println("###Reverse7:   " + value7.get(0));

        PropertyUtils.setIndexedProperty(bean, property8, place2);
        Place value8 = (Place) PropertyUtils.getIndexedProperty(bean, property8);
        System.out.println("###Reverse8:   " + value8);

        PropertyUtils.setNestedProperty(bean, property9, award);
        TourismAward value9 = (TourismAward) PropertyUtils.getNestedProperty(bean, property9);
        System.out.println("###Reverse8:   " + value8);

    } catch (IllegalAccessException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvocationTargetException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}

From source file:org.displaytag.util.LookupUtil.java

/**
 * <p>/* w w  w  .jav a2 s .c  o  m*/
 * Returns the value of a property in the given bean.
 * </p>
 * <p>
 * This method is a modificated version from commons-beanutils PropertyUtils.getProperty(). It allows intermediate
 * nulls in expression without throwing exception (es. it doesn't throw an exception for the property
 * <code>object.date.time</code> if <code>date</code> is null)
 * </p>
 * @param bean javabean
 * @param name name of the property to read from the javabean
 * @return Object
 * @throws ObjectLookupException for errors while retrieving a property in the bean
 */
public static Object getBeanProperty(Object bean, String name) throws ObjectLookupException {

    if (log.isDebugEnabled()) {
        log.debug("getProperty [" + name + "] on bean " + bean);
    }

    if (bean == null) {
        throw new IllegalArgumentException("No bean specified");
    }
    if (name == null) {
        throw new IllegalArgumentException("No name specified");
    }

    Object evalBean = bean;
    String evalName = name;

    try {

        int indexOfINDEXEDDELIM;
        int indexOfMAPPEDDELIM;
        int indexOfMAPPEDDELIM2;
        int indexOfNESTEDDELIM;
        while (true) {

            indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM);
            indexOfMAPPEDDELIM = evalName.indexOf(PropertyUtils.MAPPED_DELIM);
            indexOfMAPPEDDELIM2 = evalName.indexOf(PropertyUtils.MAPPED_DELIM2);
            if (indexOfMAPPEDDELIM2 >= 0 && indexOfMAPPEDDELIM >= 0
                    && (indexOfNESTEDDELIM < 0 || indexOfNESTEDDELIM > indexOfMAPPEDDELIM)) {
                indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM, indexOfMAPPEDDELIM2);
            } else {
                indexOfNESTEDDELIM = evalName.indexOf(PropertyUtils.NESTED_DELIM);
            }
            if (indexOfNESTEDDELIM < 0) {
                break;
            }
            String next = evalName.substring(0, indexOfNESTEDDELIM);
            indexOfINDEXEDDELIM = next.indexOf(PropertyUtils.INDEXED_DELIM);
            indexOfMAPPEDDELIM = next.indexOf(PropertyUtils.MAPPED_DELIM);
            if (evalBean instanceof Map) {
                evalBean = ((Map) evalBean).get(next);
            } else if (indexOfMAPPEDDELIM >= 0) {

                evalBean = PropertyUtils.getMappedProperty(evalBean, next);

            } else if (indexOfINDEXEDDELIM >= 0) {
                evalBean = PropertyUtils.getIndexedProperty(evalBean, next);
            } else {
                evalBean = PropertyUtils.getSimpleProperty(evalBean, next);
            }

            if (evalBean == null) {
                log.debug("Null property value for '" + evalName.substring(0, indexOfNESTEDDELIM) + "'");
                return null;
            }
            evalName = evalName.substring(indexOfNESTEDDELIM + 1);

        }

        indexOfINDEXEDDELIM = evalName.indexOf(PropertyUtils.INDEXED_DELIM);
        indexOfMAPPEDDELIM = evalName.indexOf(PropertyUtils.MAPPED_DELIM);

        if (evalBean instanceof Map) {
            evalBean = ((Map) evalBean).get(evalName);
        } else if (indexOfMAPPEDDELIM >= 0) {
            evalBean = PropertyUtils.getMappedProperty(evalBean, evalName);
        } else if (indexOfINDEXEDDELIM >= 0) {
            evalBean = PropertyUtils.getIndexedProperty(evalBean, evalName);
        } else {
            evalBean = PropertyUtils.getSimpleProperty(evalBean, evalName);
        }
    } catch (IllegalAccessException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    }

    catch (InvocationTargetException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    } catch (NoSuchMethodException e) {
        throw new ObjectLookupException(LookupUtil.class, evalBean, evalName, e);
    }

    return evalBean;

}

From source file:org.itracker.web.actions.project.CreateIssueAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    ActionMessages errors = new ActionMessages();

    if (!isTokenValid(request)) {
        log.info("execute: Invalid request token while creating issue.");
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.transaction"));
        saveErrors(request, errors);/*from  w w  w. ja  v  a2  s  .c  o  m*/
        log.info("execute: return to edit-issue");
        saveToken(request);

        EditIssueActionUtil.setupCreateIssue(request);
        return mapping.findForward("createissue");

    }
    resetToken(request);

    try {
        IssueService issueService = ServletContextUtils.getItrackerServices().getIssueService();
        NotificationService notificationService = ServletContextUtils.getItrackerServices()
                .getNotificationService();
        ProjectService projectService = ServletContextUtils.getItrackerServices().getProjectService();

        HttpSession session = request.getSession(true);
        User currUser = (User) session.getAttribute(Constants.USER_KEY);
        Map<Integer, Set<PermissionType>> userPermissionsMap = RequestHelper.getUserPermissions(session);
        Locale locale = getLocale(request);
        Integer currUserId = currUser.getId();

        IssueForm issueForm = (IssueForm) form;

        Integer creator = currUserId;

        Project project = null;
        Integer projectId = issueForm.getProjectId();

        if (projectId == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidproject"));
        } else {
            project = projectService.getProject(projectId);
        }

        if (errors.isEmpty() && project == null) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.invalidproject"));
        } else if (errors.isEmpty() && project.getStatus() != Status.ACTIVE) {
            errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.projectlocked"));
        } else if (!UserUtilities.hasPermission(userPermissionsMap, projectId, PermissionType.ISSUE_CREATE)) {
            return mapping.findForward("unauthorized");
        } else {
            issueForm.invokeProjectScripts(project, WorkflowUtilities.EVENT_FIELD_ONPRESUBMIT, errors);

            Issue issue = new Issue();
            issue.setDescription(issueForm.getDescription());
            issue.setSeverity(issueForm.getSeverity());
            issue.setStatus(IssueUtilities.STATUS_NEW);
            issue.setResolution("");

            IssueHistory issueHistory = new IssueHistory(issue, currUser, issueForm.getHistory(),
                    IssueUtilities.HISTORY_STATUS_AVAILABLE);
            issueHistory.setCreateDate(new Date());
            issue.getHistory().add(issueHistory);

            // creating issues as another user

            if (UserUtilities.hasPermission(userPermissionsMap, projectId,
                    PermissionType.ISSUE_CREATE_OTHERS)) {
                creator = null != issueForm.getCreatorId() ? issueForm.getCreatorId() : currUserId;
                if (log.isDebugEnabled()) {
                    log.debug("New issue creator set to " + creator + ". Issue created by " + currUserId);
                }
            }
            // create the issue in the database
            ActionMessages msg = AttachmentUtilities.validate(issueForm.getAttachment(),
                    ServletContextUtils.getItrackerServices());

            if (!msg.isEmpty()) {
                log.info("execute: tried to create issue with invalid attachemnt: " + msg);
                errors.add(msg);
                saveErrors(request, errors);
                EditIssueActionUtil.setupCreateIssue(request);
                return mapping.findForward("createissue");
            }

            if (log.isDebugEnabled()) {
                log.debug("execute: creating new issue..");
            }

            issue = issueService.createIssue(issue, projectId, creator, currUserId);

            if (log.isDebugEnabled()) {
                log.debug("execute: issue created: " + issue);
            }

            if (issue != null) {
                if (!ProjectUtilities.hasOption(ProjectUtilities.OPTION_NO_ATTACHMENTS, project.getOptions())) {
                    msg = new ActionMessages();
                    issue = issueForm.addAttachment(issue, project, currUser,
                            ServletContextUtils.getItrackerServices(), msg);

                    if (!msg.isEmpty()) {
                        errors.add(msg);
                    }

                }

                Integer newOwner = issueForm.getOwnerId();

                if (newOwner != null && newOwner.intValue() >= 0) {
                    if (UserUtilities.hasPermission(userPermissionsMap, PermissionType.ISSUE_ASSIGN_OTHERS)
                            || (UserUtilities.hasPermission(userPermissionsMap,
                                    PermissionType.ISSUE_ASSIGN_SELF) && currUserId.equals(newOwner))) {
                        issueService.assignIssue(issue.getId(), newOwner, currUserId);
                    }
                }

                // TODO this is absolutely complex, unreadable code. why do it, what does it do, can we keep it simple?
                // it seems to set issueCustomField (issueFields), you might be able to refactor this into its own method (hiding in a method ;) )
                List<IssueField> issueFields = new ArrayList<IssueField>();
                Map<String, String> customFields = issueForm.getCustomFields();

                if (customFields != null && customFields.size() > 0) {
                    List<IssueField> issueFieldsVector = new ArrayList<IssueField>();
                    ResourceBundle bundle = ITrackerResources.getBundle(locale);

                    for (Iterator<String> iter = customFields.keySet().iterator(); iter.hasNext();) {
                        try {
                            Integer fieldId = Integer.valueOf(iter.next());
                            CustomField field = IssueUtilities.getCustomField(fieldId);
                            String fieldValue = (String) PropertyUtils.getMappedProperty(form,
                                    "customFields(" + fieldId + ")");

                            if (fieldValue != null && fieldValue.trim().length() != 0) {
                                IssueField issueField = new IssueField(issue, field);
                                issueField.setValue(fieldValue, bundle);
                                issueFieldsVector.add(issueField);
                            }
                        } catch (Exception e) {
                            log.error("execute: failed to assign issue", e);
                        }
                    }
                    issueFields = issueFieldsVector;
                }
                issueService.setIssueFields(issue.getId(), issueFields);

                HashSet<Integer> components = new HashSet<>();
                Integer[] componentIds = issueForm.getComponents();

                if (componentIds != null) {
                    Collections.addAll(components, componentIds);
                    issueService.setIssueComponents(issue.getId(), components, creator);
                }
                HashSet<Integer> versions = new HashSet<>();
                Integer[] versionIds = issueForm.getVersions();

                if (versionIds != null) {
                    Collections.addAll(versions, versionIds);
                    issueService.setIssueVersions(issue.getId(), versions, creator);
                }

                try {
                    Integer relatedIssueId = issueForm.getRelatedIssueId();
                    IssueRelation.Type relationType = issueForm.getRelationType();

                    if (relatedIssueId != null && relatedIssueId > 0 && relationType != null
                            && relationType.getCode() > 0) {
                        Issue relatedIssue = issueService.getIssue(relatedIssueId);

                        if (relatedIssue == null) {
                            log.debug("Unknown relation issue, relation not created.");
                        } else if (relatedIssue.getProject() == null
                                || !IssueUtilities.canEditIssue(relatedIssue, currUserId, userPermissionsMap)) {
                            log.info("User not authorized to add issue relation from issue " + issue.getId()
                                    + " to issue " + relatedIssueId);
                        } else if (IssueUtilities.hasIssueRelation(issue, relatedIssueId)) {
                            log.debug("Issue " + issue.getId() + " is already related to issue "
                                    + relatedIssueId + ", relation ot created.");
                        } else {
                            if (!issueService.addIssueRelation(issue.getId(), relatedIssueId, relationType,
                                    currUser.getId())) {
                                log.info("Error adding issue relation from issue " + issue.getId()
                                        + " to issue " + relatedIssueId);
                            }
                        }
                    }
                } catch (RuntimeException e) {
                    log.warn("execute: Exception adding new issue relation.", e);
                    errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
                    saveErrors(request, errors);
                    EditIssueActionUtil.setupCreateIssue(request);
                    return mapping.findForward("createissue");
                }

                notificationService.sendNotification(issue, Type.CREATED, getBaseURL(request));
            } else {

                errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
                saveErrors(request, errors);
                return mapping.findForward("createissue");
            }
            session.removeAttribute(Constants.PROJECT_KEY);

            issueForm.invokeProjectScripts(project, WorkflowUtilities.EVENT_FIELD_ONPOSTSUBMIT, errors);

            if (errors.isEmpty()) {
                return getReturnForward(issue, project, issueForm, mapping);
            }
            saveErrors(request, errors);
            EditIssueActionUtil.setupCreateIssue(request);
            return mapping.findForward("createissue");

        }
    } catch (RuntimeException e) {
        log.error("Exception processing form data", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    } catch (WorkflowException e) {
        log.error("Exception processing form data", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    } catch (ProjectException e) {
        log.error("Exception processing form data", e);
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("itracker.web.error.system"));
    }

    if (!errors.isEmpty()) {
        saveErrors(request, errors);
    }
    return mapping.findForward("createissue");
}