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:org.sakaiproject.citation.impl.BaseConfigurationService.java

/**
 * Get the maximum number of databases we can search at one time
 * @return The maximum value (defaults to <code>SEARCHABLE_DATABASES</code>
 *                            if no other value is specified)
 *//*www.ja v  a2s .  c  o m*/
public synchronized int getSiteConfigMaximumSearchableDBs() {
    String configValue = getConfigurationParameter("searchable-databases");
    int searchableDbs = SEARCHABLE_DATABASES;
    /*
     * Supply the default if no value was configured
     */
    if (configValue == null) {
        return searchableDbs;
    }
    /*
     * Make sure we have a good value
     */
    try {
        searchableDbs = Integer.parseInt(configValue);
        if (searchableDbs <= 0) {
            throw new NumberFormatException(configValue);
        }
    } catch (NumberFormatException exception) {
        if (m_log.isDebugEnabled()) {
            m_log.debug("Maximum searchable database exception: " + exception.toString());
        }
        searchableDbs = SEARCHABLE_DATABASES;
    } finally {
        return searchableDbs;
    }
}

From source file:us.mn.state.health.lims.sample.action.HumanSampleTwoUpdateAction.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 w w.ja v a 2  s  .c  o 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");
    String blankscreen = (String) dynaForm.get("blankscreen");

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

    String typeOfSample = (String) dynaForm.get("typeOfSampleDesc");
    //bugzilla 2470, unused
    //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("HumanSampleTwoUpdateAction", "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("HumanSampleTwoUpdateAction", "performAction()", nfe.toString());
            project2Id = project2NameOrId;
        }

    }

    //bugzilla 2028
    //bugzilla 2069
    String submitterNumber = (String) dynaForm.get("organizationLocalAbbreviation");

    // 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);

    PersonDAO personDAO = new PersonDAOImpl();
    PatientDAO patientDAO = new PatientDAOImpl();
    ProviderDAO providerDAO = new ProviderDAOImpl();
    SampleDAO sampleDAO = new SampleDAOImpl();
    SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
    SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
    SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
    AnalysisDAO analysisDAO = new AnalysisDAOImpl();
    SampleProjectDAO sampleProjectDAO = new SampleProjectDAOImpl();
    ProjectDAO projectDAO = new ProjectDAOImpl();
    AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
    QaEventDAO qaEventDAO = new QaEventDAOImpl();

    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 oldSampleProjects = new ArrayList();
    List newSampleProjects = new ArrayList();
    SampleItem sampleItem = new SampleItem();
    sampleItem.setStatusId(StatusService.getInstance().getStatusID(SampleStatus.Entered));
    // TODO need to populate this with tests entered in HSE I
    List analyses = new ArrayList();

    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("HumanSampleTwoUpdateAction", "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);
        PropertyUtils.setProperty(dynaForm, "blankscreen", "true");
        request.setAttribute(ALLOW_EDITS_KEY, "false");

        return mapping.findForward(FWD_FAIL);
    }
    // System.out.println("Now try to get data for accession number ");
    errors = dynaForm.validate(mapping, request);

    try {
        errors = validateAll(request, errors, dynaForm, humanSampleOneMap);
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("HumanSampleTwoUpdateAction", "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) {
        saveErrors(request, errors);
        // since we forward to jsp - not Action we don't need to
        // repopulate
        // the lists here
        return mapping.findForward(FWD_FAIL);
    }

    // GET ORIGINAL DATA
    try {

        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);

            oldSampleProjects = sample.getSampleProjects();

        }

    } catch (LIMSRuntimeException lre) {
        // if error then forward to fail and don't update to blank page
        // = false
        //bugzilla 2154
        LogEvent.logError("HumanSampleTwoUpdateAction", "performAction()", lre.toString());
        errors = new ActionMessages();
        ActionError error = null;
        error = new ActionError("errors.GetException", null, null);
        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);

    }

    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;
             }
          }
    */
    // System.out.println("This is entered date before update from form
    // "
    // + sample.getEnteredDate()
    // + sample.getEnteredDateForDisplay());

    // UPDATE DATA FROM FORM
    // 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 org = new Organization();
    org.setOrganizationLocalAbbreviation((String) dynaForm.get("organizationLocalAbbreviation"));
    OrganizationDAO organizationDAO = new OrganizationDAOImpl();
    org = organizationDAO.getOrganizationByLocalAbbreviation(org, true);
    sampleOrganization.setOrganization(org);

    // if there was a first sampleProject id entered
    // 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);
        p = projectDAO.getProjectByLocalAbbreviation(p, true);
        sampleProject.setProject(p);
        sampleProject.setSample(sample);
        sampleProject.setIsPermanent(NO);
        newSampleProjects.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);
        p2 = projectDAO.getProjectByLocalAbbreviation(p2, true);
        sampleProject2.setProject(p2);
        sampleProject2.setSample(sample);
        sampleProject2.setIsPermanent(NO);
        newSampleProjects.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);

    Timestamp d = sample.getCollectionDate();
    //bgm - bugzilla 1586 check for null date
    if (null != d) {
        if (time.indexOf(":") > 0) {
            //bugzilla 1857 deprecated stuff
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(time.substring(0, 2)).intValue());
            cal.set(Calendar.MINUTE, Integer.valueOf(time.substring(3, 5)).intValue());
            //d.setHours(Integer.valueOf(time.substring(0, 2)).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);
    // set the sourceOfSample
    // fixed in bugzilla 2470 unused 
    //sampleItem.setSourceOfSample(sourceOfSamp);

    sample.setSampleProjects(newSampleProjects);
    // get entered by through system (when we have login functionality)
    // removed per Christina 3/03/2006
    // sample.setEnteredBy("diane");

    //get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());

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

    List newIds = new ArrayList();
    List oldIds = new ArrayList();

    if (newSampleProjects != null) {
        for (int i = 0; i < newSampleProjects.size(); i++) {
            SampleProject sp = (SampleProject) newSampleProjects.get(i);
            newIds.add(sp.getId());
        }
    }

    if (oldSampleProjects != null) {

        List listOfOldOnesToRemove = new ArrayList();
        for (int i = 0; i < oldSampleProjects.size(); i++) {
            SampleProject sp = (SampleProject) oldSampleProjects.get(i);
            oldIds.add(sp.getId());
            if (!newIds.contains(sp.getId())) {
                // remove ones that are to be deleted
                listOfOldOnesToRemove.add(new Integer(i));
            }
        }

        int decreaseOSPIndexBy = 0;
        int decreaseOIIndexBy = 0;
        List listOfSampleProjectObjectsToDelete = new ArrayList();
        for (int i = 0; i < listOfOldOnesToRemove.size(); i++) {
            SampleProject sp = (SampleProject) oldSampleProjects
                    .remove(((Integer) listOfOldOnesToRemove.get(i)).intValue() - decreaseOSPIndexBy++);
            //bugzilla 1926
            sp.setSysUserId(sysUserId);
            listOfSampleProjectObjectsToDelete.add(sp);
            oldIds.remove(((Integer) listOfOldOnesToRemove.get(i)).intValue() - decreaseOIIndexBy++);

        }
        sampleProjectDAO.deleteData(listOfSampleProjectObjectsToDelete);
    }

    if (newSampleProjects != null) {
        for (int j = 0; j < newSampleProjects.size(); j++) {
            SampleProject saPr = (SampleProject) newSampleProjects.get(j);

            int index = oldIds.indexOf(saPr.getId());
            if (index >= 0) {
                SampleProject sampleProjectClone = (SampleProject) oldSampleProjects.get(index);
                PropertyUtils.copyProperties(sampleProjectClone, saPr);
                Sample smplClone = (Sample) sampleProjectClone.getSample();
                sampleProjectClone.setSample(smplClone);
                Project pClone = (Project) sampleProjectClone.getProject();
                sampleProjectClone.setProject(pClone);
                PropertyUtils.setProperty(sampleProjectClone, "lastupdated",
                        (Timestamp) dynaForm.get("sampleProject1Lastupdated"));

                sampleProjectClone.setSysUserId(sysUserId);
                sampleProjectDAO.updateData(sampleProjectClone);
                oldSampleProjects.set(index, sampleProjectClone);
            } else {
                SampleProject sampleProjectClone = new SampleProject();
                PropertyUtils.copyProperties(sampleProjectClone, saPr);
                Sample smplClone = (Sample) sampleProjectClone.getSample();
                sampleProjectClone.setSample(smplClone);
                Project pClone = (Project) sampleProjectClone.getProject();
                sampleProjectClone.setProject(pClone);
                PropertyUtils.setProperty(sampleProjectClone, "lastupdated",
                        (Timestamp) dynaForm.get("sampleProject2Lastupdated"));
                //bugzilla 1926
                sampleProjectClone.setSysUserId(sysUserId);
                sampleProjectDAO.insertData(sampleProjectClone);
                oldSampleProjects.add(sampleProjectClone);
            }

        }

    }
    sample.setSampleProjects(oldSampleProjects);
    // END DIANE

    try {

        // set last updated from form
        PropertyUtils.setProperty(person, "lastupdated", (Timestamp) dynaForm.get("personLastupdated"));
        PropertyUtils.setProperty(patient, "lastupdated", (Timestamp) dynaForm.get("patientLastupdated"));
        PropertyUtils.setProperty(sample, "lastupdated", (Timestamp) dynaForm.get("lastupdated"));
        PropertyUtils.setProperty(providerPerson, "lastupdated",
                (Timestamp) dynaForm.get("providerPersonLastupdated"));
        PropertyUtils.setProperty(provider, "lastupdated", (Timestamp) dynaForm.get("providerLastupdated"));
        PropertyUtils.setProperty(sampleItem, "lastupdated", (Timestamp) dynaForm.get("sampleItemLastupdated"));
        PropertyUtils.setProperty(sampleHuman, "lastupdated",
                (Timestamp) dynaForm.get("sampleHumanLastupdated"));
        PropertyUtils.setProperty(sampleOrganization, "lastupdated",
                (Timestamp) dynaForm.get("sampleOrganizationLastupdated"));

        //System.out.println("This is person ts " + person.getLastupdated().toLocaleString());

        person.setSysUserId(sysUserId);
        patient.setSysUserId(sysUserId);
        providerPerson.setSysUserId(sysUserId);
        provider.setSysUserId(sysUserId);
        sample.setSysUserId(sysUserId);
        sampleHuman.setSysUserId(sysUserId);
        sampleOrganization.setSysUserId(sysUserId);
        sampleItem.setSysUserId(sysUserId);

        personDAO.updateData(person);
        patient.setPerson(person);
        //System.out.println("This is patient ts "    + patient.getLastupdated().toLocaleString());

        patientDAO.updateData(patient);
        personDAO.updateData(providerPerson);
        provider.setPerson(providerPerson);
        providerDAO.updateData(provider);

        sampleHuman.setSampleId(sample.getId());
        sampleHuman.setPatientId(patient.getId());
        sampleHuman.setProviderId(provider.getId());
        sampleHumanDAO.updateData(sampleHuman);
        sampleOrganization.setSampleId(sample.getId());
        sampleOrganization.setSample(sample);
        sampleOrganizationDAO.updateData(sampleOrganization);

        //bugzilla 2470 
        SampleItem si = new SampleItem();
        si.setSample(sample);
        sampleItemDAO.getDataBySample(si);
        sampleItem.setId(si.getId());
        sampleItem.setSourceOfSampleId(si.getSourceOfSampleId());
        sampleItem.setSourceOther(si.getSourceOther());

        //bugzilla 1773 need to store sample not sampleId for use in sorting
        sampleItem.setSample(sample);
        sampleItemDAO.updateData(sampleItem);

        boolean allAnalysesReleased = true;

        //bugzilla 2028 get the possible qa events
        QaEvent qaEventForNoCollectionDate = new QaEvent();
        qaEventForNoCollectionDate
                .setQaEventName(SystemConfiguration.getInstance().getQaEventCodeForRequestNoCollectionDate());
        qaEventForNoCollectionDate = qaEventDAO.getQaEventByName(qaEventForNoCollectionDate);

        QaEvent qaEventForNoSampleType = new QaEvent();
        qaEventForNoSampleType
                .setQaEventName(SystemConfiguration.getInstance().getQaEventCodeForRequestNoSampleType());
        qaEventForNoSampleType = qaEventDAO.getQaEventByName(qaEventForNoSampleType);

        QaEvent qaEventForUnknownSubmitter = new QaEvent();
        qaEventForUnknownSubmitter
                .setQaEventName(SystemConfiguration.getInstance().getQaEventCodeForRequestUnknownSubmitter());
        qaEventForUnknownSubmitter = qaEventDAO.getQaEventByName(qaEventForUnknownSubmitter);
        //end bugzilla 2028

        // Analysis table
        for (int i = 0; i < analyses.size(); i++) {
            Analysis analysis = (Analysis) analyses.get(i);
            //bugzilla 1942: if all analyses for this sample have already gone through results verification and analysis.status is released
            //               then change sample.status to released also
            if (StringUtil.isNullorNill(analysis.getStatus()) || !analysis.getStatus()
                    .equals(SystemConfiguration.getInstance().getAnalysisStatusReleased())) {
                allAnalysesReleased = false;
            }
            analysis.setSampleItem(sampleItem);
            analysis.setSysUserId(sysUserId);

            //bugzilla 2028 QA_EVENT COLLECTIONDATE
            if (sample.getCollectionDate() == null) {
                AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                analysisQaEvent.setAnalysis(analysis);
                analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
                analysisQaEvent = analysisQaEventDAO.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                if (analysisQaEvent == null) {
                    analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
                    analysisQaEvent.setCompletedDate(null);
                    analysisQaEvent.setSysUserId(sysUserId);
                    analysisQaEventDAO.insertData(analysisQaEvent);
                } else {
                    if (analysisQaEvent.getCompletedDate() != null) {
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }

                }
            }

            //bugzilla 2028 QA_EVENT SAMPLETYPE
            if (typeOfSample.equals(SAMPLE_TYPE_NOT_GIVEN)) {
                AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                analysisQaEvent.setAnalysis(analysis);
                analysisQaEvent.setQaEvent(qaEventForNoSampleType);
                analysisQaEvent = analysisQaEventDAO.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                if (analysisQaEvent == null) {
                    analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoSampleType);
                    analysisQaEvent.setCompletedDate(null);
                    analysisQaEvent.setSysUserId(sysUserId);
                    analysisQaEventDAO.insertData(analysisQaEvent);
                } else {
                    if (analysisQaEvent.getCompletedDate() != null) {
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }

                }
            }

            //bugzilla 2028 QA_EVENT UNKNOWN SUBMITTER
            if (submitterNumber
                    .equals(SystemConfiguration.getInstance().getUnknownSubmitterNumberForQaEvent())) {
                AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                analysisQaEvent.setAnalysis(analysis);
                analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
                analysisQaEvent = analysisQaEventDAO.getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                if (analysisQaEvent == null) {
                    analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
                    analysisQaEvent.setCompletedDate(null);
                    analysisQaEvent.setSysUserId(sysUserId);
                    analysisQaEventDAO.insertData(analysisQaEvent);
                } else {
                    if (analysisQaEvent.getCompletedDate() != null) {
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }

                }
            }
            analysisDAO.updateData(analysis);
        }

        //bugzilla 1942
        if (analyses.size() > 0 && allAnalysesReleased) {
            sample.setStatus(SystemConfiguration.getInstance().getSampleStatusReleased());
            sample.setReleasedDateForDisplay(dateAsText);
        } else {
            sample.setStatus(SystemConfiguration.getInstance().getSampleStatusEntry2Complete());
        }

        sampleDAO.updateData(sample);

        tx.commit();
        // done updating return to menu
        blankscreen = "false";
        forward = FWD_CLOSE;

    } catch (LIMSRuntimeException lre) {
        //bugzilla 2154
        LogEvent.logError("HumanSampleTwoUpdateAction", "performAction()", lre.toString());
        tx.rollback();
        // if error then forward to fail and don't update to blank page
        // = false
        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 {
            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(FWD_FAIL);

    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");
    }

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

}

From source file:dk.defxws.fedoragsearch.server.Config.java

private void checkConfig() throws ConfigException {

    if (logger.isDebugEnabled())
        logger.debug("fedoragsearch.properties=" + fgsProps.toString());

    //     Check for unknown properties, indicating typos or wrong property names
    String[] propNames = { "fedoragsearch.deployFile", "fedoragsearch.soapBase", "fedoragsearch.soapUser",
            "fedoragsearch.soapPass", "fedoragsearch.defaultNoXslt",
            "fedoragsearch.defaultGfindObjectsRestXslt", "fedoragsearch.defaultUpdateIndexRestXslt",
            "fedoragsearch.defaultBrowseIndexRestXslt", "fedoragsearch.defaultGetRepositoryInfoRestXslt",
            "fedoragsearch.defaultGetIndexInfoRestXslt", "fedoragsearch.mimeTypes", "fedoragsearch.maxPageSize",
            "fedoragsearch.defaultBrowseIndexTermPageSize", "fedoragsearch.defaultGfindObjectsHitPageSize",
            "fedoragsearch.defaultGfindObjectsSnippetsMax", "fedoragsearch.defaultGfindObjectsFieldMaxLength",
            "fedoragsearch.repositoryNames", "fedoragsearch.indexNames", "fedoragsearch.updaterNames",
            "fedoragsearch.searchResultFilteringModule", "fedoragsearch.searchResultFilteringType" };
    //checkPropNames("fedoragsearch.properties", fgsProps, propNames);

    //     Check rest stylesheets
    checkRestStylesheet("fedoragsearch.defaultNoXslt");
    checkRestStylesheet("fedoragsearch.defaultGfindObjectsRestXslt");
    checkRestStylesheet("fedoragsearch.defaultUpdateIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultBrowseIndexRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetRepositoryInfoRestXslt");
    checkRestStylesheet("fedoragsearch.defaultGetIndexInfoRestXslt");

    //     Check mimeTypes  
    checkMimeTypes("fedoragsearch", fgsProps, "fedoragsearch.mimeTypes");

    //     Check resultPage properties
    try {//from   w  w w  . ja  va  2s .  c  om
        maxPageSize = Integer.parseInt(fgsProps.getProperty("fedoragsearch.maxPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** maxPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultBrowseIndexTermPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultBrowseIndexTermPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultBrowseIndexTermPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsHitPageSize = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsHitPageSize"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsHitPageSize is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsSnippetsMax = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsSnippetsMax"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsSnippetsMax is not valid:\n" + e.toString());
    }
    try {
        defaultGfindObjectsFieldMaxLength = Integer
                .parseInt(fgsProps.getProperty("fedoragsearch.defaultGfindObjectsFieldMaxLength"));
    } catch (NumberFormatException e) {
        errors.append("\n*** defaultGfindObjectsFieldMaxLength is not valid:\n" + e.toString());
    }

    // Check updater properties
    String updaterProperty = fgsProps.getProperty("fedoragsearch.updaterNames");
    if (updaterProperty == null) {
        updaterNameToProps = null; // No updaters will be created
    } else {
        updaterNameToProps = new Hashtable();
        StringTokenizer updaterNames = new StringTokenizer(updaterProperty);
        while (updaterNames.hasMoreTokens()) {
            String updaterName = updaterNames.nextToken();
            try {
                InputStream propStream = null;
                try {
                    propStream = getResourceInputStream("/updater/" + updaterName + "/updater.properties");
                } catch (ConfigException e) {
                    errors.append("\n" + e.getMessage());
                }
                Properties props = new Properties();
                props.load(propStream);
                propStream.close();

                //MIH
                convertProperties(props);
                if (logger.isInfoEnabled()) {
                    logger.info(
                            configName + "/updater/" + updaterName + "/updater.properties=" + props.toString());
                }

                // Check properties
                String propsNamingFactory = props.getProperty("java.naming.factory.initial");
                String propsProviderUrl = props.getProperty("java.naming.provider.url");
                String propsConnFactory = props.getProperty("connection.factory.name");
                String propsClientId = props.getProperty("client.id");

                if (propsNamingFactory == null) {
                    errors.append("\n*** java.naming.factory.initial not provided in " + configName
                            + "/updater/" + updaterName + "/updater.properties");
                }
                if (propsProviderUrl == null) {
                    errors.append("\n*** java.naming.provider.url not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsConnFactory == null) {
                    errors.append("\n*** connection.factory.name not provided in " + configName + "/updater/"
                            + updaterName + "/updater.properties");
                }
                if (propsClientId == null) {
                    errors.append("\n*** client.id not provided in " + configName + "/updater/" + updaterName
                            + "/updater.properties");
                }

                updaterNameToProps.put(updaterName, props);
            } catch (IOException e) {
                errors.append("\n*** Error loading " + configName + "/updater/" + updaterName + ".properties:\n"
                        + e.toString());
            }
        }
    }

    // Check searchResultFilteringModule property
    searchResultFilteringModuleProperty = fgsProps.getProperty("fedoragsearch.searchResultFilteringModule");
    if (searchResultFilteringModuleProperty != null && searchResultFilteringModuleProperty.length() > 0) {
        try {
            getSearchResultFiltering();
        } catch (ConfigException e) {
            errors.append(e.getMessage());
        }
        String searchResultFilteringTypeProperty = fgsProps
                .getProperty("fedoragsearch.searchResultFilteringType");
        StringTokenizer srft = new StringTokenizer("");
        if (searchResultFilteringTypeProperty != null) {
            srft = new StringTokenizer(searchResultFilteringTypeProperty);
        }
        int countTokens = srft.countTokens();
        if (searchResultFilteringTypeProperty == null || countTokens == 0 || countTokens > 1) {
            errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                    + searchResultFilteringTypeProperty
                    + ": one and only one of 'presearch', 'insearch', 'postsearch' must be stated.\n");
        } else {
            for (int i = 0; i < countTokens; i++) {
                String token = srft.nextToken();
                if (!("presearch".equals(token) || "insearch".equals(token) || "postsearch".equals(token))) {
                    errors.append("\n*** " + configName + ": fedoragsearch.searchResultFilteringType="
                            + searchResultFilteringTypeProperty
                            + ": only 'presearch', 'insearch', 'postsearch' may be stated, not '" + token
                            + "'.\n");
                }
            }
        }
    }

    //     Check repository properties
    Enumeration repositoryNames = repositoryNameToProps.keys();
    while (repositoryNames.hasMoreElements()) {
        String repositoryName = (String) repositoryNames.nextElement();
        Properties props = (Properties) repositoryNameToProps.get(repositoryName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/repository/" + repositoryName + "/repository.properties="
                    + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] reposPropNames = { "fgsrepository.repositoryName", "fgsrepository.fedoraSoap",
                "fgsrepository.fedoraUser", "fgsrepository.fedoraPass", "fgsrepository.fedoraObjectDir",
                "fgsrepository.fedoraVersion", "fgsrepository.defaultGetRepositoryInfoResultXslt",
                "fgsrepository.trustStorePath", "fgsrepository.trustStorePass" };
        //checkPropNames(configName+"/repository/"+repositoryName+"/repository.properties", props, reposPropNames);

        //        Check repositoryName
        String propsRepositoryName = props.getProperty("fgsrepository.repositoryName");
        if (!repositoryName.equals(propsRepositoryName)) {
            errors.append("\n*** " + configName + "/repository/" + repositoryName
                    + ": fgsrepository.repositoryName must be=" + repositoryName);
        }

        //        Check fedoraObjectDir
        //          String fedoraObjectDirName = insertSystemProperties(props.getProperty("fgsrepository.fedoraObjectDir"));
        //          File fedoraObjectDir = new File(fedoraObjectDirName);
        //          if (fedoraObjectDir == null) {
        //             errors.append("\n*** "+configName+"/repository/" + repositoryName
        //                   + ": fgsrepository.fedoraObjectDir="
        //                   + fedoraObjectDirName + " not found");
        //          }

        //        Check result stylesheets
        checkResultStylesheet("/repository/" + repositoryName, props,
                "fgsrepository.defaultGetRepositoryInfoResultXslt");
    }

    //     Check index properties
    Enumeration indexNames = indexNameToProps.keys();
    while (indexNames.hasMoreElements()) {
        String indexName = (String) indexNames.nextElement();
        Properties props = (Properties) indexNameToProps.get(indexName);
        if (logger.isDebugEnabled())
            logger.debug(configName + "/index/" + indexName + "/index.properties=" + props.toString());

        //        Check for unknown properties, indicating typos or wrong property names
        String[] indexPropNames = { "fgsindex.indexName", "fgsindex.indexBase", "fgsindex.indexUser",
                "fgsindex.indexPass", "fgsindex.operationsImpl", "fgsindex.defaultUpdateIndexDocXslt",
                "fgsindex.defaultUpdateIndexResultXslt", "fgsindex.defaultGfindObjectsResultXslt",
                "fgsindex.defaultBrowseIndexResultXslt", "fgsindex.defaultGetIndexInfoResultXslt",
                "fgsindex.indexDir", "fgsindex.analyzer", "fgsindex.untokenizedFields",
                "fgsindex.defaultQueryFields", "fgsindex.snippetBegin", "fgsindex.snippetEnd",
                "fgsindex.maxBufferedDocs", "fgsindex.mergeFactor", "fgsindex.ramBufferSizeMb",
                "fgsindex.defaultWriteLockTimeout", "fgsindex.defaultSortFields", "fgsindex.uriResolver" };
        //checkPropNames(configName+"/index/"+indexName+"/index.properties", props, indexPropNames);

        //        Check indexName
        String propsIndexName = props.getProperty("fgsindex.indexName");
        if (!indexName.equals(propsIndexName)) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.indexName must be="
                    + indexName);
        }

        //        Check operationsImpl class
        String operationsImpl = props.getProperty("fgsindex.operationsImpl");
        if (operationsImpl == null || operationsImpl.equals("")) {
            errors.append(
                    "\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl must be set in "
                            + configName + "/index/ " + indexName + ".properties");
        }
        try {
            Class operationsImplClass = Class.forName(operationsImpl);
            try {
                GenericOperationsImpl ops = (GenericOperationsImpl) operationsImplClass
                        .getConstructor(new Class[] {}).newInstance(new Object[] {});
            } catch (InstantiationException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (IllegalAccessException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (InvocationTargetException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            } catch (NoSuchMethodException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                        + operationsImpl + ": instantiation error.\n" + e.toString());
            }
        } catch (ClassNotFoundException e) {
            errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.operationsImpl="
                    + operationsImpl + ": class not found.\n" + e);
        }

        //        Check result stylesheets
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexDocXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultUpdateIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGfindObjectsResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultBrowseIndexResultXslt");
        checkResultStylesheet("/index/" + indexName, props, "fgsindex.defaultGetIndexInfoResultXslt");

        //        Check indexDir
        String indexDir = insertSystemProperties(props.getProperty("fgsindex.indexDir"));
        File indexDirFile = new File(indexDir);
        if (indexDirFile == null) {
            errors.append("\n*** " + configName + "/index/" + indexName + " fgsindex.indexDir=" + indexDir
                    + " must exist as a directory");
        }

        //        Check analyzer class for lucene and solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            String analyzer = props.getProperty("fgsindex.analyzer");
            if (analyzer == null || analyzer.equals("")) {
                analyzer = defaultAnalyzer;
            }
            try {
                Class analyzerClass = Class.forName(analyzer);
                try {
                    Analyzer a = (Analyzer) analyzerClass.getConstructor(new Class[] {})
                            .newInstance(new Object[] {});
                } catch (InstantiationException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (IllegalAccessException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (InvocationTargetException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error.\n" + e.toString());
                } catch (NoSuchMethodException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + " " + analyzer
                            + ": fgsindex.analyzer=" + analyzer + ": instantiation error:\n" + e.toString());
                }
            } catch (ClassNotFoundException e) {
                errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.analyzer=" + analyzer
                        + ": class not found:\n" + e.toString());
            }
        }

        //        Add untokenizedFields property for lucene
        if (operationsImpl.indexOf("fgslucene") > -1) {
            String defaultUntokenizedFields = props.getProperty("fgsindex.untokenizedFields");
            if (defaultUntokenizedFields == null)
                props.setProperty("fgsindex.untokenizedFields", "");
            if (indexDirFile != null) {
                StringBuffer untokenizedFields = new StringBuffer(
                        props.getProperty("fgsindex.untokenizedFields"));
                IndexReader ir = null;
                try {
                    ir = IndexReader.open(FSDirectory.open(new File(indexDir)), true);
                    int max = ir.numDocs();
                    if (max > 10)
                        max = 10;
                    for (int i = 0; i < max; i++) {
                        Document doc = ir.document(i);
                        for (ListIterator li = doc.getFields().listIterator(); li.hasNext();) {
                            Field f = (Field) li.next();
                            if (!f.isTokenized() && f.isIndexed() && untokenizedFields.indexOf(f.name()) < 0) {
                                untokenizedFields.append(" " + f.name());
                            }
                        }
                    }
                } catch (Exception e) {
                }
                props.setProperty("fgsindex.untokenizedFields", untokenizedFields.toString());
                if (logger.isDebugEnabled())
                    logger.debug("indexName=" + indexName + " fgsindex.untokenizedFields=" + untokenizedFields);
            }
        }

        //        Check defaultQueryFields - how can we check this?
        String defaultQueryFields = props.getProperty("fgsindex.defaultQueryFields");

        //        Use custom URIResolver if given
        //MIH: also check for solr
        if (operationsImpl.indexOf("fgslucene") > -1 || operationsImpl.indexOf("fgssolr") > -1) {
            Class uriResolverClass = null;
            String uriResolver = props.getProperty("fgsindex.uriResolver");
            if (!(uriResolver == null || uriResolver.equals(""))) {
                try {
                    uriResolverClass = Class.forName(uriResolver);
                    try {
                        URIResolverImpl ur = (URIResolverImpl) uriResolverClass.getConstructor(new Class[] {})
                                .newInstance(new Object[] {});
                        if (ur != null) {
                            ur.setConfig(this);
                            indexNameToUriResolvers.put(indexName, ur);
                        }
                    } catch (InstantiationException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (IllegalAccessException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (InvocationTargetException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error.\n"
                                + e.toString());
                    } catch (NoSuchMethodException e) {
                        errors.append("\n*** " + configName + "/index/" + indexName + " " + uriResolver
                                + ": fgsindex.uriResolver=" + uriResolver + ": instantiation error:\n"
                                + e.toString());
                    }
                } catch (ClassNotFoundException e) {
                    errors.append("\n*** " + configName + "/index/" + indexName + ": fgsindex.uriResolver="
                            + uriResolver + ": class not found:\n" + e.toString());
                }
            }
        }
    }
    if (logger.isDebugEnabled())
        logger.debug("configCheck configName=" + configName + " errors=" + errors.toString());
    if (errors.length() > 0)
        throw new ConfigException(errors.toString());
}

From source file:us.mn.state.health.lims.testmanagement.action.SampleDemographicsUpdateAction.java

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

    //System.out.println("I am in SampleDemographicsUpdateAction ");

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

    // server-side validation (validation.xml)
    ActionMessages errors = testManagementForm.validate(mapping, request);
    try {/*ww w  . j  a v  a 2s.  co  m*/
        errors = validateAll(request, errors, testManagementForm);
    } catch (Exception e) {
        //bugzilla 2154
        LogEvent.logError("SampleDemographicsUpdateAction", "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) {
        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 accessionNumber = (String) testManagementForm.get("accessionNumber");

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

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

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

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

    String projectNameOrId = (String) testManagementForm.get("projectNameOrId");
    String project2NameOrId = (String) testManagementForm.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("SampleDemographicsUpdateAction", "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("SampleDemographicsUpdateAction", "performAction()", nfe.toString());
            project2Id = project2NameOrId;
        }
    }

    // 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);

    PersonDAO personDAO = new PersonDAOImpl();
    PatientDAO patientDAO = new PatientDAOImpl();
    ProviderDAO providerDAO = new ProviderDAOImpl();
    SampleDAO sampleDAO = new SampleDAOImpl();
    SampleItemDAO sampleItemDAO = new SampleItemDAOImpl();
    SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl();
    SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl();
    AnalysisDAO analysisDAO = new AnalysisDAOImpl();
    SampleProjectDAO sampleProjectDAO = new SampleProjectDAOImpl();
    ProjectDAO projectDAO = new ProjectDAOImpl();
    AnalysisQaEventDAO analysisQaEventDAO = new AnalysisQaEventDAOImpl();
    AnalysisQaEventActionDAO analysisQaEventActionDAO = new AnalysisQaEventActionDAOImpl();
    QaEventDAO qaEventDAO = new QaEventDAOImpl();
    ActionDAO actionDAO = new ActionDAOImpl();

    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 oldSampleProjects = new ArrayList();
    List newSampleProjects = new ArrayList();
    SampleItem sampleItem = new SampleItem();

    List analyses = new ArrayList();

    // GET ORIGINAL DATA
    try {

        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);

            oldSampleProjects = sample.getSampleProjects();

        }

    } catch (LIMSRuntimeException lre) {
        // if error then forward to fail and don't update to blank page
        // = false
        //bugzilla 2154
        LogEvent.logError("SampleDemographicsUpdateAction", "performAction()", lre.toString());
        errors = new ActionMessages();
        ActionError error = null;
        error = new ActionError("errors.GetException", null, null);
        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);

    }

    // UPDATE DATA FROM FORM
    // populate valueholder from form
    PropertyUtils.copyProperties(sample, testManagementForm);
    PropertyUtils.copyProperties(person, testManagementForm);
    PropertyUtils.copyProperties(patient, testManagementForm);
    PropertyUtils.copyProperties(provider, testManagementForm);
    PropertyUtils.copyProperties(sampleHuman, testManagementForm);
    PropertyUtils.copyProperties(sampleOrganization, testManagementForm);
    PropertyUtils.copyProperties(sampleItem, testManagementForm);

    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.getDescription().equalsIgnoreCase(typeOfSample)) {
            typeOfSamp = s;
            break;
        }
    }

    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.getDescription().equalsIgnoreCase(sourceOfSample)) {
            sourceOfSamp = s;
            break;
        }
    }

    Organization org = new Organization();
    //bugzilla 2069
    org.setOrganizationLocalAbbreviation((String) testManagementForm.get("organizationLocalAbbreviation"));
    OrganizationDAO organizationDAO = new OrganizationDAOImpl();
    org = organizationDAO.getOrganizationByLocalAbbreviation(org, true);
    sampleOrganization.setOrganization(org);

    // if there was a first sampleProject id entered
    // ****Added a Try catch block to validate integer because..
    // ****When a project is deleted, the name of the project is passed in
    // as its id which causes error
    try {
        Integer i = Integer.valueOf(projectId);

        if (!StringUtil.isNullorNill(projectId)) {
            SampleProject sampleProject = new SampleProject();
            Project p = new Project();
            //bugzilla 2438
            p.setLocalAbbreviation(projectId);
            p = projectDAO.getProjectByLocalAbbreviation(p, true);
            sampleProject.setProject(p);
            sampleProject.setSample(sample);
            sampleProject.setIsPermanent(NO);
            newSampleProjects.add(sampleProject);

        }

    } catch (NumberFormatException nfe) {
        //bugzilla 2154
        LogEvent.logError("SampleDemographicsUpdateAction", "performAction()", nfe.toString());
    }

    // in case there was a second sampleProject id entered
    try {
        Integer i = Integer.valueOf(project2Id);

        if (!StringUtil.isNullorNill(project2Id)) {
            SampleProject sampleProject2 = new SampleProject();
            Project p2 = new Project();
            //bugzilla 2438
            p2.setLocalAbbreviation(project2Id);
            p2 = projectDAO.getProjectByLocalAbbreviation(p2, true);
            sampleProject2.setProject(p2);
            sampleProject2.setSample(sample);
            sampleProject2.setIsPermanent(NO);
            newSampleProjects.add(sampleProject2);
        }

    } catch (NumberFormatException nfe) {
        //bugzilla 2154
        LogEvent.logError("SampleDemographicsUpdateAction", "performAction()", nfe.toString());
    }

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

    // format workPhone for storage
    String workPhone = (String) testManagementForm.get("providerWorkPhone");
    String ext = (String) testManagementForm.get("providerWorkPhoneExtension");
    String formattedPhone = StringUtil.formatPhone(workPhone, ext);
    // phone is stored as 999/999-9999.9999
    // area code/phone - number.extension
    providerPerson.setWorkPhone(formattedPhone);

    String date = (String) testManagementForm.get("collectionDateForDisplay");

    if (!StringUtil.isNullorNill(date)) {
        //System.out.println("I am here");
        // set collection time
        String time = (String) testManagementForm.get("collectionTimeForDisplay");
        if (StringUtil.isNullorNill(time)) {
            time = "00:00";
        }
        sample.setCollectionTimeForDisplay(time);
        sample.setCollectionDateForDisplay(date);

        Timestamp d = sample.getCollectionDate();
        if (time.indexOf(":") > 0) {
            // bugzilla 1857 deprecated stuff
            Calendar cal = Calendar.getInstance();
            cal.setTime(d);
            cal.set(Calendar.HOUR_OF_DAY, Integer.valueOf(time.substring(0, 2)).intValue());
            cal.set(Calendar.MINUTE, Integer.valueOf(time.substring(3, 5)).intValue());
            // d.setHours(Integer.valueOf(time.substring(0, 2)).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);
    // set the sourceOfSample
    sampleItem.setSourceOfSample(sourceOfSamp);
    sample.setSampleProjects(newSampleProjects);

    // get sysUserId from login module
    UserSessionData usd = (UserSessionData) request.getSession().getAttribute(USER_SESSION_DATA);
    String sysUserId = String.valueOf(usd.getSystemUserId());
    org.hibernate.Transaction tx = HibernateUtil.getSession().beginTransaction();

    //bugzilla 2481, 2496 Action Owner
    SystemUser systemUser = new SystemUser();
    systemUser.setId(sysUserId);
    SystemUserDAO systemUserDAO = new SystemUserDAOImpl();
    systemUserDAO.getData(systemUser);

    List newIds = new ArrayList();
    List oldIds = new ArrayList();

    if (newSampleProjects != null) {
        for (int i = 0; i < newSampleProjects.size(); i++) {
            SampleProject sp = (SampleProject) newSampleProjects.get(i);
            newIds.add(sp.getId());
        }
    }

    if (oldSampleProjects != null) {

        List listOfOldOnesToRemove = new ArrayList();
        for (int i = 0; i < oldSampleProjects.size(); i++) {
            SampleProject sp = (SampleProject) oldSampleProjects.get(i);
            oldIds.add(sp.getId());
            if (!newIds.contains(sp.getId())) {
                // remove ones that are to be deleted
                listOfOldOnesToRemove.add(new Integer(i));
            }
        }

        int decreaseOSPIndexBy = 0;
        int decreaseOIIndexBy = 0;
        List listOfSampleProjectObjectsToDelete = new ArrayList();
        for (int i = 0; i < listOfOldOnesToRemove.size(); i++) {
            SampleProject sp = (SampleProject) oldSampleProjects
                    .remove(((Integer) listOfOldOnesToRemove.get(i)).intValue() - decreaseOSPIndexBy++);
            //bugzilla 1926
            sp.setSysUserId(sysUserId);
            listOfSampleProjectObjectsToDelete.add(sp);
            oldIds.remove(((Integer) listOfOldOnesToRemove.get(i)).intValue() - decreaseOIIndexBy++);

        }
        sampleProjectDAO.deleteData(listOfSampleProjectObjectsToDelete);
    }

    if (newSampleProjects != null) {
        for (int j = 0; j < newSampleProjects.size(); j++) {
            SampleProject saPr = (SampleProject) newSampleProjects.get(j);

            int index = oldIds.indexOf(saPr.getId());
            if (index >= 0) {
                SampleProject sampleProjectClone = (SampleProject) oldSampleProjects.get(index);
                PropertyUtils.copyProperties(sampleProjectClone, saPr);
                Sample smplClone = (Sample) sampleProjectClone.getSample();
                sampleProjectClone.setSample(smplClone);
                Project pClone = (Project) sampleProjectClone.getProject();
                sampleProjectClone.setProject(pClone);
                PropertyUtils.setProperty(sampleProjectClone, "lastupdated",
                        (Timestamp) testManagementForm.get("sampleProject1Lastupdated"));

                sampleProjectClone.setSysUserId(sysUserId);
                sampleProjectDAO.updateData(sampleProjectClone);
                oldSampleProjects.set(index, sampleProjectClone);
            } else {
                SampleProject sampleProjectClone = new SampleProject();
                PropertyUtils.copyProperties(sampleProjectClone, saPr);
                Sample smplClone = (Sample) sampleProjectClone.getSample();
                sampleProjectClone.setSample(smplClone);
                Project pClone = (Project) sampleProjectClone.getProject();
                sampleProjectClone.setProject(pClone);
                PropertyUtils.setProperty(sampleProjectClone, "lastupdated",
                        (Timestamp) testManagementForm.get("sampleProject2Lastupdated"));
                //bugzilla 1926
                sampleProjectClone.setSysUserId(sysUserId);
                sampleProjectDAO.insertData(sampleProjectClone);
                oldSampleProjects.add(sampleProjectClone);
            }
        }
    }

    sample.setSampleProjects(oldSampleProjects);
    // END DIANE

    try {

        // set last updated from form
        PropertyUtils.setProperty(person, "lastupdated",
                (Timestamp) testManagementForm.get("personLastupdated"));
        PropertyUtils.setProperty(patient, "lastupdated",
                (Timestamp) testManagementForm.get("patientLastupdated"));
        PropertyUtils.setProperty(sample, "lastupdated", (Timestamp) testManagementForm.get("lastupdated"));
        PropertyUtils.setProperty(providerPerson, "lastupdated",
                (Timestamp) testManagementForm.get("providerPersonLastupdated"));
        PropertyUtils.setProperty(provider, "lastupdated",
                (Timestamp) testManagementForm.get("providerLastupdated"));
        PropertyUtils.setProperty(sampleItem, "lastupdated",
                (Timestamp) testManagementForm.get("sampleItemLastupdated"));
        PropertyUtils.setProperty(sampleHuman, "lastupdated",
                (Timestamp) testManagementForm.get("sampleHumanLastupdated"));
        PropertyUtils.setProperty(sampleOrganization, "lastupdated",
                (Timestamp) testManagementForm.get("sampleOrganizationLastupdated"));

        person.setSysUserId(sysUserId);
        patient.setSysUserId(sysUserId);
        providerPerson.setSysUserId(sysUserId);
        provider.setSysUserId(sysUserId);
        sample.setSysUserId(sysUserId);
        sampleHuman.setSysUserId(sysUserId);
        sampleOrganization.setSysUserId(sysUserId);
        sampleItem.setSysUserId(sysUserId);
        personDAO.updateData(person);
        patient.setPerson(person);

        patientDAO.updateData(patient);
        personDAO.updateData(providerPerson);
        provider.setPerson(providerPerson);
        providerDAO.updateData(provider);
        sampleDAO.updateData(sample);

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

        sampleItemDAO.updateData(sampleItem);

        // Analysis table
        for (int i = 0; i < analyses.size(); i++) {
            Analysis analysis = (Analysis) analyses.get(i);
            analysis.setSampleItem(sampleItem);
            analysis.setSysUserId(sysUserId);
            analysisDAO.updateData(analysis);
        }

        // bugzilla 3032/2028 qa event logic needs to be executed for new and
        // existing analyses for this sample
        // ADDITIONAL REQUIREMENT ADDED 8/30: only for HSE2 Completed Status (see bugzilla 2032)
        boolean isSampleStatusReadyForQaEvent = false;
        if (!StringUtil.isNullorNill(sample.getStatus())
                && (sample.getStatus().equals(SystemConfiguration.getInstance().getSampleStatusReleased()))
                || sample.getStatus()
                        .equals(SystemConfiguration.getInstance().getSampleStatusEntry2Complete())) {
            isSampleStatusReadyForQaEvent = true;
        }
        if (isSampleStatusReadyForQaEvent) {

            // bugzilla 2028 need additional information for qa events
            typeOfSamp = sampleItem.getTypeOfSample();
            sampleOrganization.setSampleId(sample.getId());
            sampleOrganizationDAO.getDataBySample(sampleOrganization);
            //bugzilla 2589
            String submitterNumber = "";
            if (sampleOrganization != null && sampleOrganization.getOrganization() != null) {
                submitterNumber = sampleOrganization.getOrganization().getId();
            }

            //bugzilla 2227
            List allAnalysesForSample = analysisDAO.getMaxRevisionAnalysesBySample(sampleItem);

            // bugzilla 2028 get the possible qa events
            QaEvent qaEventForNoCollectionDate = new QaEvent();
            qaEventForNoCollectionDate.setQaEventName(
                    SystemConfiguration.getInstance().getQaEventCodeForRequestNoCollectionDate());
            qaEventForNoCollectionDate = qaEventDAO.getQaEventByName(qaEventForNoCollectionDate);

            QaEvent qaEventForNoSampleType = new QaEvent();
            qaEventForNoSampleType
                    .setQaEventName(SystemConfiguration.getInstance().getQaEventCodeForRequestNoSampleType());
            qaEventForNoSampleType = qaEventDAO.getQaEventByName(qaEventForNoSampleType);

            QaEvent qaEventForUnknownSubmitter = new QaEvent();
            qaEventForUnknownSubmitter.setQaEventName(
                    SystemConfiguration.getInstance().getQaEventCodeForRequestUnknownSubmitter());
            qaEventForUnknownSubmitter = qaEventDAO.getQaEventByName(qaEventForUnknownSubmitter);
            // end bugzilla 2028

            // bugzilla 2028 get the possible qa event actions
            Action actionForNoCollectionDate = new Action();
            actionForNoCollectionDate.setCode(
                    SystemConfiguration.getInstance().getQaEventActionCodeForRequestNoCollectionDate());
            actionForNoCollectionDate = actionDAO.getActionByCode(actionForNoCollectionDate);

            Action actionForNoSampleType = new Action();
            actionForNoSampleType
                    .setCode(SystemConfiguration.getInstance().getQaEventActionCodeForRequestNoSampleType());
            actionForNoSampleType = actionDAO.getActionByCode(actionForNoSampleType);

            Action actionForUnknownSubmitter = new Action();
            actionForUnknownSubmitter.setCode(
                    SystemConfiguration.getInstance().getQaEventActionCodeForRequestUnknownSubmitter());
            actionForUnknownSubmitter = actionDAO.getActionByCode(actionForUnknownSubmitter);
            // end bugzilla 2028

            for (int i = 0; i < allAnalysesForSample.size(); i++) {
                Analysis analysis = (Analysis) allAnalysesForSample.get(i);
                // bugzilla 2028 QA_EVENT COLLECTIONDATE
                if (sample.getCollectionDate() == null) {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    if (analysisQaEvent == null) {
                        analysisQaEvent = new AnalysisQaEvent();
                        analysisQaEvent.setAnalysis(analysis);
                        analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.insertData(analysisQaEvent);
                    } else {
                        if (analysisQaEvent.getCompletedDate() != null) {
                            analysisQaEvent.setCompletedDate(null);
                            analysisQaEvent.setSysUserId(sysUserId);
                            analysisQaEventDAO.updateData(analysisQaEvent);
                        }

                    }
                } else {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoCollectionDate);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    // if we don't find a record in ANALYSIS_QAEVENT (or
                    // completed date is not null) then this is already
                    // fixed
                    if (analysisQaEvent != null && analysisQaEvent.getCompletedDate() == null) {
                        AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
                        analysisQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                        analysisQaEventAction.setAction(actionForNoCollectionDate);
                        analysisQaEventAction = analysisQaEventActionDAO
                                .getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);

                        // if we found a record in ANALYSIS_QAEVENT_ACTION
                        // then this has been fixed
                        if (analysisQaEventAction == null) {
                            // insert a record in ANALYSIS_QAEVENT_ACTION
                            AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
                            analQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                            analQaEventAction.setAction(actionForNoCollectionDate);
                            analQaEventAction.setCreatedDateForDisplay(dateAsText);
                            analQaEventAction.setSysUserId(sysUserId);
                            //bugzilla 2496
                            analQaEventAction.setSystemUser(systemUser);
                            analysisQaEventActionDAO.insertData(analQaEventAction);
                        }
                        // update the found
                        // ANALYSIS_QAEVENT.COMPLETED_DATE with current
                        // date stamp
                        analysisQaEvent.setCompletedDateForDisplay(dateAsText);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }

                }

                // bugzilla 2028 QA_EVENT SAMPLETYPE
                if (typeOfSamp.getDescription().equals(SAMPLE_TYPE_NOT_GIVEN)) {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoSampleType);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    if (analysisQaEvent == null) {
                        analysisQaEvent = new AnalysisQaEvent();
                        analysisQaEvent.setAnalysis(analysis);
                        analysisQaEvent.setQaEvent(qaEventForNoSampleType);
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.insertData(analysisQaEvent);
                    } else {
                        if (analysisQaEvent.getCompletedDate() != null) {
                            analysisQaEvent.setCompletedDate(null);
                            analysisQaEvent.setSysUserId(sysUserId);
                            analysisQaEventDAO.updateData(analysisQaEvent);
                        }

                    }
                } else {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForNoSampleType);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    // if we don't find a record in ANALYSIS_QAEVENT (or
                    // completed date is not null) then this is already
                    // fixed
                    if (analysisQaEvent != null && analysisQaEvent.getCompletedDate() == null) {
                        AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
                        analysisQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                        analysisQaEventAction.setAction(actionForNoSampleType);
                        analysisQaEventAction = analysisQaEventActionDAO
                                .getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);

                        // if we found a record in ANALYSIS_QAEVENT_ACTION
                        // then this has been fixed
                        if (analysisQaEventAction == null) {
                            // insert a record in ANALYSIS_QAEVENT_ACTION
                            AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
                            analQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                            analQaEventAction.setAction(actionForNoSampleType);
                            analQaEventAction.setCreatedDateForDisplay(dateAsText);
                            analQaEventAction.setSysUserId(sysUserId);
                            //bugzilla 2496
                            analQaEventAction.setSystemUser(systemUser);
                            analysisQaEventActionDAO.insertData(analQaEventAction);
                        }
                        // update the found
                        // ANALYSIS_QAEVENT.COMPLETED_DATE with current
                        // date stamp
                        analysisQaEvent.setCompletedDateForDisplay(dateAsText);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }

                }

                // bugzilla 2028 QA_EVENT UNKNOWN SUBMITTER
                //bugzilla 2589
                if (submitterNumber
                        .equals(SystemConfiguration.getInstance().getUnknownSubmitterNumberForQaEvent())) {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    if (analysisQaEvent == null) {
                        analysisQaEvent = new AnalysisQaEvent();
                        analysisQaEvent.setAnalysis(analysis);
                        analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
                        analysisQaEvent.setCompletedDate(null);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.insertData(analysisQaEvent);
                    } else {
                        if (analysisQaEvent.getCompletedDate() != null) {
                            analysisQaEvent.setCompletedDate(null);
                            analysisQaEvent.setSysUserId(sysUserId);
                            analysisQaEventDAO.updateData(analysisQaEvent);
                        }

                    }
                } else {
                    AnalysisQaEvent analysisQaEvent = new AnalysisQaEvent();
                    analysisQaEvent.setAnalysis(analysis);
                    analysisQaEvent.setQaEvent(qaEventForUnknownSubmitter);
                    analysisQaEvent = analysisQaEventDAO
                            .getAnalysisQaEventByAnalysisAndQaEvent(analysisQaEvent);

                    // if we don't find a record in ANALYSIS_QAEVENT (or
                    // completed date is not null) then this is already
                    // fixed
                    if (analysisQaEvent != null && analysisQaEvent.getCompletedDate() == null) {
                        AnalysisQaEventAction analysisQaEventAction = new AnalysisQaEventAction();
                        analysisQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                        analysisQaEventAction.setAction(actionForUnknownSubmitter);
                        analysisQaEventAction = analysisQaEventActionDAO
                                .getAnalysisQaEventActionByAnalysisQaEventAndAction(analysisQaEventAction);

                        // if we found a record in ANALYSIS_QAEVENT_ACTION
                        // then this has been fixed
                        if (analysisQaEventAction == null) {
                            // insert a record in ANALYSIS_QAEVENT_ACTION
                            AnalysisQaEventAction analQaEventAction = new AnalysisQaEventAction();
                            analQaEventAction.setAnalysisQaEvent(analysisQaEvent);
                            analQaEventAction.setAction(actionForUnknownSubmitter);
                            analQaEventAction.setCreatedDateForDisplay(dateAsText);
                            analQaEventAction.setSysUserId(sysUserId);
                            //bugzilla 2496
                            analQaEventAction.setSystemUser(systemUser);
                            analysisQaEventActionDAO.insertData(analQaEventAction);
                        }
                        // update the found
                        // ANALYSIS_QAEVENT.COMPLETED_DATE with current
                        // date stamp
                        analysisQaEvent.setCompletedDateForDisplay(dateAsText);
                        analysisQaEvent.setSysUserId(sysUserId);
                        analysisQaEventDAO.updateData(analysisQaEvent);
                    }
                }

            }
        }

        tx.commit();
        // done updating return to menu
        forward = FWD_CLOSE;

    } catch (LIMSRuntimeException lre) {
        //bugzilla 2154
        LogEvent.logError("SampleDemographicsUpdateAction", "performAction()", lre.toString());
        tx.rollback();
        // if error then forward to fail and don't update to blank page
        // = false
        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 = testManagementForm.validate(mapping,
            // request);
            error = new ActionError("errors.OptimisticLockException", null, null);
        } else {
            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(FWD_FAIL);

    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");
    }

    return mapping.findForward(forward);
}

From source file:net.kidlogger.kidlogger.KLService.java

private void startGpsUpdates() {
    long minTime = 0;
    float minDist = 0;

    try {//from w  w w  .java  2 s .  c  o  m
        minTime = Long.parseLong(Settings.getGpsUpdatesTime(this));
        minDist = Float.parseFloat(Settings.getMinDistance(this));
    } catch (NumberFormatException e) {
        minTime = MIN * 5L;
        minDist = 20.0f;
        app.logError(CN + "startGpsUpdates", e.toString());
    }

    //List<String> locProviders = locMngr.getAllProviders();      
    locListener = new KidLocListener();

    if (locMngr.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
        locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime * MIN, minDist, locListener);
        //Log.i(CN, "GPS location");
    } else if (locMngr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
        locMngr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime * MIN, minDist, locListener);
        //Log.i(CN, "Network location");
    } else
        gpsOn = false;

    /*
    if(gpsOn)
       locMngr.removeUpdates(onLocationChange);
            
    try{
       locMngr.requestLocationUpdates(LocationManager.GPS_PROVIDER, minTime * MIN,
       minDist, onLocationChange);
       //locMngr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, minTime * MIN,
       //      minDist, onLocationChange);
       Log.i("KLS", "Min time: " + minTime + "min dist: " + minDist);
    }catch(IllegalArgumentException e){
       app.logError(CN + "startGpsUpdates", e.toString());
    }catch(SecurityException e){
       app.logError(CN + "startGpsUpdates", e.toString());
    }
    */
}

From source file:com.smartbear.jenkins.plugins.testcomplete.TcLogParser.java

public TcLogInfo parse(BuildListener listener) {
    try {//from   www  .  java 2 s.  c  o  m
        ZipFile logArchive = new ZipFile(log);

        Node descriptionTopLevelNode = NodeUtils.getRootDocumentNodeFromArchive(logArchive,
                DESCRIPTION_ENTRY_NAME);
        if (descriptionTopLevelNode == null) {
            throw new ParsingException("Unable to obtain description top-level node.");
        }

        long startTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, START_TIME_PROPERTY_NAME));
        long stopTime = Utils
                .safeConvertDate(NodeUtils.getTextProperty(descriptionTopLevelNode, STOP_TIME_PROPERTY_NAME));

        int testCount = 0;
        try {
            testCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, TEST_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int warningCount = 0;
        try {
            warningCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, WARNING_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        int errorCount = 0;
        try {
            errorCount = Integer
                    .parseInt(NodeUtils.getTextProperty(descriptionTopLevelNode, ERROR_COUNT_PROPERTY_NAME));
        } catch (NumberFormatException e) {
            // Do nothing
        }

        TcLogInfo logInfo = new TcLogInfo(startTime, stopTime, testCount, errorCount, warningCount);

        String xml = null;

        if (generateJUnitReports) {
            XMLStreamWriter xmlStreamWriter = null;
            try {
                StringWriter stringWriter = new StringWriter();
                xmlStreamWriter = XMLOutputFactory.newInstance().createXMLStreamWriter(stringWriter);
                convertToXML(logArchive, logInfo, xmlStreamWriter);
                xmlStreamWriter.flush();
                xmlStreamWriter.close();
                xmlStreamWriter = null;
                xml = stringWriter.toString();
            } catch (Exception e) {
                TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
            } finally {
                if (xmlStreamWriter != null) {
                    xmlStreamWriter.close();
                }
            }
        }

        logInfo.setXML(xml);

        return logInfo;
    } catch (Exception e) {
        TcLog.error(listener, Messages.TcTestBuilder_ExceptionOccurred(), e.toString());
        return null;
    }
}

From source file:org.etudes.util.XrefHelper.java

/**
 * If needed, import the references resource into the context in the same relative position. If we find an existing resource that matches, use it.
 * /* ww  w.  ja v  a2 s. co m*/
 * @param resourceRef
 *        the source to copy.
 * @param context
 *        The destination context.
 * @return A reference to the new or found resource, or null if it was not created.
 */
@SuppressWarnings("unchecked")
protected static Reference importResourceIfNoMatch(Reference resourceRef, String context) {
    // bypass security when reading the resource to copy
    SecurityService.pushAdvisor(new SecurityAdvisor() {
        public SecurityAdvice isAllowed(String userId, String function, String reference) {
            return SecurityAdvice.ALLOWED;
        }
    });

    try {
        // Reference does not know how to make the id from a private docs reference.
        String id = resourceRef.getId();
        if (id.startsWith("/content/")) {
            id = id.substring("/content".length());
        }

        // get the source
        ContentResource resource = ContentHostingService.getResource(id);
        String type = resource.getContentType();
        long size = resource.getContentLength();
        byte[] body = resource.getContent();

        String[] parts = StringUtil.split(id, "/");
        String relativePath = null;
        if (!"group".equals(parts[1])) {
            // for privateDocs, or an attachment, or anything other than a site's resources area, put it in the root of the new site
            relativePath = "/";
        } else {
            // the relative path and name of the source if from a site's resources area (i.e. /group/<source site>/path/b/c/name)
            relativePath = "/"
                    + ((parts.length > 4) ? (StringUtil.unsplit(parts, 3, parts.length - 4, "/") + "/") : "");
        }
        String fname = parts[parts.length - 1];
        String extension = null;
        if (fname.indexOf('.') != -1) {
            int pos = fname.lastIndexOf('.');
            extension = fname.substring(pos + 1);
            fname = fname.substring(0, pos);
        }

        int maxNum = -1;
        boolean nameInUse = false;

        // get info on everyone in the destination's relative path collection
        ContentCollection targetCollection = null;
        try {
            targetCollection = ContentHostingService.getCollection("/group/" + context + relativePath);
            List<ContentEntity> members = targetCollection.getMemberResources();
            for (ContentEntity member : members) {
                // ignore collections
                if (member instanceof ContentResource) {
                    ContentResource mr = (ContentResource) member;

                    // isolate the member's name and extension
                    String mrFname = mr.getId().substring(mr.getId().lastIndexOf('/') + 1, mr.getId().length());
                    String mrExtension = null;
                    if (mrFname.indexOf('.') != -1) {
                        int pos = mrFname.lastIndexOf('.');
                        mrExtension = mrFname.substring(pos + 1);
                        mrFname = mrFname.substring(0, pos);
                    }

                    // the extensions have to match
                    if (!StringUtil.different(extension, mrExtension, true)) {
                        // the names have to match
                        if (!StringUtil.different(fname, mrFname, true)) {
                            // the resource name is in use already
                            nameInUse = true;

                            // no extension is the "0" one.
                            int num = 0;

                            // keep track of the biggest numeric extension
                            if (num > maxNum)
                                maxNum = num;

                            // if the member 'matches' the import, use the member
                            if (matches(mr, type, size, body)) {
                                return EntityManager.newReference(mr.getReference());
                            }
                        }

                        // if the member name has a "dash-number" extension past the source name, we can still use it if it matches size and type
                        else if (mrFname.startsWith(fname + "-")) {
                            // the rest after the "-" has to be numeric
                            try {
                                int num = Integer.valueOf(mrFname.substring(fname.length() + 1));

                                // keep track of the biggest numeric extension
                                if (num > maxNum)
                                    maxNum = num;

                                // if the member 'matches' the import, use the member
                                if (matches(mr, type, size, body)) {
                                    return EntityManager.newReference(mr.getReference());
                                }
                            } catch (NumberFormatException e) {
                                // not numeric... ignore
                            }
                        }
                    }

                }
            }
        } catch (IdUnusedException e) {
            // there is no collection at the new site's relative path
        }

        // there's nothing here to use, so import it

        // adjust the fname with a "dash-number" if needed
        if ((nameInUse) && (maxNum > -1)) {
            // maxNum is the greatest numeric extension we saw in the collection for this name, so we want the next
            fname += "-" + Integer.toString(maxNum + 1);
        }

        // the new resource id
        String destinationPath = "/group/" + context + relativePath + fname
                + ((extension == null) ? "" : ("." + extension));

        // make sure to remove the reference root sakai:reference-root
        ResourcePropertiesEdit props = ContentHostingService.newResourceProperties();
        props.addAll(resource.getProperties());
        props.removeProperty("sakai:reference-root");

        // create the new resource
        ContentResource importedResource = ContentHostingService.addResource(destinationPath, type, body, props,
                0);

        // return a reference to it
        Reference reference = EntityManager.newReference(importedResource.getReference());
        return reference;
    } catch (PermissionException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (IdUnusedException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (TypeException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (ServerOverloadException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (IdInvalidException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (InconsistentException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (IdUsedException e) {
        M_log.warn("importResource: " + e.toString());
    } catch (OverQuotaException e) {
        M_log.warn("importResource: " + e.toString());
    } finally {
        SecurityService.popAdvisor();
    }

    return null;
}

From source file:org.agnitas.backend.Data.java

public void setupMailingInformations(String prefix, String status) throws Exception {
    if (prefix.equals("preview")) {
        String[] opts = status.split(",");

        if (opts.length > 0) {
            try {
                mailing_id = Long.parseLong(opts[0]);
            } catch (NumberFormatException e) {
                logging(Log.WARNING, "setup",
                        "Unparseable input string for mailing_id: \"" + opts[0] + "\": " + e.toString());
                mailing_id = 0;//from  w w w.  j ava  2  s .co  m
            }
        } else {
            mailing_id = 0;
        }
        if (mailing_id > 0) {
            try {
                company_id = dbase.queryLong("SELECT company_id FROM mailing_tbl WHERE mailing_id = :mailingID",
                        "mailingID", mailing_id);
            } catch (Exception e) {
                throw new Exception(
                        "Failed to query company_id for mailing_id " + mailing_id + ": " + e.toString());
            }
        } else {
            mailing_id = 0;
            company_id = 1;
            mailinglist_id = 1;
            try {
                if (opts.length > 1) {
                    company_id = Long.parseLong(opts[1]);
                    if (opts.length > 2) {
                        mailinglist_id = Long.parseLong(opts[2]);
                    }
                }
            } catch (NumberFormatException e) {
                logging(Log.WARNING, "setup",
                        "Unparseable input string for preview \"" + status + "\": " + e.toString());
            }
        }
        status_field = "P";
        sendtimestamp = null;
    } else
        throw new Exception("Unknown status prefix \"" + prefix + "\" encountered");
}

From source file:lu.uni.adtool.tools.Clo.java

/**
 * Class used to parse command line options. Returns true if GUI window should
 * be shown/*from www .j a va 2s . c  o m*/
 */
public boolean parse(String[] args) {
    CommandLineParser parser = new DefaultParser();
    CommandLine cmd = null;
    try {
        cmd = parser.parse(options, args);
        if (cmd.hasOption("h")) {
            help();
            return false;
        } else if (cmd.hasOption("v")) {
            version();
            return false;
        } else if (cmd.hasOption("o")) {
            this.toOpen = cmd.getOptionValues("o");
            if (this.toOpen != null && this.toOpen.length == 0) {
                this.toOpen = null;
            }
        }
        if (cmd.hasOption("i") && cmd.hasOption("x") || cmd.hasOption("i") && cmd.hasOption("d")
                && (cmd.getOptionValue("d", "0").equals("?") || cmd.getOptionValue("d", "0").equals("q"))) {
            ImportExport exporter = new ImportExport();
            if (cmd.hasOption("D")) {
                exporter.setNoDerivedValues(true);
            }
            if (cmd.hasOption("m")) {
                exporter.setMarkEditable(true);
            }
            if (cmd.hasOption("r")) {
                String r = cmd.getOptionValue("r");
                try {
                    int x = Integer.parseInt(r);
                    if (x > 0) {
                        exporter.setExportRanking(x);
                    } else {
                        System.err.println(Options.getMsg("clo.wrongrank"));
                    }
                } catch (NumberFormatException e) {
                    System.err.println(Options.getMsg("clo.wrongrank"));
                }
            }
            if (cmd.hasOption("L")) {
                exporter.setNoLabels(true);
            }
            if (cmd.hasOption("C")) {
                exporter.setNoComputedValues(true);
            }
            if (cmd.hasOption("s")) {
                String size = cmd.getOptionValue("s");
                int index = size.indexOf('x');
                if (index > 0) {
                    try {
                        int x = Integer.parseInt(size.substring(0, index));
                        int y = Integer.parseInt(size.substring(index + 1));
                        exporter.setViewPortSize(new Dimension(x, y));
                    } catch (NumberFormatException e) {
                        System.err.println(Options.getMsg("clo.wrongsize"));
                    }
                }
            }
            if (cmd.hasOption("d")) {
                String[] domainIds = cmd.getOptionValues("d");

                if (domainIds != null) {
                    // if (domainId == "?" || domainId=="q") {
                    // System.out.println(new Integer(exporter.countDomains(fileName)));
                    // return false;
                    // }
                    exporter.setExportDomainStr(domainIds);
                }
            }
            String fileName = cmd.getOptionValue("i");
            if (fileName != null && exporter.doImport(fileName)) {
                fileName = cmd.getOptionValue("x");
                if (fileName != null) {
                    exporter.doExport(fileName);
                }
            }
            return toOpen != null;
        }
        if (cmd.getOptions().length > 0) {
            System.err.println(Options.getMsg("clo.wrongCombination") + ".");
            help();
            return false;
        }
    } catch (ParseException e) {
        System.err.println(Options.getMsg("clo.parseError") + ": " + e.toString());
        help();
        return false;
    }
    return true;
}