Example usage for java.lang NumberFormatException toString

List of usage examples for java.lang NumberFormatException toString

Introduction

In this page you can find the example usage for java.lang NumberFormatException toString.

Prototype

public String toString() 

Source Link

Document

Returns a short description of this throwable.

Usage

From source file:com.bonsai.wallet32.WalletService.java

public void startBackgroundTimeout() {

    // Cancel any pre-existing timeout.
    cancelBackgroundTimeout();/*  ww  w  .ja v  a2s .co m*/

    Runnable task = new Runnable() {
        public void run() {
            mLogger.info("background timeout");
            mApp.doExit();
        }
    };

    String delaystr = mPrefs.getString(SettingsActivity.KEY_BACKGROUND_TIMEOUT, "600");
    long delay;
    try {
        delay = Long.parseLong(delaystr);
    } catch (NumberFormatException ex) {
        throw new RuntimeException(ex.toString()); // Shouldn't happen.
    }

    if (delay != -1) {
        mBackgroundTimeout = mTimeoutWorker.schedule(task, delay, TimeUnit.SECONDS);

        mLogger.info(String.format("background timeout scheduled in %d seconds", delay));
    }
}

From source file:info.alni.comete.android.Comete.java

public void reconnect(View view) {
    try {/*from   w  ww . j  av a2s .  com*/
        mConnectingDialog = ProgressDialog.show(Comete.this, "", "Connecting. Please wait...", true);

        Thread t = new Thread(new ConnectTask(getConnectionPrefs().getString("ipAddress", ""),
                Integer.parseInt(getConnectionPrefs().getString("port", "")),
                getConnectionPrefs().getInt("simType", 0)));
        t.start();
    } catch (NumberFormatException e) {
        showMsg(Comete.this, e.toString());
        e.printStackTrace();
    }
}

From source file:info.alni.comete.android.Comete.java

private AlertDialog createConnectDialog() {
    final View ll = getLayoutInflater().inflate(R.layout.connect_dialog, null);
    final EditText etIpAddress = (EditText) ll.findViewById(R.id.ipAddress);
    final EditText etPort = (EditText) ll.findViewById(R.id.port);
    final Spinner sSimType = (Spinner) ll.findViewById(R.id.sim_type);
    etIpAddress.setText(getConnectionPrefs().getString("ipAddress", ""));
    etPort.setText(getConnectionPrefs().getString("port", ""));
    return new AlertDialog.Builder(this).setTitle("Enter host IP and port ").setView(ll)
            .setPositiveButton("Connect", new DialogInterface.OnClickListener() {

                @Override/*  w  w w  .j a v  a  2s  .  co  m*/
                public void onClick(DialogInterface dialog, int which) {
                    String ipAddress = etIpAddress.getText().toString();
                    String port = etPort.getText().toString();
                    int simType = sSimType.getSelectedItemPosition();
                    if (StringUtils.validateIPAddress(ipAddress) && StringUtils.validatePort(port)) {
                        Editor editor = getConnectionPrefs().edit();
                        editor.putString("ipAddress", ipAddress);
                        editor.putString("port", port);
                        editor.putInt("simType", simType);
                        editor.commit();

                        try {
                            mConnectingDialog = ProgressDialog.show(Comete.this, "",
                                    "Connecting. Please wait...", true);
                            //                              Comete.this.mIpAddress = ipAddress;
                            //                              Comete.this.mPort = Integer.parseInt(port);
                            Thread t = new Thread(new ConnectTask(ipAddress, Integer.parseInt(port), simType));

                            t.start();
                        } catch (NumberFormatException e) {
                            showMsg(Comete.this, e.toString());
                            e.printStackTrace();
                        }
                    }
                }
            }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();

                }
            }).create();
}

From source file:us.mn.state.health.lims.sample.action.HumanSampleTwoPopulateHashMapFromDE1Action.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 Sample.
    // If there is a parameter present, we should bring up an existing
    // Sample to edit.

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

    String id = request.getParameter(ID);

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

    BaseActionForm dynaForm = (BaseActionForm) form;

    // first get the accessionNumber and whether we are on blank page or not
    String accessionNumber = (String) dynaForm.get("accessionNumber");
    //bugzilla 2154
    LogEvent.logDebug("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()",
            "accessionNumber coming in: " + accessionNumber);
    String start = (String) request.getParameter("startingRecNo");

    String typeOfSample = (String) dynaForm.get("typeOfSampleDesc");
    String sourceOfSample = (String) dynaForm.get("sourceOfSampleDesc");

    List typeOfSamples = new ArrayList();
    List sourceOfSamples = new ArrayList();

    if (dynaForm.get("typeOfSamples") != null) {
        typeOfSamples = (List) dynaForm.get("typeOfSamples");
    } else {
        TypeOfSampleDAO typeOfSampleDAO = new TypeOfSampleDAOImpl();
        typeOfSamples = typeOfSampleDAO.getAllTypeOfSamples();
    }
    if (dynaForm.get("sourceOfSamples") != null) {
        sourceOfSamples = (List) dynaForm.get("sourceOfSamples");
    } else {
        SourceOfSampleDAO sourceOfSampleDAO = new SourceOfSampleDAOImpl();
        sourceOfSamples = sourceOfSampleDAO.getAllSourceOfSamples();
    }

    HashMap humanSampleOneMap = new HashMap();
    if (dynaForm.get("humanSampleOneMap") != null) {
        humanSampleOneMap = (HashMap) dynaForm.get("humanSampleOneMap");
    }

    String projectIdOrName = (String) dynaForm.get("projectIdOrName");
    String project2IdOrName = (String) dynaForm.get("project2IdOrName");

    String projectNameOrId = (String) dynaForm.get("projectNameOrId");
    String project2NameOrId = (String) dynaForm.get("project2NameOrId");

    String projectId = null;
    String project2Id = null;
    if (projectIdOrName != null && projectNameOrId != null) {
        try {
            Integer i = Integer.valueOf(projectIdOrName);
            projectId = projectIdOrName;

        } catch (NumberFormatException nfe) {
            //bugzilla 2154
            LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", nfe.toString());
            projectId = projectNameOrId;
        }

    }

    if (project2IdOrName != null && project2NameOrId != null) {
        try {
            Integer i = Integer.valueOf(project2IdOrName);
            project2Id = project2IdOrName;

        } catch (NumberFormatException nfe) {
            //bugzilla 2154
            LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", nfe.toString());
            project2Id = project2NameOrId;
        }

    }

    //bugzilla 2154
    LogEvent.logDebug("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()",
            "ProjectId is: " + projectId + " Project2Id is: " + project2Id);

    // set current date for validation of dates
    Date today = Calendar.getInstance().getTime();
    Locale locale = (Locale) request.getSession().getAttribute("org.apache.struts.action.LOCALE");
    String dateAsText = DateUtil.formatDateAsText(today, locale);

    Patient patient = new Patient();
    Person person = new Person();
    Provider provider = new Provider();
    Person providerPerson = new Person();
    Sample sample = new Sample();
    SampleHuman sampleHuman = new SampleHuman();
    SampleOrganization sampleOrganization = new SampleOrganization();
    List sampleProjects = new ArrayList();
    List updatedSampleProjects = new ArrayList();
    SampleItem sampleItem = new SampleItem();
    // TODO need to populate this with tests entered in HSE I
    List analyses = new ArrayList();

    // tests are not handled in HSE II
    /*
     * String stringOfTestIds = (String) dynaForm.get("selectedTestIds");
     * 
     * String[] listOfTestIds = stringOfTestIds.split(SystemConfiguration
     * .getInstance().getDefaultIdSeparator(), -1);
     * 
     * List analyses = new ArrayList(); for (int i = 0; i <
     * listOfTestIds.length; i++) { if
     * (!StringUtil.isNullorNill(listOfTestIds[i])) { Analysis analysis =
     * new Analysis(); analysis.setTestId(listOfTestIds[i]); // TODO: need
     * to populate this with actual data!!!
     * analysis.setAnalysisType("TEST"); analyses.add(analysis); } }
     */

    ActionMessages errors = null;

    // validate on server-side sample accession number

    try {
        errors = new ActionMessages();
        errors = validateAccessionNumber(request, errors, dynaForm);
        // System.out.println("Just validated accessionNumber");
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", e.toString());
        ActionError error = new ActionError("errors.ValidationException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
    }
    // System.out.println("This is errors after validation of accn Number "
    // + errors);
    if (errors != null && errors.size() > 0) {
        saveErrors(request, errors);
        // initialize the form but retain the invalid accessionNumber
        dynaForm.initialize(mapping);
        dynaForm.set("accessionNumber", accessionNumber);

        // repopulate lists
        PropertyUtils.setProperty(dynaForm, "typeOfSamples", typeOfSamples);
        PropertyUtils.setProperty(dynaForm, "sourceOfSamples", sourceOfSamples);
        request.setAttribute(ALLOW_EDITS_KEY, "false");

        return mapping.findForward(FWD_FAIL);
    }
    // System.out.println("Now try to get data for accession number ");
    try {

        PatientDAO patientDAO = new PatientDAOImpl();
        PersonDAO personDAO = new PersonDAOImpl();
        ProviderDAO providerDAO = new ProviderDAOImpl();
        SampleDAO sampleDAO = new SampleDAOImpl();
        SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
        SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
        SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();

        sample.setAccessionNumber(accessionNumber);
        sampleDAO.getSampleByAccessionNumber(sample);
        if (!StringUtil.isNullorNill(sample.getId())) {
            sampleHuman.setSampleId(sample.getId());
            sampleHumanDAO.getDataBySample(sampleHuman);
            sampleOrganization.setSampleId(sample.getId());
            sampleOrganizationDAO.getDataBySample(sampleOrganization);
            // bugzilla 1773 need to store sample not sampleId for use in
            // sorting
            sampleItem.setSample(sample);
            sampleItemDAO.getDataBySample(sampleItem);
            patient.setId(sampleHuman.getPatientId());
            patientDAO.getData(patient);
            person = patient.getPerson();
            personDAO.getData(person);

            provider.setId(sampleHuman.getProviderId());
            providerDAO.getData(provider);
            providerPerson = provider.getPerson();
            personDAO.getData(providerPerson);
            //bugzilla 2227
            analyses = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

            humanSampleOneMap = populateHumanSampleOneMap(patient, person, provider, providerPerson, sample,
                    sampleHuman, sampleOrganization, sampleItem, analyses);

        }

    } catch (LIMSRuntimeException lre) {
        // if error then forward to fail and don't update to blank page
        // = false
        //bugzilla 2154
        LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()", lre.toString());
        errors = new ActionMessages();
        ActionError error = null;
        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);
            //bugzilla 2154
            LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()",
                    "errors.OptimisticLockException");
        } else {
            error = new ActionError("errors.GetException", null, null);
            //bugzilla 2154
            LogEvent.logError("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()",
                    "errors.GetException");
        }
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        return mapping.findForward(FWD_FAIL);

    }

    // initialize the form
    dynaForm.initialize(mapping);

    // set lastupdated fields
    dynaForm.set("lastupdated", sample.getLastupdated());
    dynaForm.set("personLastupdated", person.getLastupdated());
    dynaForm.set("patientLastupdated", patient.getLastupdated());
    dynaForm.set("providerPersonLastupdated", providerPerson.getLastupdated());
    dynaForm.set("providerLastupdated", provider.getLastupdated());
    dynaForm.set("sampleItemLastupdated", sampleItem.getLastupdated());
    dynaForm.set("sampleHumanLastupdated", sampleHuman.getLastupdated());
    dynaForm.set("sampleOrganizationLastupdated", sampleOrganization.getLastupdated());

    if (updatedSampleProjects != null && updatedSampleProjects.size() > 0) {
        if (updatedSampleProjects.size() == 1) {
            SampleProject sp = (SampleProject) updatedSampleProjects.get(0);
            dynaForm.set("sampleProject1Lastupdated", sp.getLastupdated());
            // bugzilla 1857 deprecated stuff
            //System.out.println("This is sp ts "
            //      + StringUtil.formatDateAsText(sp.getLastupdated(),
            //            SystemConfiguration.getInstance()
            //                  .getDefaultLocale()));
        }
        if (updatedSampleProjects.size() == 2) {
            SampleProject sp2 = (SampleProject) updatedSampleProjects.get(1);
            dynaForm.set("sampleProject2Lastupdated", sp2.getLastupdated());
            // bugzilla 1857 deprecated stuff
            //System.out.println("This is sp2 ts "
            //      + StringUtil.formatDateAsText(sp2.getLastupdated(),
            //            SystemConfiguration.getInstance()
            //                  .getDefaultLocale()));
        }
    }

    if (dynaForm.get("sampleProject1Lastupdated") == null) {
        PropertyUtils.setProperty(form, "sampleProject1Lastupdated", new Timestamp(System.currentTimeMillis()));
    }
    if (dynaForm.get("sampleProject2Lastupdated") == null) {
        PropertyUtils.setProperty(form, "sampleProject2Lastupdated", new Timestamp(System.currentTimeMillis()));
    }

    PropertyUtils.setProperty(dynaForm, "currentDate", dateAsText);
    PropertyUtils.setProperty(dynaForm, "accessionNumber", sample.getAccessionNumber());
    // set receivedDate
    PropertyUtils.setProperty(dynaForm, "receivedDateForDisplay", (String) sample.getReceivedDateForDisplay());

    PropertyUtils.setProperty(dynaForm, "typeOfSamples", typeOfSamples);
    PropertyUtils.setProperty(dynaForm, "sourceOfSamples", sourceOfSamples);
    PropertyUtils.setProperty(dynaForm, "humanSampleOneMap", humanSampleOneMap);

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

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

    }

    if (forward.equals(FWD_SUCCESS)) {
        request.setAttribute("menuDefinition", "default");
    }

    //bugzilla 2154
    LogEvent.logDebug("HumanSampleTwoPopulateHashMapFromDE1Action", "performAction()",
            "forwarding to: " + forward);

    //pdf - get accession number List
    if (SystemConfiguration.getInstance().getEnabledSamplePdf().equals(YES)) {
        String status = SystemConfiguration.getInstance().getSampleStatusEntry1Complete(); //status = 2
        String humanDomain = SystemConfiguration.getInstance().getHumanDomain();
        UserTestSectionDAO userTestSectionDAO = new UserTestSectionDAOImpl();
        List accessionNumberListTwo = userTestSectionDAO.getSamplePdfList(request, locale, status, humanDomain);
        PropertyUtils.setProperty(form, "accessionNumberListTwo", accessionNumberListTwo);
    }

    // return getForward(mapping.findForward(forward), id, start);
    return mapping.findForward(forward);

}

From source file:org.moqui.impl.service.ServiceDefinition.java

private boolean validateParameterSingle(MNode valNode, String parameterName, Object pv,
        ExecutionContextImpl eci) {/*ww w.  j av a 2  s. co m*/
    // should never be null (caller checks) but check just in case
    if (pv == null)
        return true;

    String validateName = valNode.getName();
    if ("val-or".equals(validateName)) {
        boolean anyPass = false;
        for (MNode child : valNode.getChildren())
            if (validateParameterSingle(child, parameterName, pv, eci))
                anyPass = true;
        return anyPass;
    } else if ("val-and".equals(validateName)) {
        boolean allPass = true;
        for (MNode child : valNode.getChildren())
            if (!validateParameterSingle(child, parameterName, pv, eci))
                allPass = false;
        return allPass;
    } else if ("val-not".equals(validateName)) {
        boolean allPass = true;
        for (MNode child : valNode.getChildren())
            if (!validateParameterSingle(child, parameterName, pv, eci))
                allPass = false;
        return !allPass;
    } else if ("matches".equals(validateName)) {
        if (!(pv instanceof CharSequence)) {
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand(
                            "Value entered (${pv}) is not a string, cannot do matches validation.", "", map),
                    null);
            return false;
        }

        String pvString = pv.toString();
        String regexp = valNode.attribute("regexp");
        if (regexp != null && !regexp.isEmpty() && !pvString.matches(regexp)) {
            // a message attribute should always be there, but just in case we'll have a default
            final String message = valNode.attribute("message");
            Map<String, Object> map = new HashMap<>(2);
            map.put("pv", pv);
            map.put("regexp", regexp);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource()
                            .expand(message != null && !message.isEmpty() ? message
                                    : "Value entered (${pv}) did not match expression: ${regexp}", "", map),
                    null);
            return false;
        }

        return true;
    } else if ("number-range".equals(validateName)) {
        BigDecimal bdVal = new BigDecimal(pv.toString());
        String minStr = valNode.attribute("min");
        if (minStr != null && !minStr.isEmpty()) {
            BigDecimal min = new BigDecimal(minStr);
            if ("false".equals(valNode.attribute("min-include-equals"))) {
                if (bdVal.compareTo(min) <= 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("min", min);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is less than or equal to ${min} must be greater than.",
                                    "", map),
                            null);
                    return false;
                }
            } else {
                if (bdVal.compareTo(min) < 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("min", min);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is less than ${min} and must be greater than or equal to.",
                                    "", map),
                            null);
                    return false;
                }
            }
        }

        String maxStr = valNode.attribute("max");
        if (maxStr != null && !maxStr.isEmpty()) {
            BigDecimal max = new BigDecimal(maxStr);
            if ("true".equals(valNode.attribute("max-include-equals"))) {
                if (bdVal.compareTo(max) > 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("max", max);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is greater than ${max} and must be less than or equal to.",
                                    "", map),
                            null);
                    return false;
                }

            } else {
                if (bdVal.compareTo(max) >= 0) {
                    Map<String, Object> map = new HashMap<>(2);
                    map.put("pv", pv);
                    map.put("max", max);
                    eci.getMessage().addValidationError(null, parameterName, serviceName,
                            eci.getResource().expand(
                                    "Value entered (${pv}) is greater than or equal to ${max} and must be less than.",
                                    "", map),
                            null);
                    return false;
                }
            }
        }

        return true;
    } else if ("number-integer".equals(validateName)) {
        try {
            new BigInteger(pv.toString());
        } catch (NumberFormatException e) {
            if (logger.isTraceEnabled())
                logger.trace(
                        "Adding error message for NumberFormatException for BigInteger parse: " + e.toString());
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value [${pv}] is not a whole (integer) number.", "", map), null);
            return false;
        }

        return true;
    } else if ("number-decimal".equals(validateName)) {
        try {
            new BigDecimal(pv.toString());
        } catch (NumberFormatException e) {
            if (logger.isTraceEnabled())
                logger.trace(
                        "Adding error message for NumberFormatException for BigDecimal parse: " + e.toString());
            Map<String, Object> map = new HashMap<>(1);
            map.put("pv", pv);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value [${pv}] is not a decimal number.", "", map), null);
            return false;
        }

        return true;
    } else if ("text-length".equals(validateName)) {
        String str = pv.toString();
        String minStr = valNode.attribute("min");
        if (minStr != null && !minStr.isEmpty()) {
            int min = Integer.parseInt(minStr);
            if (str.length() < min) {
                Map<String, Object> map = new HashMap<>(3);
                map.put("pv", pv);
                map.put("str", str);
                map.put("minStr", minStr);
                eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand(
                        "Value entered (${pv}), length ${str.length()}, is shorter than ${minStr} characters.",
                        "", map), null);
                return false;
            }

        }

        String maxStr = valNode.attribute("max");
        if (maxStr != null && !maxStr.isEmpty()) {
            int max = Integer.parseInt(maxStr);
            if (str.length() > max) {
                Map<String, Object> map = new HashMap<>(3);
                map.put("pv", pv);
                map.put("str", str);
                map.put("maxStr", maxStr);
                eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource().expand(
                        "Value entered (${pv}), length ${str.length()}, is longer than ${maxStr} characters.",
                        "", map), null);
                return false;
            }
        }

        return true;
    } else if ("text-email".equals(validateName)) {
        String str = pv.toString();
        if (!emailValidator.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value entered (${str}) is not a valid email address.", "", map),
                    null);
            return false;
        }

        return true;
    } else if ("text-url".equals(validateName)) {
        String str = pv.toString();
        if (!urlValidator.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName,
                    eci.getResource().expand("Value entered (${str}) is not a valid URL.", "", map), null);
            return false;
        }

        return true;
    } else if ("text-letters".equals(validateName)) {
        String str = pv.toString();
        for (char c : str.toCharArray()) {
            if (!Character.isLetter(c)) {
                Map<String, String> map = new HashMap<>(1);
                map.put("str", str);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${str}) must have only letters.", "", map),
                        null);
                return false;
            }
        }

        return true;
    } else if ("text-digits".equals(validateName)) {
        String str = pv.toString();
        for (char c : str.toCharArray()) {
            if (!Character.isDigit(c)) {
                Map<String, String> map = new HashMap<>(1);
                map.put("str", str);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value [${str}] must have only digits.", "", map), null);
                return false;
            }
        }

        return true;
    } else if ("time-range".equals(validateName)) {
        Calendar cal;
        String format = valNode.attribute("format");
        if (pv instanceof CharSequence) {
            cal = eci.getL10n().parseDateTime(pv.toString(), format);
        } else {
            // try letting groovy convert it
            cal = Calendar.getInstance();
            // TODO: not sure if this will work: ((pv as java.util.Date).getTime())
            cal.setTimeInMillis((DefaultGroovyMethods.asType(pv, Date.class)).getTime());
        }

        String after = valNode.attribute("after");
        if (after != null && !after.isEmpty()) {
            // handle after date/time/date-time depending on type of parameter, support "now" too
            Calendar compareCal;
            if ("now".equals(after)) {
                compareCal = Calendar.getInstance();
                compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime());
            } else {
                compareCal = eci.getL10n().parseDateTime(after, format);
            }
            if (cal != null && !cal.after(compareCal)) {
                Map<String, Object> map = new HashMap<>(2);
                map.put("pv", pv);
                map.put("after", after);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${pv}) is before ${after}.", "", map), null);
                return false;
            }
        }

        String before = valNode.attribute("before");
        if (before != null && !before.isEmpty()) {
            // handle after date/time/date-time depending on type of parameter, support "now" too
            Calendar compareCal;
            if ("now".equals(before)) {
                compareCal = Calendar.getInstance();
                compareCal.setTimeInMillis(eci.getUser().getNowTimestamp().getTime());
            } else {
                compareCal = eci.getL10n().parseDateTime(before, format);
            }
            if (cal != null && !cal.before(compareCal)) {
                Map<String, Object> map = new HashMap<>(1);
                map.put("pv", pv);
                eci.getMessage().addValidationError(null, parameterName, serviceName,
                        eci.getResource().expand("Value entered (${pv}) is after ${before}.", "", map), null);
                return false;
            }
        }

        return true;
    } else if ("credit-card".equals(validateName)) {
        long creditCardTypes = 0;
        String types = valNode.attribute("types");
        if (types != null && !types.isEmpty()) {
            for (String cts : types.split(","))
                creditCardTypes += creditCardTypeMap.get(cts.trim());
        } else {
            creditCardTypes = allCreditCards;
        }

        CreditCardValidator ccv = new CreditCardValidator(creditCardTypes);
        String str = pv.toString();
        if (!ccv.isValid(str)) {
            Map<String, String> map = new HashMap<>(1);
            map.put("str", str);
            eci.getMessage().addValidationError(null, parameterName, serviceName, eci.getResource()
                    .expand("Value entered (${str}) is not a valid credit card number.", "", map), null);
            return false;
        }

        return true;
    }
    // shouldn't get here, but just in case
    return true;
}

From source file:org.ohmage.request.survey.annotation.PromptResponseAnnotationReadRequest.java

/**
 * Creates a new survey annotation creation request.
 * //from   w  ww.  j a  va  2 s. c  o m
 * @param httpRequest The HttpServletRequest with the parameters for this
 *                  request.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 */
public PromptResponseAnnotationReadRequest(HttpServletRequest httpRequest)
        throws IOException, InvalidRequestException {
    super(httpRequest, null, TokenLocation.PARAMETER, null);

    LOGGER.info("Creating a prompt response annotation read request.");

    UUID tSurveyId = null;
    String tPromptId = null;
    String tRepeatableSetId = null;
    Integer tRepeatableSetIteration = null;

    if (!isFailed()) {
        try {
            Map<String, String[]> parameters = getParameters();

            // Validate the survey ID
            String[] t = parameters.get(InputKeys.SURVEY_ID);
            if (t == null || t.length != 1) {
                setFailed(ErrorCode.SURVEY_INVALID_SURVEY_ID,
                        "survey_id is missing or there is more than one.");
                throw new ValidationException("survey_id is missing or there is more than one.");
            } else {
                tSurveyId = SurveyResponseValidators.validateSurveyResponseId(t[0]);

                if (tSurveyId == null) {
                    setFailed(ErrorCode.SURVEY_INVALID_SURVEY_ID, "The survey ID is invalid.");
                    throw new ValidationException("The survey ID is invalid.");
                }
            }

            // Validate the prompt ID
            t = parameters.get(InputKeys.PROMPT_ID);
            if (t == null || t.length != 1) {
                setFailed(ErrorCode.SURVEY_INVALID_PROMPT_ID,
                        "prompt_id is missing or there is more than one.");
                throw new ValidationException("prompt_id is missing or there is more than one.");
            } else {

                if (StringUtils.isEmptyOrWhitespaceOnly(t[0])) {
                    setFailed(ErrorCode.SURVEY_INVALID_PROMPT_ID, "The prompt ID is invalid.");
                    throw new ValidationException("The prompt ID is invalid.");
                }

                // Just grab the only item in the set
                tPromptId = t[0];
            }

            // Validate the optional repeatable set ID
            t = parameters.get(InputKeys.REPEATABLE_SET_ID);
            if (t != null) {

                if (t.length != 1) {
                    setFailed(ErrorCode.SURVEY_INVALID_REPEATABLE_SET_ID,
                            "there is more than one repeatable set ID.");
                    throw new ValidationException("there is more than one repeatable set ID.");
                }

                if (StringUtils.isEmptyOrWhitespaceOnly(t[0])) {
                    tRepeatableSetId = null;
                } else {
                    tRepeatableSetId = t[0];
                }

            } else {

                tRepeatableSetId = null;

            }

            // Validate the optional repeatable set iteration
            // If a repeatable set id is present, an iteration is required and vice versa
            t = parameters.get(InputKeys.REPEATABLE_SET_ITERATION);
            if (t != null) {

                if (t.length != 1) {
                    setFailed(ErrorCode.SURVEY_INVALID_REPEATABLE_SET_ITERATION,
                            "there is more than one repeatable set iteration.");
                    throw new ValidationException("there is more than one repeatable set iteration.");
                }

                if (StringUtils.isEmptyOrWhitespaceOnly(t[0])) {
                    tRepeatableSetIteration = null;
                } else {

                    if (tRepeatableSetId == null) {
                        setFailed(ErrorCode.SURVEY_INVALID_REPEATABLE_SET_ITERATION,
                                "repeatable set iteration does not make sense without a repeatable set id");
                        throw new ValidationException(
                                "repeatable set iteration does not make sense without a repeatable set id");
                    }

                    try {

                        tRepeatableSetIteration = Integer.parseInt(t[0]);
                    } catch (NumberFormatException e) {
                        setFailed(ErrorCode.SURVEY_INVALID_REPEATABLE_SET_ITERATION,
                                "The repeatable set iteration is invalid.");
                        throw new ValidationException("The repeatable set iteration is invalid.");
                    }
                }

                if (tRepeatableSetIteration == null && tRepeatableSetId != null) {

                    setFailed(ErrorCode.SURVEY_INVALID_REPEATABLE_SET_ITERATION,
                            "repeatable set id does not make sense without a repeatable set iteration");
                    throw new ValidationException(
                            "repeatable set id does not make sense without a repeatable set iteration");
                }
            } else {

                tRepeatableSetIteration = null;
            }

        } catch (ValidationException e) {
            e.failRequest(this);
            LOGGER.info(e.toString());
        }
    }

    this.surveyId = tSurveyId;
    this.promptId = tPromptId;
    this.repeatableSetId = tRepeatableSetId;
    this.repeatableSetIteration = tRepeatableSetIteration;
}

From source file:org.ohmage.request.survey.annotation.AnnotationUpdateRequest.java

/**
 * Creates a new survey annotation update request.
 * /*from   w  w w  . j  a v  a 2s. co m*/
 * @param httpRequest The HttpServletRequest with the parameters for this
 *                  request.
 * 
 * @throws InvalidRequestException Thrown if the parameters cannot be 
 *                            parsed.
 * 
 * @throws IOException There was an error reading from the request.
 */
public AnnotationUpdateRequest(HttpServletRequest httpRequest) throws IOException, InvalidRequestException {
    super(httpRequest, null, TokenLocation.PARAMETER, null);

    LOGGER.info("Creating a survey annotation update request.");

    UUID tAnnotationId = null;
    String tAnnotationText = null;
    long tTime = -1;
    DateTimeZone tTimezone = null;

    if (!isFailed()) {
        try {
            Map<String, String[]> parameters = getParameters();

            // Validate the annotation ID
            String[] t = parameters.get(InputKeys.ANNOTATION_ID);
            if (t == null || t.length != 1) {
                setFailed(ErrorCode.ANNOTATION_INVALID_ID,
                        "annotation_id is missing or there is more than one.");
                throw new ValidationException("annotation_id is missing or there is more than one.");
            } else {
                // FIXME We need a generic way to validate UUIDs
                tAnnotationId = SurveyResponseValidators.validateSurveyResponseId(t[0]);

                if (tAnnotationId == null) {
                    setFailed(ErrorCode.ANNOTATION_INVALID_ID, "The annoatation ID is invalid.");
                    throw new ValidationException("The annotation ID is invalid.");
                }
            }

            // Validate the annotation text
            t = parameters.get(InputKeys.ANNOTATION_TEXT);

            if (t == null || t.length != 1) {
                setFailed(ErrorCode.ANNOTATION_INVALID_ANNOTATION,
                        "annotation is missing or there is more than one.");
                throw new ValidationException("annotation is missing or there is more than one.");
            } else {
                tAnnotationText = t[0];

                if (StringUtils.isEmptyOrWhitespaceOnly(tAnnotationText)) {
                    setFailed(ErrorCode.ANNOTATION_INVALID_ANNOTATION, "The annotation is invalid.");
                    throw new ValidationException("The annotation is invalid.");
                }
            }

            // Validate the time
            t = parameters.get(InputKeys.TIME);

            if (t == null || t.length != 1) {
                setFailed(ErrorCode.ANNOTATION_INVALID_TIME, "time is missing or there is more than one value");
                throw new ValidationException("time is missing or there is more than one value");
            } else {

                try {
                    tTime = Long.valueOf(t[0]);
                } catch (NumberFormatException e) {
                    setFailed(ErrorCode.ANNOTATION_INVALID_TIME, "The time is invalid.");
                    throw new ValidationException("The time is invalid.");
                }
            }

            // Validate the timezone
            t = parameters.get(InputKeys.TIMEZONE);

            if (t == null || t.length != 1) {
                setFailed(ErrorCode.ANNOTATION_INVALID_TIMEZONE,
                        "timezone is missing or there is more than one value");
                throw new ValidationException("timezone is missing or there is more than one value");
            } else {

                try {
                    tTimezone = DateTimeUtils.getDateTimeZoneFromString(t[0]);
                } catch (IllegalArgumentException invalidTimezone) {
                    setFailed(ErrorCode.ANNOTATION_INVALID_TIMEZONE, "unknown timezone");
                    throw new ValidationException("unknown timezone", invalidTimezone);
                }
            }
        } catch (ValidationException e) {
            e.failRequest(this);
            LOGGER.info(e.toString());
        }
    }

    this.annotationId = tAnnotationId;
    this.annotationText = tAnnotationText;
    this.time = tTime;
    this.timezone = tTimezone;
}

From source file:com.lgallardo.qbittorrentclient.SettingsActivity.java

public void saveQBittorrentServerValues() {

    currentServerValue = currentServer.getValue();

    // Save options locally
    SharedPreferences sharedPrefs = getPreferenceManager().getSharedPreferences();

    Editor editor = sharedPrefs.edit();//from  w  w w.  j  a v  a  2s.  com

    if (hostname.getText().toString() != null && hostname.getText().toString() != "") {
        editor.putString("hostname" + currentServerValue, hostname.getText().toString());
    }

    if (subfolder.getText().toString() != null) {
        editor.putString("subfolder" + currentServerValue, subfolder.getText().toString());
    }

    editor.putBoolean("https" + currentServerValue, https.isChecked());

    if (port.getText().toString() != null && port.getText().toString() != "") {

        editor.putString("port" + currentServerValue, port.getText().toString());
    }

    if (username.getText().toString() != null && username.getText().toString() != "") {

        editor.putString("username" + currentServerValue, username.getText().toString());
    }

    if (password.getText().toString() != null && password.getText().toString() != "") {

        editor.putString("password" + currentServerValue, password.getText().toString());
    }

    if (connection_timeout.getText().toString() != null && connection_timeout.getText().toString() != "") {
        editor.putString("connection_timeout", connection_timeout.getText().toString());
    }

    if (data_timeout.getText().toString() != null && data_timeout.getText().toString() != "") {
        editor.putString("data_timeout", data_timeout.getText().toString());
    }

    editor.putBoolean("dark_ui" + currentServerValue, dark_ui.isChecked());

    if (ssid.getText().toString() != null && ssid.getText().toString() != "") {
        editor.putString("ssid" + currentServerValue, ssid.getText().toString());
    }

    if (local_hostname.getText().toString() != null && local_hostname.getText().toString() != "") {
        editor.putString("local_hostname" + currentServerValue, local_hostname.getText().toString());
    }

    if (local_port.getText().toString() != null && local_port.getText().toString() != "") {
        editor.putString("local_port" + currentServerValue, local_port.getText().toString());
    }

    if (keystore_path.getSummary().toString() != null) {
        editor.putString("keystore_path" + currentServerValue, keystore_path.getSummary().toString());
    }

    if (keystore_password.getText().toString() != null) {
        editor.putString("keystore_password" + currentServerValue, keystore_password.getText().toString());
    }

    // Commit changes
    editor.commit();

    // Refresh drawer servers
    String[] navigationDrawerServerItems;
    navigationDrawerServerItems = getResources().getStringArray(R.array.qBittorrentServers);

    ArrayList<DrawerItem> serverItems = new ArrayList<DrawerItem>();

    // Server items
    int currentServerIntValue = 1;

    try {
        currentServerIntValue = Integer.parseInt(currentServerValue);
    } catch (NumberFormatException e) {

    }

    serverItems.add(new DrawerItem(R.drawable.ic_drawer_servers,
            getResources().getString(R.string.drawer_servers_category), MainActivity.DRAWER_CATEGORY, false,
            null));

    for (int i = 0; i < navigationDrawerServerItems.length; i++) {
        serverItems.add(new DrawerItem(R.drawable.ic_drawer_subitem, navigationDrawerServerItems[i],
                MainActivity.DRAWER_ITEM_SERVERS, ((i + 1) == currentServerIntValue), "changeCurrentServer"));
    }

    try {
        MainActivity.rAdapter.refreshDrawerServers(serverItems);

    } catch (Exception e) {
        Log.e("Debug", "SettingActivity - Couldn't refresh servers: " + e.toString());
    }
}

From source file:org.quartz.impl.StdSchedulerFactory.java

private void setBeanProps(Object obj, Properties props) throws NoSuchMethodException, IllegalAccessException,
        java.lang.reflect.InvocationTargetException, IntrospectionException, SchedulerConfigException {
    props.remove("class");

    BeanInfo bi = Introspector.getBeanInfo(obj.getClass());
    PropertyDescriptor[] propDescs = bi.getPropertyDescriptors();
    PropertiesParser pp = new PropertiesParser(props);

    java.util.Enumeration keys = props.keys();
    while (keys.hasMoreElements()) {
        String name = (String) keys.nextElement();
        String c = name.substring(0, 1).toUpperCase(Locale.US);
        String methName = "set" + c + name.substring(1);

        java.lang.reflect.Method setMeth = getSetMethod(methName, propDescs);

        try {/*from  w  ww .j a va 2s. c o m*/
            if (setMeth == null) {
                throw new NoSuchMethodException("No setter for property '" + name + "'");
            }

            Class[] params = setMeth.getParameterTypes();
            if (params.length != 1) {
                throw new NoSuchMethodException("No 1-argument setter for property '" + name + "'");
            }
            if (params[0].equals(int.class)) {
                setMeth.invoke(obj, new Object[] { new Integer(pp.getIntProperty(name)) });
            } else if (params[0].equals(long.class)) {
                setMeth.invoke(obj, new Object[] { new Long(pp.getLongProperty(name)) });
            } else if (params[0].equals(float.class)) {
                setMeth.invoke(obj, new Object[] { new Float(pp.getFloatProperty(name)) });
            } else if (params[0].equals(double.class)) {
                setMeth.invoke(obj, new Object[] { new Double(pp.getDoubleProperty(name)) });
            } else if (params[0].equals(boolean.class)) {
                setMeth.invoke(obj, new Object[] { new Boolean(pp.getBooleanProperty(name)) });
            } else if (params[0].equals(String.class)) {
                setMeth.invoke(obj, new Object[] { pp.getStringProperty(name) });
            } else {
                throw new NoSuchMethodException("No primitive-type setter for property '" + name + "'");
            }
        } catch (NumberFormatException nfe) {
            throw new SchedulerConfigException(
                    "Could not parse property '" + name + "' into correct data type: " + nfe.toString());
        }
    }
}

From source file:us.mn.state.health.lims.sample.action.HumanSampleOneUpdateAction.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 Sample.
    // If there is a parameter present, we should bring up an existing
    // Sample to edit.
    String forward = FWD_SUCCESS;
    request.setAttribute(ALLOW_EDITS_KEY, "true");

    String id = request.getParameter(ID);

    if (StringUtil.isNullorNill(id) || "0".equals(id)) {
        isNew = true;/*from  w  ww .j av a 2  s. c  o m*/
    } else {
        isNew = false;
    }

    BaseActionForm dynaForm = (BaseActionForm) form;

    // server-side validation (validation.xml)
    ActionMessages errors = dynaForm.validate(mapping, request);

    // validate on server-side patient city/zip combination
    /*
     * String city = (String) dynaForm.get("city"); String zipCode =
     * (String) dynaForm.get("zipCode"); if (!StringUtil.isNullorNill(city) &&
     * !StringUtil.isNullorNill(zipCode)) { try { errors =
     * validateZipCity(errors, zipCode, city); } catch (Exception e) {
     * ActionError error = new ActionError( "errors.ValidationException",
     * null, null); errors.add(ActionMessages.GLOBAL_MESSAGE, error); } }
     */
    try {
        errors = validateAll(request, errors, dynaForm);
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("HumanSampleOneUpdateAction", "performAction()", e.toString());
        ActionError error = new ActionError("errors.ValidationException", null, null);
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
    }
    // end of zip/city combination check

    if (errors != null && errors.size() > 0) {
        // System.out.println("saveing errors " + errors.size());
        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");

    Patient patient = new Patient();
    Person person = new Person();
    Provider provider = new Provider();
    Person providerPerson = new Person();
    Sample sample = new Sample();
    SampleHuman sampleHuman = new SampleHuman();
    SampleOrganization sampleOrganization = new SampleOrganization();
    List sampleProjects = new ArrayList();
    SampleItem sampleItem = new SampleItem();
    sampleItem.setStatusId(StatusService.getInstance().getStatusID(SampleStatus.Entered));
    // bugzilla 1926 get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());
    // String typeOfSampleId = (String) dynaForm.get("typeOfSampleId");
    String typeOfSample = (String) dynaForm.get("typeOfSampleDesc");
    // String sourceOfSampleId = (String) dynaForm.get("sourceOfSampleId");
    //bugzilla 2470, unused
    // String sourceOfSample = (String) dynaForm.get("sourceOfSampleDesc");

    List sysUsers = new ArrayList();
    List sampleDomains = new ArrayList();
    List typeOfSamples = new ArrayList();
    List sourceOfSamples = new ArrayList();

    if (dynaForm.get("sysUsers") != null) {
        sysUsers = (List) dynaForm.get("sysUsers");
    } else {
        SystemUserDAO sysUserDAO = new SystemUserDAOImpl();
        sysUsers = sysUserDAO.getAllSystemUsers();
    }

    if (dynaForm.get("sampleDomains") != null) {
        sampleDomains = (List) dynaForm.get("sampleDomains");
    } else {
        SampleDomainDAO sampleDomainDAO = new SampleDomainDAOImpl();
        sampleDomains = sampleDomainDAO.getAllSampleDomains();
    }
    if (dynaForm.get("typeOfSamples") != null) {
        typeOfSamples = (List) dynaForm.get("typeOfSamples");
    } else {
        TypeOfSampleDAO typeOfSampleDAO = new TypeOfSampleDAOImpl();
        typeOfSamples = typeOfSampleDAO.getAllTypeOfSamples();
    }
    if (dynaForm.get("sourceOfSamples") != null) {
        sourceOfSamples = (List) dynaForm.get("sourceOfSamples");
    } else {
        SourceOfSampleDAO sourceOfSampleDAO = new SourceOfSampleDAOImpl();
        sourceOfSamples = sourceOfSampleDAO.getAllSourceOfSamples();
    }
    String stringOfTestIds = (String) dynaForm.get("selectedTestIds");

    String projectIdOrName = (String) dynaForm.get("projectIdOrName");
    String project2IdOrName = (String) dynaForm.get("project2IdOrName");

    String projectNameOrId = (String) dynaForm.get("projectNameOrId");
    String project2NameOrId = (String) dynaForm.get("project2NameOrId");

    // get the numeric projectId either from projectIdOrName or from
    // projectNameOrId
    String projectId = null;
    String project2Id = null;
    //bugzilla 2318 
    if (!StringUtil.isNullorNill(projectIdOrName) && !StringUtil.isNullorNill(projectNameOrId)) {
        try {
            Integer i = Integer.valueOf(projectIdOrName);
            projectId = projectIdOrName;
            //bugzilla 2154
            LogEvent.logDebug("HumanSampleOneUpdateAction", "performAction()",
                    "Parsed integer value of projectIdOrName: " + projectIdOrName + " projectNameOrId: "
                            + projectNameOrId);
        } catch (NumberFormatException nfe) {
            projectId = projectNameOrId;
            //bugzilla 2154
            LogEvent.logError("HumanSampleOneUpdateAction", "performAction()",
                    "Error parsing integer value of projectIdOrName: " + projectIdOrName + " "
                            + nfe.toString());
        }

    }

    //bugzilla 2318
    if (!StringUtil.isNullorNill(project2IdOrName) && !StringUtil.isNullorNill(project2NameOrId)) {
        try {
            Integer i = Integer.valueOf(project2IdOrName);
            project2Id = project2IdOrName;
            //bugzilla 2154
            LogEvent.logDebug("HumanSampleOneUpdateAction", "performAction()",
                    "Parsed integer value of project2IdOrName: " + project2IdOrName + " project2NameOrId: "
                            + project2NameOrId);
        } catch (NumberFormatException nfe) {
            project2Id = project2NameOrId;
            //bugzilla 2154
            LogEvent.logError("HumanSampleOneUpdateAction", "performAction()",
                    "Error parsing integer value of project2IdOrName: " + project2IdOrName + " "
                            + nfe.toString());
        }

    }

    String[] listOfTestIds = stringOfTestIds.split(SystemConfiguration.getInstance().getDefaultIdSeparator(),
            -1);

    List analyses = new ArrayList();
    for (int i = 0; i < listOfTestIds.length; i++) {
        if (!StringUtil.isNullorNill(listOfTestIds[i])) {
            Analysis analysis = new Analysis();

            Test test = new Test();
            String testId = (String) listOfTestIds[i];
            test.setId(testId);

            TestDAO testDAO = new TestDAOImpl();
            testDAO.getData(test);
            analysis.setTest(test);

            // TODO: need to populate this with actual data!!!
            analysis.setAnalysisType("TEST");
            analyses.add(analysis);
        }
    }

    SystemUser sysUser = null;

    for (int i = 0; i < sysUsers.size(); i++) {
        SystemUser su = (SystemUser) sysUsers.get(i);
        if (su.getId().equals(sysUserId)) {
            sysUser = su;
            break;
        }
    }

    TypeOfSample typeOfSamp = null;

    // get the right typeOfSamp to update sampleitem with
    for (int i = 0; i < typeOfSamples.size(); i++) {
        TypeOfSample s = (TypeOfSample) typeOfSamples.get(i);
        // if (s.getId().equals(typeOfSampleId)) {
        if (s.getDescription().equalsIgnoreCase(typeOfSample)) {
            typeOfSamp = s;
            break;
        }
    }

    // fixed in bugzilla 2470, unused
    //SourceOfSample sourceOfSamp = null;
    /*      
          // get the right sourceOfSamp to update sampleitem with
          for (int i = 0; i < sourceOfSamples.size(); i++) {
             SourceOfSample s = (SourceOfSample) sourceOfSamples.get(i);
             // if (s.getId().equals(sourceOfSampleId)) {
             if (s.getDescription().equalsIgnoreCase(sourceOfSample)) {
    sourceOfSamp = s;
    break;
             }
          }
    */
    // populate valueholder from form
    PropertyUtils.copyProperties(sample, dynaForm);
    PropertyUtils.copyProperties(person, dynaForm);
    PropertyUtils.copyProperties(patient, dynaForm);
    PropertyUtils.copyProperties(provider, dynaForm);
    PropertyUtils.copyProperties(sampleHuman, dynaForm);
    PropertyUtils.copyProperties(sampleOrganization, dynaForm);
    PropertyUtils.copyProperties(sampleItem, dynaForm);

    Organization o = new Organization();
    //bugzilla 2069
    o.setOrganizationLocalAbbreviation((String) dynaForm.get("organizationLocalAbbreviation"));
    OrganizationDAO organizationDAO = new OrganizationDAOImpl();
    o = organizationDAO.getOrganizationByLocalAbbreviation(o, true);

    sampleOrganization.setOrganization(o);

    // if there was a first sampleProject id entered
    if (!StringUtil.isNullorNill(projectId)) {
        SampleProject sampleProject = new SampleProject();
        Project p = new Project();
        //bugzilla 2438
        p.setLocalAbbreviation(projectId);
        ProjectDAO projectDAO = new ProjectDAOImpl();
        p = projectDAO.getProjectByLocalAbbreviation(p, true);
        sampleProject.setProject(p);
        sampleProject.setIsPermanent(NO);
        sampleProjects.add(sampleProject);
    }

    // in case there was a second sampleProject id entered
    if (!StringUtil.isNullorNill(project2Id)) {
        SampleProject sampleProject2 = new SampleProject();
        Project p2 = new Project();
        //bugzilla 2438
        p2.setLocalAbbreviation(project2Id);
        ProjectDAO projectDAO = new ProjectDAOImpl();
        p2 = projectDAO.getProjectByLocalAbbreviation(p2, true);
        sampleProject2.setProject(p2);
        sampleProject2.setIsPermanent(NO);
        sampleProjects.add(sampleProject2);
    }

    // set the provider person manually as we have two Person valueholders
    // to populate and copyProperties() can only handle one per form
    providerPerson.setFirstName((String) dynaForm.get("providerFirstName"));
    providerPerson.setLastName((String) dynaForm.get("providerLastName"));

    // format workPhone for storage
    String workPhone = (String) dynaForm.get("providerWorkPhone");
    String ext = (String) dynaForm.get("providerWorkPhoneExtension");
    String formattedPhone = StringUtil.formatPhone(workPhone, ext);
    // phone is stored as 999/999-9999.9999
    // area code/phone - number.extension
    providerPerson.setWorkPhone(formattedPhone);
    //bugzilla 1701 blank out provider.externalId - this is copied from patient 
    //externalId which is not related...and we currently don't enter an externalId for
    //provider on this screen
    provider.setExternalId(BLANK);

    // set collection time
    String time = (String) dynaForm.get("collectionTimeForDisplay");

    if (StringUtil.isNullorNill(time)) {
        time = "00:00";
    }
    sample.setCollectionTimeForDisplay(time);
    // AIS - bugzilla 1408 - Start
    String accessionNumberOne = (String) dynaForm.get("accessionNumber");
    sample.setAccessionNumber(accessionNumberOne);
    SampleDAO sampleDAO = new SampleDAOImpl();
    sampleDAO.getSampleByAccessionNumber(sample);
    String stickerReceivedFlag = (String) dynaForm.get("stickerReceivedFlag");
    String referredCultureFlag = (String) dynaForm.get("referredCultureFlag");
    sample.setStickerReceivedFlag(stickerReceivedFlag);
    sample.setReferredCultureFlag(referredCultureFlag);
    String date = (String) dynaForm.get("collectionDateForDisplay");

    // bgm - bugzilla 1586 check for null collection date
    //db bugzilla 1765 - noticed that error occurs - need to check
    // also that date is not nill as well as not null
    if (!StringUtil.isNullorNill(date)) {
        sample.setCollectionDateForDisplay(date);
        // AIS - bugzilla 1408 - End

        Timestamp d = sample.getCollectionDate();
        //bugzilla 1857 deprecated date stuff
        Calendar cal = Calendar.getInstance();
        cal.setTime(d);
        if (null != d)
            if (time.indexOf(":") > 0) {
                cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(time.substring(0, 2)).intValue());
                //d.setHours(Integer.valueOf(time.substring(0, 2)).intValue());
                cal.set(Calendar.MINUTE, Integer.valueOf(time.substring(3, 5)).intValue());
                //d.setMinutes(Integer.valueOf(time.substring(3, 5)).intValue());
                d = new Timestamp(cal.getTimeInMillis());
                sample.setCollectionDate(d);
            }
    }
    // sampleItem
    sampleItem.setSortOrder("1");
    // set the typeOfSample
    sampleItem.setTypeOfSample(typeOfSamp);
    // sampleItem.setTypeOfSample(typeOfSample);
    // set the sourceOfSample
    // fixed in bugzilla 2470 unused
    //sampleItem.setSourceOfSample(sourceOfSamp);
    // sampleItem.setSourceOfSample(sourceOfSample);

    // set the system user
    sample.setSystemUser(sysUser);
    //bugzilla 2112
    sample.setSysUserId(sysUserId);
    //bugzilla 1926
    sampleItem.setSysUserId(sysUserId);
    sampleOrganization.setSysUserId(sysUserId);
    sampleHuman.setSysUserId(sysUserId);
    patient.setSysUserId(sysUserId);
    person.setSysUserId(sysUserId);
    provider.setSysUserId(sysUserId);
    providerPerson.setSysUserId(sysUserId);

    //bugzilla 2169 - undo bugzilla 1408 logic to copy externalId into sample client_reference if clientRef# is blank
    if (!StringUtil.isNullorNill((String) dynaForm.get("clientReference"))) {
        sample.setClientReference((String) dynaForm.get("clientReference"));
    }

    //bugzilla 1761 (get status code and domain from SystemConfiguration)
    sample.setStatus(SystemConfiguration.getInstance().getSampleStatusEntry1Complete());
    sample.setDomain(SystemConfiguration.getInstance().getHumanDomain());
    sample.setSampleProjects(sampleProjects);

    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    try {

        // HumanSampleOneDAO humanSampleOneDAO = new
        // HumanSampleOneDAOImpl();
        PersonDAO personDAO = new PersonDAOImpl();
        PatientDAO patientDAO = new PatientDAOImpl();
        ProviderDAO providerDAO = new ProviderDAOImpl();

        // AIS - bugzilla 1408 ( already declared..)
        // SampleDAO sampleDAO = new SampleDAOImpl();

        SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
        SampleProjectDAO sampleProjectDAO = new SampleProjectDAOImpl();
        SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
        SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
        AnalysisDAO analysisDAO = new AnalysisDAOImpl();

        // why does it only work if sample is the first insert (not when
        // person is first insert?)

        // AIS - bugzilla 1408
        // sampleDAO.insertData(sample);
        //bugzilla 2154
        LogEvent.logDebug("HumanSampleOneUpdateAction", "performAction()",
                "About to sampleDAO.updateData() status code: " + sample.getStatus());

        sampleDAO.updateData(sample);

        personDAO.insertData(person);
        patient.setPerson(person);
        patientDAO.insertData(patient);
        personDAO.insertData(providerPerson);
        provider.setPerson(providerPerson);
        providerDAO.insertData(provider);

        for (int i = 0; i < sampleProjects.size(); i++) {
            SampleProject sampleProject = (SampleProject) sampleProjects.get(i);
            sampleProject.setSample(sample);
            // sampleProject.setProject(prClone);

            //bugzilla 2112
            sampleProject.setSysUserId(sysUserId);
            sampleProjectDAO.insertData(sampleProject);
        }

        sampleHuman.setSampleId(sample.getId());
        sampleHuman.setPatientId(patient.getId());
        sampleHuman.setProviderId(provider.getId());
        sampleHumanDAO.insertData(sampleHuman);
        sampleOrganization.setSampleId(sample.getId());
        sampleOrganization.setSample(sample);
        sampleOrganizationDAO.insertData(sampleOrganization);
        //bugzilla 1773 need to store sample not sampleId for use in sorting
        sampleItem.setSample(sample);
        // AIS - bugzilla 1408
        // sampleItemDAO.insertData(sampleItem);

        //bugzilla 2113 
        SampleItem si = new SampleItem();
        si.setSample(sample);
        sampleItemDAO.getDataBySample(si);
        sampleItem.setId(si.getId());

        //bugzilla 2470
        sampleItem.setSourceOfSampleId(si.getSourceOfSampleId());
        sampleItem.setSourceOther(si.getSourceOther());

        sampleItem.setLastupdated(si.getLastupdated());
        sampleItemDAO.updateData(sampleItem);

        // Analysis table
        if (analyses != null) {
            for (int i = 0; i < analyses.size(); i++) {
                Analysis analysis = (Analysis) analyses.get(i);
                analysis.setSampleItem(sampleItem);
                //bugzilla 2064
                analysis.setRevision(SystemConfiguration.getInstance().getAnalysisDefaultRevision());
                //bugzilla 2013 added duplicateCheck parameter
                analysisDAO.insertData(analysis, false);
            }
        }

        // insert humanSampleOne
        // humanSampleOneDAO.insertData(patient, person, provider,
        // providerPerson, sample, sampleHuman, sampleOrganization,
        // sampleItem, analyses);
        tx.commit();
    } catch (LIMSRuntimeException lre) {
        //bugzilla 2154
        LogEvent.logError("HumanSampleOneUpdateAction", "performAction()", lre.toString());
        tx.rollback();
        errors = new ActionMessages();
        ActionError error = null;
        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 {
            //lre.printStackTrace();
            error = new ActionError("errors.UpdateException", null, null);
        }
        errors.add(ActionMessages.GLOBAL_MESSAGE, error);
        saveErrors(request, errors);
        request.setAttribute(Globals.ERROR_KEY, errors);
        request.setAttribute(ALLOW_EDITS_KEY, "false");
        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, sample);

    // PropertyUtils.setProperty(dynaForm, "parentSamples", samps);
    PropertyUtils.setProperty(dynaForm, "sysUsers", sysUsers);
    PropertyUtils.setProperty(dynaForm, "sampleDomains", sampleDomains);

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

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

    }

    if (forward.equals(FWD_SUCCESS)) {
        request.setAttribute("menuDefinition", "default");
    }

    // TODO: temporary code to forward with accessionNumber (remove the
    // overriding getForward in this class
    String accessionNumber = sample.getAccessionNumber();
    // return getForward(mapping.findForward(forward), id, start);
    return getForward(mapping.findForward(forward), id, start, accessionNumber);

}