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

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

Introduction

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

Prototype

public static void setProperty(Object bean, String name, Object value)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException 

Source Link

Document

Set the value of the specified property of the specified bean, no matter which property reference format is used, with no type conversions.

For more details see PropertyUtilsBean.

Usage

From source file:test.openmobster.device.agent.frameworks.mobileObject.TestBeanUtils.java

public void testPropertySetting() throws Exception {
    Object pojo = Thread.currentThread().getContextClassLoader()
            .loadClass("test.openmobster.device.agent.frameworks.mobileObject.MockPOJO").newInstance();

    //Set Simple Property
    String simpleProperty = "value";
    PropertyUtils.setProperty(pojo, simpleProperty, "parent");

    //Set Nested Property
    String nestedProperty = "child.value";
    StringTokenizer st = new StringTokenizer(nestedProperty, ".");
    Object courObj = pojo;/*from w  w  w.j ava2s . c om*/
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (!st.hasMoreTokens()) {
            PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
            PropertyUtils.setNestedProperty(pojo, nestedProperty,
                    ConvertUtils.convert("child", metaData.getPropertyType()));
        } else {
            PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
            if (PropertyUtils.getProperty(courObj, token) == null) {
                Object nestedObj = metaData.getPropertyType().newInstance();
                PropertyUtils.setProperty(courObj, token, nestedObj);
                courObj = nestedObj;
            } else {
                courObj = PropertyUtils.getProperty(courObj, token);
            }
        }
    }

    //Set Nested Property non-string
    nestedProperty = "child.id";
    st = new StringTokenizer(nestedProperty, ".");
    courObj = pojo;
    while (st.hasMoreTokens()) {
        String token = st.nextToken();
        if (!st.hasMoreTokens()) {
            PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
            PropertyUtils.setNestedProperty(pojo, nestedProperty,
                    ConvertUtils.convert("123", metaData.getPropertyType()));
        } else {
            PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
            if (PropertyUtils.getProperty(courObj, token) == null) {
                Object nestedObj = metaData.getPropertyType().newInstance();
                PropertyUtils.setProperty(courObj, token, nestedObj);
                courObj = nestedObj;
            } else {
                courObj = PropertyUtils.getProperty(courObj, token);
            }
        }
    }

    //Set Indexed Property      
    //String indexedProperty = "childArray[0]";
    //st = new StringTokenizer(indexedProperty, ".");
    //courObj = pojo;
    //while(st.hasMoreTokens())
    //{
    //   String token = st.nextToken();                        
    //   if(!st.hasMoreTokens())
    //   {
    //      PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);
    //      PropertyUtils.setIndexedProperty(pojo, indexedProperty, ConvertUtils.convert("child://0", metaData.getPropertyType()));            
    //   }
    //   else
    //   {
    /*if(token.indexOf('[') != -1)
    {
       token = token.substring(0, token.indexOf('['));
    }*/

    //      PropertyDescriptor metaData = PropertyUtils.getPropertyDescriptor(courObj, token);            
    //      if(PropertyUtils.getProperty(courObj, token) == null)
    //      {
    //         Object nestedObj = metaData.getPropertyType().newInstance();
    //         PropertyUtils.setProperty(courObj, token, nestedObj);
    //         courObj = nestedObj;
    //      }
    //      else
    //      {
    //         courObj = PropertyUtils.getProperty(courObj, token);
    //      }
    //   }
    //}

    //Assert
    String[] childArray = ((MockPOJO) pojo).getChildArray();
    assertEquals("Value does not match", ((MockPOJO) pojo).getValue(), "parent");
    assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getValue(), "child");
    assertEquals("Value does not match", ((MockPOJO) pojo).getChild().getId(), 123);
    //assertEquals("Value does not match", childArray[0], "child://0");
}

From source file:us.mn.state.health.lims.analyte.action.AnalyteAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Analyte.
    // If there is a parameter present, we should bring up an existing
    // Analyte to edit.
    String id = request.getParameter(ID);

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    DynaActionForm dynaForm = (DynaActionForm) form;

    // initialize the form
    dynaForm.initialize(mapping);/*ww w.  ja  va 2  s  .  c  o  m*/

    Analyte analyte = new Analyte();

    if ((id != null) && (!"0".equals(id))) { // this is an existing
        // analyte

        analyte.setId(id);
        AnalyteDAO analyteDAO = new AnalyteDAOImpl();
        analyteDAO.getData(analyte);
        // initialize selectedAnalyteId
        if (analyte.getAnalyte() != null) {
            analyte.setSelectedAnalyteId(analyte.getAnalyte().getId());
        }
        isNew = false; // this is to set correct page title

        // do we need to enable next or previous?
        //bugzilla 1427 pass in name not id
        List analytes = analyteDAO.getNextAnalyteRecord(analyte.getAnalyteName());
        if (analytes.size() > 0) {
            // enable next button
            request.setAttribute(NEXT_DISABLED, "false");
        }
        //bugzilla 1427 pass in name not id
        analytes = analyteDAO.getPreviousAnalyteRecord(analyte.getAnalyteName());
        if (analytes.size() > 0) {
            // enable next button
            request.setAttribute(PREVIOUS_DISABLED, "false");
        }
        // end of logic to enable next or previous button
    } else { // this is a new analyte

        // default isActive to 'Y'
        analyte.setIsActive(YES);
        isNew = true; // this is to set correct page title
    }

    if (analyte.getId() != null && !analyte.getId().equals("0")) {
        request.setAttribute(ID, analyte.getId());
    }

    // populate form from valueholder
    PropertyUtils.copyProperties(form, analyte);

    AnalyteDAO analDAO = new AnalyteDAOImpl();

    List parentAnalytes = analDAO.getAllAnalytes();

    // set parentAnalyteName
    String parentAnalyteName = null;
    for (int i = 0; i < parentAnalytes.size(); i++) {
        Analyte parentAnalyte = (Analyte) parentAnalytes.get(i);
        if (parentAnalyte.getId().equals(analyte.getSelectedAnalyteId())) {
            parentAnalyteName = parentAnalyte.getAnalyteName();
        }
    }

    PropertyUtils.setProperty(form, "parentAnalytes", parentAnalytes);
    PropertyUtils.setProperty(form, "parentAnalyteName", parentAnalyteName);

    return mapping.findForward(forward);
}

From source file:us.mn.state.health.lims.analyte.action.AnalyteUpdateAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // The first job is to determine if we are coming to this action with an
    // ID parameter in the request. If there is no parameter, we are
    // creating a new Analyte.
    // If there is a parameter present, we should bring up an existing
    // Analyte to edit.

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "false");
    request.setAttribute(NEXT_DISABLED, "false");

    String id = request.getParameter(ID);

    if (StringUtil.isNullorNill(id) || "0".equals(id)) {
        isNew = true;/*from ww w  . j a v a2s  . com*/
    } else {
        isNew = false;
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    // server-side validation (validation.xml)
    ActionMessages errors = dynaForm.validate(mapping, request);
    try {
        errors = validateAll(request, errors, dynaForm);
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("AnalyteUpdateAction", "performAction()", e.toString());
        ActionError error = new ActionError("errors.ValidationException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
    }

    if (errors != null && errors.size() > 0) {
        // System.out.println("Server side validation errors "
        // + errors.toString());
        saveErrors(request, errors);
        // since we forward to jsp - not Action we don't need to repopulate
        // the lists here
        return mapping.findForward(FWD_FAIL);
    }

    String start = (String) request.getParameter("startingRecNo");
    String direction = (String) request.getParameter("direction");

    // System.out.println("This is ID from request " + id);
    Analyte analyte = new Analyte();
    //get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());
    analyte.setSysUserId(sysUserId);
    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    // String selectedAnalyteId = (String)
    // dynaForm.get("selectedAnalyteId");
    String parentAnalyteName = (String) dynaForm.get("parentAnalyteName");

    // System.out.println("This is selectedAnalyteId "
    // + dynaForm.get("selectedAnalyteId"));
    List anals = new ArrayList();
    if (dynaForm.get("parentAnalytes") != null) {
        anals = (List) dynaForm.get("parentAnalytes");
    } else {
        AnalyteDAO analDAO = new AnalyteDAOImpl();
        anals = analDAO.getAllAnalytes();
    }

    Analyte parentAnalyte = null;

    // get the right parentAnalyte to update analyte with
    for (int i = 0; i < anals.size(); i++) {
        Analyte o = (Analyte) anals.get(i);
        // if (o.getId().equals(selectedAnalyteId)) {
        if ((o != null) && (parentAnalyteName != null)) {
            if (o.getAnalyteName().equals(parentAnalyteName)) {
                parentAnalyte = o;
                break;
            }
        }
    }

    // populate valueholder from form
    PropertyUtils.copyProperties(analyte, dynaForm);

    analyte.setAnalyte(parentAnalyte);

    try {

        AnalyteDAO analyteDAO = new AnalyteDAOImpl();
        if (!isNew) {
            // UPDATE
            analyteDAO.updateData(analyte);
        } else {
            // INSERT
            analyteDAO.insertData(analyte);
        }
        tx.commit();
    } catch (LIMSRuntimeException lre) {
        //bugzilla 2154
        LogEvent.logError("AnalyteUpdateAction", "performAction()", lre.toString());
        tx.rollback();
        errors = new ActionMessages();
        ActionError error = null;
        //bugzilla 1482
        java.util.Locale locale = (java.util.Locale) request.getSession()
                .getAttribute("org.apache.struts.action.LOCALE");
        if (lre.getException() instanceof org.hibernate.StaleObjectStateException) {
            // how can I get popup instead of struts error at the top of
            // page?
            // ActionMessages errors = dynaForm.validate(mapping, request);
            error = new ActionError("errors.OptimisticLockException", null, null);

        } else {
            //bugzilla 1482
            if (lre.getException() instanceof LIMSDuplicateRecordException) {
                //bugzilla 2432
                String messageKey = "analyte.analyteNameOrLocalAbbreviation";
                String msg = ResourceLocator.getInstance().getMessageResources().getMessage(locale, messageKey);
                error = new ActionError("errors.DuplicateRecord.activate", msg, null);

            } else {
                error = new ActionError("errors.UpdateException", null, null);
            }
        }

        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        //bugzilla 1485: allow change and try updating again (enable save button)
        //request.setAttribute(ALLOW_EDITS_KEY, "false");
        // disable previous and next
        request.setAttribute(PREVIOUS_DISABLED, "true");
        request.setAttribute(NEXT_DISABLED, "true");
        forward = FWD_FAIL;
    } finally {
        HibernateUtil.closeSession();
    }
    if (forward.equals(FWD_FAIL))
        return mapping.findForward(forward);

    // initialize the form
    dynaForm.initialize(mapping);
    // repopulate the form from valueholder
    PropertyUtils.copyProperties(dynaForm, analyte);

    // need to repopulate in case of FWD_FAIL?
    PropertyUtils.setProperty(form, "parentAnalytes", anals);

    if ("true".equalsIgnoreCase(request.getParameter("close"))) {
        forward = FWD_CLOSE;
    }

    if (analyte.getId() != null && !analyte.getId().equals("0")) {
        request.setAttribute(ID, analyte.getId());
    }

    //bugzilla 1400
    if (isNew)
        forward = FWD_SUCCESS_INSERT;
    //bugzilla 1467 added direction for redirect to NextPreviousAction
    return getForward(mapping.findForward(forward), id, start, direction);

}

From source file:us.mn.state.health.lims.analyzer.action.ListPluginAction.java

@Override
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    BaseActionForm dynaForm = (BaseActionForm) form;
    dynaForm.initialize(mapping);//  w ww  .  ja va2s. co m

    List<String> pluginNames = PluginLoader.getCurrentPlugins();

    if (pluginNames.size() == 0) {
        pluginNames.add(StringUtil.getContextualMessageForKey("plugin.no.plugins"));
    }
    PropertyUtils.setProperty(dynaForm, "pluginList", pluginNames);

    return mapping.findForward(IActionConstants.FWD_SUCCESS);
}

From source file:us.mn.state.health.lims.analyzerimport.action.AnalyzerTestNameAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");
    request.setAttribute(PREVIOUS_DISABLED, "true");
    request.setAttribute(NEXT_DISABLED, "true");

    DynaActionForm dynaForm = (DynaActionForm) form;

    dynaForm.initialize(mapping);//from   w  ww . j  a v a 2 s  .  c om

    List<Analyzer> analyzerList = getAllAnalyzers();
    List<Test> testList = getAllTests();

    PropertyUtils.setProperty(form, "analyzerList", analyzerList);
    PropertyUtils.setProperty(form, "testList", testList);

    return mapping.findForward(forward);
}

From source file:us.mn.state.health.lims.analyzerresults.action.AnalyzerResultsAction.java

protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String forward = FWD_SUCCESS;

    request.getSession().setAttribute(SAVE_DISABLED, TRUE);

    String page = request.getParameter("page");
    setAnalyzerRequest(request.getParameter("type"));

    DynaActionForm dynaForm = (DynaActionForm) form;
    PropertyUtils.setProperty(dynaForm, "analyzerType", analyzer);

    AnalyzerResultsPaging paging = new AnalyzerResultsPaging();
    if (GenericValidator.isBlankOrNull(page)) {
        // get list of AnalyzerData from table based on analyzer type
        List<AnalyzerResults> analyzerResultsList = getAnalyzerResults();

        if (analyzerResultsList.isEmpty()) {
            PropertyUtils.setProperty(dynaForm, "resultList", new ArrayList<AnalyzerResultItem>());
            String msg = StringUtil.getMessageForKey("result.noResultsFound");
            PropertyUtils.setProperty(dynaForm, "notFoundMsg", msg);
            paging.setEmptyPageBean(request, dynaForm);

        } else {/*  ww  w  .  j a v a 2s  .  co m*/

            /*
             * The problem we are solving is that the accession numbers may
             * not be consecutive but we still want to maintain the order So
             * we will form the groups (by analyzer runs) by going in order
             * but if the accession number is in another group it will be
             * boosted to the first group
             */
            boolean missingTest = false;

            resolveMissingTests(analyzerResultsList);

            List<List<AnalyzerResultItem>> accessionGroupedResultsList = groupAnalyzerResults(
                    analyzerResultsList);

            List<AnalyzerResultItem> analyzerResultItemList = new ArrayList<AnalyzerResultItem>();

            int sampleGroupingNumber = 0;
            for (List<AnalyzerResultItem> group : accessionGroupedResultsList) {
                sampleGroupingNumber++;
                AnalyzerResultItem groupHeader = null;
                for (AnalyzerResultItem resultItem : group) {
                    if (groupHeader == null) {
                        groupHeader = resultItem;
                        setNonConformityStateForResultItem(resultItem);
                    }
                    resultItem.setSampleGroupingNumber(sampleGroupingNumber);

                    // There are two reasons there may not be a test id,
                    // 1. it could not be found due to missing mapping
                    // 2. it may not be looked for if the results are read
                    // only
                    // we only want to capture 1.
                    if (GenericValidator.isBlankOrNull(resultItem.getTestId()) && !resultItem.isReadOnly()) {
                        groupHeader.setGroupIsReadOnly(true);
                        missingTest = true;
                    } else if (resultItem.getIsControl()) {
                        groupHeader.setGroupIsReadOnly(true);
                    }

                    analyzerResultItemList.add(resultItem);
                }
            }

            PropertyUtils.setProperty(dynaForm, "missingTestMsg", new Boolean(missingTest));

            paging.setDatabaseResults(request, dynaForm, analyzerResultItemList);
        }
    } else {
        paging.page(request, dynaForm, page);
    }

    return mapping.findForward(forward);
}

From source file:us.mn.state.health.lims.analyzerresults.action.AnalyzerResultsPaging.java

public void setDatabaseResults(HttpServletRequest request, DynaActionForm dynaForm,
        List<AnalyzerResultItem> tests)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    paging.setDatabaseResults(request.getSession(), tests, pagingHelper);

    List<AnalyzerResultItem> resultPage = paging.getPage(1, request.getSession());
    if (resultPage != null) {
        PropertyUtils.setProperty(dynaForm, "resultList", resultPage);
        PropertyUtils.setProperty(dynaForm, "paging",
                paging.getPagingBeanWithSearchMapping(1, request.getSession()));
    }/*from w  w w  .  ja  v a2  s  . co m*/
}

From source file:us.mn.state.health.lims.analyzerresults.action.AnalyzerResultsPaging.java

@SuppressWarnings("unchecked")
public void page(HttpServletRequest request, DynaActionForm dynaForm, String newPage)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {

    request.getSession().setAttribute(IActionConstants.SAVE_DISABLED, IActionConstants.FALSE);
    List<AnalyzerResultItem> clientTests = (List<AnalyzerResultItem>) dynaForm.get("resultList");
    PagingBean bean = (PagingBean) dynaForm.get("paging");

    paging.updatePagedResults(request.getSession(), clientTests, bean, pagingHelper);

    int page = Integer.parseInt(newPage);

    List<AnalyzerResultItem> resultPage = paging.getPage(page, request.getSession());
    if (resultPage != null) {
        PropertyUtils.setProperty(dynaForm, "resultList", resultPage);
        PropertyUtils.setProperty(dynaForm, "paging",
                paging.getPagingBeanWithSearchMapping(page, request.getSession()));
    }/*from w w  w. j av  a  2s.c  om*/
}

From source file:us.mn.state.health.lims.analyzerresults.action.AnalyzerResultsPaging.java

public void setEmptyPageBean(HttpServletRequest request, DynaActionForm dynaForm)
        throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    PropertyUtils.setProperty(dynaForm, "paging",
            paging.getPagingBeanWithSearchMapping(0, request.getSession()));
}

From source file:us.mn.state.health.lims.audittrail.action.AuditTrailViewAction.java

@Override
protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    BaseActionForm dynaForm = (BaseActionForm) form;
    String accessionNumber = dynaForm.getString("accessionNumberSearch");
    dynaForm.initialize(mapping);/* w w  w.j  a  va  2s. c  om*/

    if (!GenericValidator.isBlankOrNull(accessionNumber)) {
        AuditTrailViewWorker worker = new AuditTrailViewWorker(accessionNumber);
        List<AuditTrailItem> items = worker.getAuditTrail();
        PropertyUtils.setProperty(dynaForm, "log", items);
        PropertyUtils.setProperty(dynaForm, "accessionNumber", accessionNumber);
        PropertyUtils.setProperty(dynaForm, "sampleOrderItems", worker.getSampleOrderSnapshot());
        PropertyUtils.setProperty(dynaForm, "patientProperties", worker.getPatientSnapshot());
    }

    return mapping.findForward(IActionConstants.FWD_SUCCESS);
}