Example usage for org.springframework.web.context WebApplicationContext getBean

List of usage examples for org.springframework.web.context WebApplicationContext getBean

Introduction

In this page you can find the example usage for org.springframework.web.context WebApplicationContext getBean.

Prototype

Object getBean(String name) throws BeansException;

Source Link

Document

Return an instance, which may be shared or independent, of the specified bean.

Usage

From source file:org.openecomp.sdc.be.filters.BasicAuthenticationFilter.java

private ConsumerBusinessLogic getConsumerBusinessLogic() {
    ServletContext context = sr.getSession().getServletContext();
    WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
    WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
    ConsumerBusinessLogic consumerBusinessLogic = webApplicationContext.getBean(ConsumerBusinessLogic.class);
    return consumerBusinessLogic;
}

From source file:org.openecomp.sdc.be.servlets.AbstractValidationsServlet.java

private void initSpringFromContext() {
    if (servletUtils == null) {
        synchronized (LOCK) {
            if (servletUtils == null) {
                ServletContext context = servletRequest.getSession().getServletContext();
                WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
                        .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
                WebApplicationContext webApplicationContext = webApplicationContextWrapper
                        .getWebAppContext(context);
                servletUtils = webApplicationContext.getBean(ServletUtils.class);
                resourceImportManager = webApplicationContext.getBean(ResourceImportManager.class);
            }// w  w w.  ja v  a 2s.  c o  m
        }
    }
}

From source file:org.openecomp.sdc.be.servlets.TypesUploadServlet.java

private <T> T initElementTypeImportManager(ServletContext context, Supplier<Class<T>> classGetter) {
    WebAppContextWrapper webApplicationContextWrapper = (WebAppContextWrapper) context
            .getAttribute(Constants.WEB_APPLICATION_CONTEXT_WRAPPER_ATTR);
    WebApplicationContext webApplicationContext = webApplicationContextWrapper.getWebAppContext(context);
    T elementTypeImortManager = webApplicationContext.getBean(classGetter.get());
    return elementTypeImortManager;
}

From source file:org.openlegacy.web.tiles.OpenLegacyTilesConfigurer.java

private String[] extractDefinitionsFromPlugin() {
    if (servletContext == null) {
        return null;
    }//from  w  w  w .j a  v  a  2 s .c om
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    PluginsRegistry pluginsRegistry = wac.getBean(PluginsRegistry.class);

    if (pluginsRegistry.isEmpty()) {
        return null;
    }

    List<String> viewResources = pluginsRegistry.getViewDeclarations();

    return viewResources.toArray(new String[] {});
}

From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java

public ActionForward issueNoteSave(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String strNote = request.getParameter("value");
    String appointmentNo = request.getParameter("appointmentNo");
    HttpSession session = request.getSession();

    String[] extNames = { "startdate", "resolutiondate", "proceduredate", "ageatonset", "problemstatus",
            "treatment", "exposuredetail", "relationship", "lifestage", "hidecpp", "problemdescription" };
    String[] extKeys = { CaseManagementNoteExt.STARTDATE, CaseManagementNoteExt.RESOLUTIONDATE,
            CaseManagementNoteExt.PROCEDUREDATE, CaseManagementNoteExt.AGEATONSET,
            CaseManagementNoteExt.PROBLEMSTATUS, CaseManagementNoteExt.TREATMENT,
            CaseManagementNoteExt.EXPOSUREDETAIL, CaseManagementNoteExt.RELATIONSHIP,
            CaseManagementNoteExt.LIFESTAGE, CaseManagementNoteExt.HIDECPP, CaseManagementNoteExt.PROBLEMDESC };

    // strNote = strNote.trim();
    logger.debug("Saving: " + strNote);
    strNote = org.apache.commons.lang.StringUtils.trimToNull(strNote);
    if (strNote == null || strNote.equals(""))
        return null;

    String providerNo = getProviderNo(request);
    if (providerNo == null) {
        providerNo = LoggedInInfo.loggedInInfo.get().loggedInProvider.getProviderNo();
    }//from   w  w  w .ja  v a 2  s  .  co m
    Provider provider = getProvider(request);
    if (provider == null) {
        provider = LoggedInInfo.loggedInInfo.get().loggedInProvider;
    }
    String userName = provider != null ? provider.getFullName() : "";

    String demo = getDemographicNo(request);

    String noteId = request.getParameter("noteId");
    logger.debug("SAVING NOTE " + noteId + " STRING: " + strNote);
    String issueChange = request.getParameter("issueChange");
    String archived = request.getParameter("archived");

    CaseManagementNote note;
    boolean newNote = false;
    // we don't want to try to remove an issue from a new note so we test here
    if (noteId.isEmpty())
        noteId = "0";

    if (noteId.equals("0")) {

        note = new CaseManagementNote();
        note.setDemographic_no(demo);
        newNote = true;
    } else {
        boolean extChanged = false;
        List<CaseManagementNoteExt> cmeList = caseManagementNoteExtDao.getExtByNote(Long.valueOf(noteId));

        extNames: for (int i = 0; i < extNames.length; i++) {
            boolean extKeyMatched = false;

            String val = request.getParameter(extNames[i]);
            for (CaseManagementNoteExt cme : cmeList) {
                if (!cme.getKeyVal().equals(extKeys[i]))
                    continue;

                if (i <= 2) {
                    if (!nullEmptyEqual(cme.getDateValueStr(), partialFullDate(val, partialDateFormat(val)))) {
                        extChanged = true;
                        break extNames;
                    }
                    val = partialDateFormat(val);
                }
                if (!nullEmptyEqual(cme.getValue(), val)) {
                    extChanged = true;
                    break extNames;
                }
                extKeyMatched = true;
                break;
            }
            if (filled(val) && !extKeyMatched) { // new ext value(s) added
                extChanged = true;
                break extNames;
            }
        }

        // if note has not changed don't save
        note = this.caseManagementMgr.getNote(noteId);
        if (strNote.equals(note.getNote()) && !issueChange.equals("true") && !extChanged
                && (archived == null || archived.equalsIgnoreCase("false")))
            return null;
    }
    note.setNote(strNote);
    note.setProviderNo(providerNo);
    note.setSigning_provider_no(providerNo);
    note.setSigned(true);

    if (provider != null)
        note.setProvider(provider);

    String logAction = new String();
    if (archived == null || archived.equalsIgnoreCase("false")) {
        note.setArchived(false);
    } else {
        note.setArchived(true);
        logger.debug("Setting archived to true");
        logAction = LogConst.ARCHIVE;
    }

    logger.debug("Note archived " + note.isArchived());
    String programId = (String) session.getAttribute("case_program_id");
    note.setProgram_no(programId);

    WebApplicationContext ctx = this.getSpringContext();

    ProgramManager programManager = (ProgramManager) ctx.getBean("programManager");
    AdmissionManager admissionManager = (AdmissionManager) ctx.getBean("admissionManager");

    String role = null;
    String team = null;

    try {
        role = String.valueOf((programManager.getProgramProvider(note.getProviderNo(), note.getProgram_no()))
                .getRole().getId());
    } catch (Throwable e) {
        logger.error("Error", e);
        role = "0";
    }

    note.setReporter_caisi_role(role);

    try {
        team = String.valueOf(
                (admissionManager.getAdmission(note.getProgram_no(), Integer.valueOf(note.getDemographic_no())))
                        .getTeamId());
    } catch (Throwable e) {
        logger.error("Error", e);
        team = "0";
    }
    note.setReporter_program_team(team);
    if (appointmentNo != null && appointmentNo.length() > 0) {
        try {
            note.setAppointmentNo(ConversionUtils.fromIntString(appointmentNo));
        } catch (NumberFormatException e) {
            logger.info("no appt no");
        }
    }
    // update note issues
    String sessionFrmName = "caseManagementEntryForm" + demo;
    CaseManagementEntryFormBean sessionFrm = (CaseManagementEntryFormBean) session.getAttribute(sessionFrmName);
    Set<CaseManagementIssue> issueSet = new HashSet<CaseManagementIssue>();
    Set<CaseManagementNote> noteSet = new HashSet<CaseManagementNote>();
    String[] issue_id = request.getParameterValues("issue_id");
    CheckBoxBean[] existingCaseIssueList = sessionFrm.getIssueCheckList();
    ArrayList<CheckBoxBean> caseIssueList = new ArrayList<CheckBoxBean>();

    // copy existing issues for sessionfrm
    for (int idx = 0; idx < existingCaseIssueList.length; ++idx) {
        caseIssueList.add(existingCaseIssueList[idx]);
    }

    // first we check if any notes have been removed
    Set<CaseManagementIssue> noteIssues = note.getIssues();
    Iterator<CaseManagementIssue> iter = noteIssues.iterator();
    CaseManagementIssue cIssue;
    boolean issueExists;
    StringBuilder issueNames = new StringBuilder();
    int j;

    // we need the defining issue as originally passed in
    String reloadQuery = request.getParameter("reloadUrl");
    String[] params = reloadQuery.split("&");
    String cppStrIssue = new String();
    for (int p = 0; p < params.length; ++p) {
        String[] keyVal = params[p].split("=");
        if (keyVal[0].equalsIgnoreCase("issue_code")) {
            cppStrIssue = keyVal[1];
            break;
        }
    }

    boolean removed = false;

    // we've removed all issues so record that
    ResourceBundle props = ResourceBundle.getBundle("oscarResources");
    if (issue_id == null) {
        while (iter.hasNext()) {
            cIssue = iter.next();
            issueNames.append(cIssue.getIssue().getDescription() + "\n");
        }

        strNote += "\n" + new SimpleDateFormat("dd-MMM-yyyy", request.getLocale()).format(new Date()) + " "
                + props.getString("oscarEncounter.removedIssue.Msg") + ":\n" + issueNames.toString();
        note.setNote(strNote);
        removed = true;
    } else {
        // check to see if we have removed any issues
        while (iter.hasNext()) {
            cIssue = iter.next();
            issueExists = false;
            for (j = 0; j < issue_id.length; ++j) {
                if (Long.parseLong(issue_id[j]) == cIssue.getIssue_id()) {
                    issueExists = true;
                    break;
                }
            }

            if (!issueExists) {
                issueNames.append(cIssue.getIssue().getDescription() + "\n");
                if (cIssue.getIssue().getCode().equalsIgnoreCase(cppStrIssue)) {
                    removed = true;
                }
            }
        }

        // if we have removed an issue add it to message body
        if (issueNames.length() > 0) {
            strNote += "\n" + new SimpleDateFormat("dd-MMM-yyyy", request.getLocale()).format(new Date()) + " "
                    + props.getString("oscarEncounter.removedIssue.Msg") + ":\n" + issueNames.toString();
            note.setNote(strNote);
        }

        for (int idx = 0; idx < issue_id.length; ++idx) {
            cIssue = this.caseManagementMgr.getIssueById(demo, issue_id[idx]);
            if (cIssue == null) {
                Issue issue = this.caseManagementMgr.getIssue(issue_id[idx]);
                cIssue = this.newIssueToCIssue(demo, issue, ConversionUtils.fromIntString(programId));
                cIssue.setNotes(noteSet);

                // we have a new issue so add it to sessionfrm list
                CheckBoxBean checkbox = new CheckBoxBean();
                checkbox.setIssue(cIssue);
                checkbox.setChecked("off");
                checkbox.setUsed(true);
                caseIssueList.add(checkbox);
            }
            issueSet.add(cIssue);

        } // end for

        CheckBoxBean[] newCheckBox = new CheckBoxBean[caseIssueList.size()];
        newCheckBox = caseIssueList.toArray(newCheckBox);
        sessionFrm.setIssueCheckList(newCheckBox);

    }
    note.setIssues(issueSet);

    // now we can update the order of the notes if necessary
    // if the note has been removed or archived we move notes up in the order
    // else we check if position has changed and move the note down
    int position = -1;
    int newPos = ConversionUtils.fromIntString(request.getParameter("position"));

    List<Issue> cppIssue = caseManagementMgr.getIssueInfoByCode(providerNo, cppStrIssue);
    List<CaseManagementNote> curCPPNotes = new ArrayList<CaseManagementNote>();
    if (cppIssue.size() > 0) {
        String[] strIssueId = { String.valueOf(cppIssue.get(0).getId()) };
        curCPPNotes = this.caseManagementMgr.getActiveNotes(demo, strIssueId);
    }

    CaseManagementNote curNote;
    long nId = Long.parseLong(noteId);
    int numNotes = curCPPNotes.size();
    // Alas we have to cycle through to make sure an ordering has been set
    // this is for legacy data
    for (int idx = 1; idx < curCPPNotes.size(); ++idx) {
        curNote = curCPPNotes.get(idx);
        if (curNote.getPosition() == 0) {
            curNote.setPosition(idx);

            if (curNote.getId() == nId) {
                note.setPosition(idx);
            }

            this.caseManagementMgr.updateNote(curNote);
        }
    }

    if (removed || note.isArchived()) {
        position = note.getPosition();
        for (CaseManagementNote c : curCPPNotes) {
            if (c.getId() == nId) {
                continue;
            } else if (position < c.getPosition()) {
                newPos = c.getPosition() - 1;
                c.setPosition(newPos);
                this.caseManagementMgr.updateNote(c);
            }
        }
    } else if ((newPos != note.getPosition() && !(newPos == numNotes && note.getPosition() == (numNotes - 1)))
            || newNote) {
        for (CaseManagementNote c : curCPPNotes) {
            if (c.getId() != nId) {
                if (newNote && c.getPosition() >= newPos) {
                    position = c.getPosition() + 1;
                    c.setPosition(position);
                    this.caseManagementMgr.updateNote(c);
                } else if ((!newNote && newPos < note.getPosition()) && c.getPosition() >= newPos
                        && c.getPosition() < note.getPosition()) {
                    position = c.getPosition() + 1;
                    c.setPosition(position);
                    this.caseManagementMgr.updateNote(c);
                } else if ((!newNote && newPos > note.getPosition()) && c.getPosition() <= newPos
                        && c.getPosition() > note.getPosition()) {
                    position = c.getPosition() - 1;
                    c.setPosition(position);
                    this.caseManagementMgr.updateNote(c);
                }

            }
        }

        if (newPos == numNotes && !newNote) {
            --newPos;
        }
        note.setPosition(newPos);
    }

    /*
     * Remove linked issue(s) and insert message into note
     *
     * if( removeIssue.equals("true") ) { issue_id = request.getParameterValues("issue_id"); issueSet = note.getIssues(); StringBuilder issueNames = new StringBuilder(); for( int idx = 0; idx < issue_id.length; ++idx ) { for(Iterator iter =
     * issueSet.iterator();iter.hasNext();) { CaseManagementIssue cIssue = (CaseManagementIssue)iter.next(); if( cIssue.getIssue_id() == Long.parseLong(issue_id[idx]) ) { issueSet.remove(cIssue); issueNames.append(cIssue.getIssue().getDescription() +
     * "\n"); break; } } } //Force hibernate to save rather than update Set tmpIssues = new HashSet(issueSet); note.setIssues(tmpIssues); strNote += "\n" + new SimpleDateFormat("dd-MMM-yyyy").format(new Date()) + " Removed following issue(s):\n" +
     * issueNames.toString(); note.setNote(strNote); }
     */

    int revision;

    if (note.getRevision() != null) {
        revision = ConversionUtils.fromIntString(note.getRevision());
        ++revision;
    } else
        revision = 1;

    note.setRevision(String.valueOf(revision));
    Date now = new Date();
    if (note.getObservation_date() == null) {
        note.setObservation_date(now);
    }

    note.setUpdate_date(now);
    if (note.getCreate_date() == null)
        note.setCreate_date(now);

    /* save note including add signature */
    String lastSavedNoteString = (String) session.getAttribute("lastSavedNoteString");
    String roleName = caseManagementMgr.getRoleName(providerNo, note.getProgram_no());
    CaseManagementCPP cpp = this.caseManagementMgr.getCPP(demo);
    if (cpp == null) {
        cpp = new CaseManagementCPP();
        cpp.setDemographic_no(demo);
    }
    cpp = copyNote2cpp(cpp, note);
    String savedStr = caseManagementMgr.saveNote(cpp, note, providerNo, userName, lastSavedNoteString,
            roleName);
    addNewNoteLink(note.getId());
    logger.debug("Saved note " + savedStr);
    caseManagementMgr.saveCPP(cpp, providerNo);
    /* remember the str written into echart */
    session.setAttribute("lastSavedNoteString", savedStr);

    /* save extra fields */
    CaseManagementNoteExt cme = new CaseManagementNoteExt();
    cme.setNoteId(note.getId());
    for (int i = 0; i < extNames.length; i++) {
        String val = request.getParameter(extNames[i]);
        if (filled(val)) {
            cme.setKeyVal(extKeys[i]);
            cme.setDateValue((Date) null);
            cme.setValue(null);
            if (i <= 2) {
                if (writePartialDate(val, cme))
                    caseManagementMgr.saveNoteExt(cme);
            } else {
                cme.setValue(val);
                caseManagementMgr.saveNoteExt(cme);
            }
        }
    }

    /* Save annotation */

    String attrib_name = request.getParameter("annotation_attrib");
    CaseManagementNote cmn = (CaseManagementNote) session.getAttribute(attrib_name);
    if (cmn != null) {
        // new annotation created and got it in session attribute

        caseManagementMgr.saveNoteSimple(cmn);
        CaseManagementNoteLink cml = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                note.getId(), cmn.getId());
        caseManagementMgr.saveNoteLink(cml);
        LogAction.addLog(providerNo, LogConst.ANNOTATE, LogConst.CON_CME_NOTE, String.valueOf(cmn.getId()),
                request.getRemoteAddr(), demo, cmn.getNote());
        session.removeAttribute(attrib_name);

    }
    if (!noteId.equals("0")) {
        // Not a new note, look for old annotation

        CaseManagementNoteLink cml_anno = null;
        CaseManagementNoteLink cml_dump = null;
        List<CaseManagementNoteLink> cmll = caseManagementMgr
                .getLinkByTableIdDesc(CaseManagementNoteLink.CASEMGMTNOTE, Long.valueOf(noteId));
        for (CaseManagementNoteLink link : cmll) {
            CaseManagementNote cmmn = caseManagementMgr.getNote(link.getNoteId().toString());
            if (cmmn == null)
                continue;

            if (cmmn.getNote().startsWith("imported.cms4.2011.06")) {
                if (cml_dump == null)
                    cml_dump = link;
            } else {
                if (cml_anno == null)
                    cml_anno = link;
            }
            if (cml_anno != null && cml_dump != null)
                break;
        }

        if (cml_anno != null) {// old annotation exists - create new link
            CaseManagementNoteLink cml_n = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                    note.getId(), cml_anno.getNoteId());
            caseManagementMgr.saveNoteLink(cml_n);
        }
        if (cml_dump != null) {// old dump exists - create new link
            CaseManagementNoteLink cml_n = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                    note.getId(), cml_dump.getNoteId());
            caseManagementMgr.saveNoteLink(cml_n);
        }
    }
    caseManagementMgr.getEditors(note);

    if (newNote) {
        logAction = LogConst.ADD;
    } else if (note.isArchived()) {
        logAction = LogConst.ARCHIVE;
    } else {
        logAction = LogConst.UPDATE;
    }

    LogAction.addLog((String) session.getAttribute("user"), logAction, LogConst.CON_CME_NOTE,
            String.valueOf(note.getId()), request.getRemoteAddr(), demo, note.getAuditString());

    String f = request.getParameter("forward");
    if (f != null && f.equals("none")) {
        response.getWriter().println(note.getId());
        return null;
    }

    ActionForward forward = mapping.findForward("listCPPNotes");
    StringBuilder path = new StringBuilder(forward.getPath());
    path.append("?" + reloadQuery);
    return new ActionForward(path.toString());
}

From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java

private long noteSave(CaseManagementEntryFormBean cform, HttpServletRequest request) throws Exception {
    WebApplicationContext ctx = getSpringContext();
    ProgramManager programManager = (ProgramManager) ctx.getBean("programManager");
    AdmissionManager admissionManager = (AdmissionManager) ctx.getBean("admissionManager");
    HttpSession session = request.getSession();

    // we don't want to save empty notes!

    String noteTxt = cform.getCaseNote_note();
    noteTxt = org.apache.commons.lang.StringUtils.trimToNull(noteTxt);
    if (noteTxt == null || noteTxt.equals(""))
        return -1;

    String demo = getDemographicNo(request);

    String sessionFrmName = "caseManagementEntryForm" + demo;
    CaseManagementEntryFormBean sessionFrm = (CaseManagementEntryFormBean) session.getAttribute(sessionFrmName);

    CaseManagementNote note = sessionFrm.getCaseNote();
    Long old_note_id = note.getId(); // saved for use with annotation

    note.setNote(noteTxt);/*from   w  w w. j  a  va2 s .  com*/

    String providerNo = getProviderNo(request);
    Provider provider = getProvider(request);
    String userName = provider != null ? provider.getFullName() : "";

    CaseManagementCPP cpp = this.caseManagementMgr.getCPP(demo);
    if (cpp == null) {
        cpp = new CaseManagementCPP();
        cpp.setDemographic_no(demo);
    }

    boolean inCaisi = OscarProperties.getInstance().isCaisiLoaded();

    String lastSavedNoteString = (String) session.getAttribute("lastSavedNoteString");

    // bug fix - encounter type was not being updated.
    String encounterType = request.getParameter("caseNote.encounter_type");
    if (encounterType != null) {
        note.setEncounter_type(encounterType);
    }

    String hourOfEncounterTime = request.getParameter("hourOfEncounterTime");
    if (hourOfEncounterTime != null && hourOfEncounterTime != "") {
        note.setHourOfEncounterTime(Integer.valueOf(hourOfEncounterTime));
    }

    String minuteOfEncounterTime = request.getParameter("minuteOfEncounterTime");
    if (minuteOfEncounterTime != null && minuteOfEncounterTime != "") {
        note.setMinuteOfEncounterTime(Integer.valueOf(minuteOfEncounterTime));
    }

    String hourOfEncTransportationTime = request.getParameter("hourOfEncTransportationTime");
    if (hourOfEncTransportationTime != null && hourOfEncTransportationTime != "") {
        note.setHourOfEncTransportationTime(Integer.valueOf(hourOfEncTransportationTime));
    }

    String minuteOfEncTransportationTime = request.getParameter("minuteOfEncTransportationTime");
    if (minuteOfEncTransportationTime != null && minuteOfEncTransportationTime != "") {
        note.setMinuteOfEncTransportationTime(Integer.valueOf(minuteOfEncTransportationTime));
    }

    String sign = request.getParameter("sign");
    if (sign == null) {
        note.setSigning_provider_no("");
        note.setSigned(false);
        sessionFrm.setSign("off");
    } else if (sign.equalsIgnoreCase("persist")) {

        if (note.isSigned()) {
            note.setSigning_provider_no(providerNo);
            note.setSigned(true);
        } else {
            note.setSigning_provider_no("");
            note.setSigned(false);
            sessionFrm.setSign("off");
        }
    } else if (sign.equalsIgnoreCase("on")) {
        note.setSigning_provider_no(providerNo);
        note.setSigned(true);
    } else {
        note.setSigning_provider_no("");
        note.setSigned(false);
        sessionFrm.setSign("off");
    }

    note.setProviderNo(providerNo);
    if (provider != null)
        note.setProvider(provider);

    String role = null;
    String team = null;

    // if this is an update, don't overwrite the program id
    if (note.getProgram_no() == null || note.getProgram_no().equals("") || !note.getProgram_no().equals("")) {
        String programId = (String) session.getAttribute("case_program_id");
        note.setProgram_no(programId);
    }

    try {
        role = String.valueOf((programManager.getProgramProvider(note.getProviderNo(), note.getProgram_no()))
                .getRole().getId());
    } catch (Throwable e) {
        role = "0";
    }
    /*
     * if(session.getAttribute("archiveView")!="true") note.setReporter_caisi_role(role); else note.setReporter_caisi_role("1");
     */
    note.setReporter_caisi_role(role);

    try {
        Admission admission = admissionManager.getAdmission(note.getProgram_no(),
                Integer.valueOf(note.getDemographic_no()));
        if (admission != null) {
            team = String.valueOf(admission.getTeamId());
        } else {
            team = "0";
        }
    } catch (Throwable e) {
        logger.error("Error", e);
        team = "0";
    }
    note.setReporter_program_team(team);

    /* get the checked issue save into note */
    // this goes into the database casemgmt_issue table
    List<CaseManagementIssue> issuelist = new ArrayList<CaseManagementIssue>();

    CheckBoxBean[] checkedlist = sessionFrm.getIssueCheckList();

    // this gets attached to the CaseManagementNote object
    Set<CaseManagementIssue> issueset = new HashSet<CaseManagementIssue>();
    // wherever this is populated, it's not here...
    Set<CaseManagementNote> noteSet = new HashSet<CaseManagementNote>();
    String ongoing = new String();
    Boolean useNewCaseMgmt = Boolean.valueOf((String) session.getAttribute("newCaseManagement"));
    if (useNewCaseMgmt) {
        ongoing = saveCheckedIssues_newCme(request, demo, note, issuelist, checkedlist, issueset, noteSet,
                ongoing);
    } else {
        ongoing = saveCheckedIssues_oldCme(request, demo, issuelist, checkedlist, issueset, noteSet, ongoing);
    }

    sessionFrm.setIssueCheckList(checkedlist);
    note.setIssues(issueset);

    /* remove signature and the related issues from note */
    String noteString = note.getNote();
    // noteString = removeSignature(noteString);
    noteString = removeCurrentIssue(noteString);
    note.setNote(noteString);

    /* add issues into notes */
    String includeIssue = request.getParameter("includeIssue");
    if (includeIssue == null || !includeIssue.equals("on")) {
        /* set includeissue in note */
        note.setIncludeissue(false);
        sessionFrm.setIncludeIssue("off");
    } else {
        note.setIncludeissue(true);
        /* add the related issues to note */

        String issueString = new String();
        issueString = createIssueString(issueset);
        // insert the string before signiture

        int index = noteString.indexOf("\n[[");
        if (index >= 0) {
            String begString = noteString.substring(0, index);
            String endString = noteString.substring(index + 1);
            note.setNote(begString + issueString + endString);
        } else {
            note.setNote(noteString + issueString);
        }
    }

    /* save all issue changes for demographic */
    caseManagementMgr.saveAndUpdateCaseIssues(issuelist);
    if (inCaisi)
        cpp.setOngoingConcerns(ongoing);

    // update appointment and add verify message to note if verified
    String strBeanName = "casemgmt_oscar_bean" + demo;
    EctSessionBean sessionBean = (EctSessionBean) session.getAttribute(strBeanName);
    String verify = request.getParameter("verify");
    OscarAppointmentDao appointmentDao = (OscarAppointmentDao) SpringUtils.getBean("oscarAppointmentDao");

    Date now = new Date();
    String roleName = caseManagementMgr.getRoleName(providerNo, note.getProgram_no());

    if (verify != null && verify.equalsIgnoreCase("on")) {
        String message = caseManagementMgr.getSignature(providerNo, userName, roleName, request.getLocale(),
                caseManagementMgr.SIGNATURE_VERIFY);

        String n = note.getNote() + "\n" + message;
        note.setNote(n);

        // only update appt if there is one
        if (sessionBean.appointmentNo != null
                && !(sessionBean.appointmentNo.equals("") || sessionBean.appointmentNo.equals("0"))) {
            //String apptStatus = updateApptStatus(sessionBean.status, "verify");            
            Appointment appointment = appointmentDao
                    .find(ConversionUtils.fromIntString(sessionBean.appointmentNo));
            appointmentArchiveDao.archiveAppointment(appointment);
            String apptStatus = updateApptStatus(appointment.getStatus(), "verify");
            appointment.setStatus(apptStatus);
            appointment.setLastUpdateUser(providerNo);
            appointmentDao.merge(appointment);
        }

    } else if (note.isSigned()) {
        String message = caseManagementMgr.getSignature(providerNo, userName, roleName, request.getLocale(),
                caseManagementMgr.SIGNATURE_SIGNED);

        String n = note.getNote() + "\n" + message;
        note.setNote(n);

        // only update appt if there is one
        if (sessionBean.appointmentNo != null
                && !(sessionBean.appointmentNo.equals("") || sessionBean.appointmentNo.equals("0"))) {
            //String apptStatus = updateApptStatus(sessionBean.status, "sign");
            Appointment appointment = appointmentDao
                    .find(ConversionUtils.fromIntString(sessionBean.appointmentNo));
            appointmentArchiveDao.archiveAppointment(appointment);
            String apptStatus = updateApptStatus(appointment.getStatus(), "sign");
            appointment.setStatus(apptStatus);
            appointment.setLastUpdateUser(providerNo);
            appointmentDao.merge(appointment);
        }
    }

    // PLACEHOLDER FOR DX CHECK
    /*
     * If an issue is checked, new , and certain - we want to check dx associations. if found in dx associations. we want to make an entry into dx.
     */
    if (note.isSigned()) {
        for (CaseManagementIssue cmIssue : issueset) {
            if (cmIssue.isCertain()) {
                DxAssociation assoc = dxDao.findAssociation(cmIssue.getIssue().getType(),
                        cmIssue.getIssue().getCode());
                if (assoc != null) {
                    // we found a match. Let's add them to registry
                    this.caseManagementMgr.saveToDx(getDemographicNo(request), assoc.getDxCode(),
                            assoc.getDxCodeType(), true);

                }
            }
        }
    }

    /*
     * if provider is a doctor or nurse,get all major and resolved medical issue for demograhhic and append them to CPP medical history
     */
    if (inCaisi) {
        /* get access right */
        List accessRight = caseManagementMgr.getAccessRight(providerNo, getDemographicNo(request),
                (String) session.getAttribute("case_program_id"));
        setCPPMedicalHistory(cpp, providerNo, accessRight);
        cpp.setUpdate_date(now);
        caseManagementMgr.saveCPP(cpp, providerNo);
    }

    // update password
    String passwd = cform.getCaseNote().getPassword();
    if (passwd != null && passwd.trim().length() > 0) {
        note.setPassword(passwd);
        note.setLocked(true);
    }

    int revision;

    if (note.getRevision() != null) {
        revision = ConversionUtils.fromIntString(note.getRevision());
        ++revision;
    } else
        revision = 1;

    note.setRevision(String.valueOf(revision));

    String observationDate = cform.getObservation_date();
    ResourceBundle props = ResourceBundle.getBundle("oscarResources", request.getLocale());
    if (observationDate != null && !observationDate.equals("")) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy H:mm", request.getLocale());
        Date dateObserve = formatter.parse(observationDate);
        if (dateObserve.getTime() > now.getTime()) {
            request.setAttribute("DateError", props.getString("oscarEncounter.futureDate.Msg"));
            note.setObservation_date(now);
        } else
            note.setObservation_date(dateObserve);
    } else if (note.getObservation_date() == null) {
        note.setObservation_date(now);
    }

    note.setUpdate_date(now);
    boolean newNote = false;
    if (note.getCreate_date() == null) {
        note.setCreate_date(now);
        newNote = true;
    }

    // Checks whether the user can set the program via the UI - if so, make sure that they can't screw it up if they do
    if (OscarProperties.getInstance().getBooleanProperty("note_program_ui_enabled", "true")) {
        String noteProgramNo = request.getParameter("_note_program_no");
        String noteRoleId = request.getParameter("_note_role_id");

        if (noteProgramNo != null && noteRoleId != null && noteProgramNo.trim().length() > 0
                && noteRoleId.trim().length() > 0) {
            if (noteProgramNo.equalsIgnoreCase("-2") || noteRoleId.equalsIgnoreCase("-2")) {
                throw new Exception(
                        "Patient is not admitted to any programs user has access to. [roleId=-2, programNo=-2]");
            } else if (!noteProgramNo.equalsIgnoreCase("-1") && !noteRoleId.equalsIgnoreCase("-1")) {
                note.setProgram_no(noteProgramNo);
                note.setReporter_caisi_role(noteRoleId);
            }
        } else {
            throw new Exception("Missing role id or program number. [roleId=" + noteRoleId + ", programNo="
                    + noteProgramNo + "]");
        }
    }

    if (sessionBean.appointmentNo != null && sessionBean.appointmentNo.length() > 0) {
        note.setAppointmentNo(ConversionUtils.fromIntString(sessionBean.appointmentNo));
    }

    /* save note including add signature */
    String savedStr = caseManagementMgr.saveNote(cpp, note, providerNo, userName, lastSavedNoteString,
            roleName);
    addNewNoteLink(note.getId());
    /* remember the str written into echart */
    session.setAttribute("lastSavedNoteString", savedStr);
    caseManagementMgr.getEditors(note);
    cform.setCaseNote(note);

    try {
        this.caseManagementMgr.deleteTmpSave(providerNo, note.getDemographic_no(), note.getProgram_no());
    } catch (Throwable e) {
        logger.warn("warn", e);
    }

    /* Save annotation */

    String attrib_name = request.getParameter("annotation_attribname");
    CaseManagementNote cmn = (CaseManagementNote) session.getAttribute(attrib_name);
    if (cmn != null) {
        // new annotation created and got it in session attribute

        caseManagementMgr.saveNoteSimple(cmn);
        CaseManagementNoteLink cml = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                note.getId(), cmn.getId());
        caseManagementMgr.saveNoteLink(cml);
        LogAction.addLog(providerNo, LogConst.ANNOTATE, LogConst.CON_CME_NOTE, String.valueOf(cmn.getId()),
                request.getRemoteAddr(), demo, cmn.getNote());
        session.removeAttribute(attrib_name);

    }
    if (old_note_id != null) {
        // Not a new note, look for old annotation

        CaseManagementNoteLink cml_anno = null;
        CaseManagementNoteLink cml_dump = null;
        List<CaseManagementNoteLink> cmll = caseManagementMgr
                .getLinkByTableIdDesc(CaseManagementNoteLink.CASEMGMTNOTE, old_note_id);
        for (CaseManagementNoteLink link : cmll) {
            CaseManagementNote cmmn = caseManagementMgr.getNote(link.getNoteId().toString());
            if (cmmn == null)
                continue;

            if (cmmn.getNote().startsWith("imported.cms4.2011.06")) {
                if (cml_dump == null)
                    cml_dump = link;
            } else {
                if (cml_anno == null)
                    cml_anno = link;
            }
            if (cml_anno != null && cml_dump != null)
                break;
        }

        if (cml_anno != null) {// old annotation exists - create new link
            CaseManagementNoteLink cml_n = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                    note.getId(), cml_anno.getNoteId());
            caseManagementMgr.saveNoteLink(cml_n);
        }
        if (cml_dump != null) {// old dump exists - create new link
            CaseManagementNoteLink cml_n = new CaseManagementNoteLink(CaseManagementNoteLink.CASEMGMTNOTE,
                    note.getId(), cml_dump.getNoteId());
            caseManagementMgr.saveNoteLink(cml_n);
        }
    }

    String logAction;
    if (newNote) {
        logAction = LogConst.ADD;
    } else {
        logAction = LogConst.UPDATE;
    }
    LogAction.addLog((String) session.getAttribute("user"), logAction, LogConst.CON_CME_NOTE,
            "" + Long.valueOf(note.getId()).intValue(), request.getRemoteAddr(), demo, note.getAuditString());

    return note.getId();
}

From source file:org.oscarehr.casemgmt.web.CaseManagementEntryAction.java

public ActionForward ajaxsave(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    if (session.getAttribute("userrole") == null)
        return mapping.findForward("expired");

    String noteTxt = request.getParameter("noteTxt");
    noteTxt = org.apache.commons.lang.StringUtils.trimToNull(noteTxt);
    if (noteTxt == null || noteTxt.equals(""))
        return null;

    logger.debug("Saving Note" + request.getParameter("nId"));
    logger.debug("Text -- " + noteTxt);
    String demo = getDemographicNo(request);
    String providerNo = getProviderNo(request);
    Provider provider = getProvider(request);

    CaseManagementNote note;/*from  w w  w. ja v a  2s. c om*/
    String history;
    String noteId = request.getParameter("nId");
    boolean newNote;
    Date now = new Date();
    if (noteId.substring(0, 1).equals("0")) {
        note = new CaseManagementNote();
        note.setDemographic_no(demo);
        history = new String();
        newNote = true;
    } else {
        note = this.caseManagementMgr.getNote(request.getParameter("nId"));
        history = note.getHistory();
        history = "---------History Record---------" + history;
        newNote = false;
    }

    String observationDate = request.getParameter("obsDate");
    ResourceBundle props = ResourceBundle.getBundle("oscarResources");
    if (observationDate != null && !observationDate.equals("")) {
        SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy H:mm", request.getLocale());
        Date dateObserve = formatter.parse(observationDate);
        if (dateObserve.getTime() > now.getTime()) {
            request.setAttribute("DateError", props.getString("oscarEncounter.futureDate.Msg"));
            note.setObservation_date(now);
        } else
            note.setObservation_date(dateObserve);
    } else if (note.getObservation_date() == null) {
        note.setObservation_date(now);
    }

    history = noteTxt + "[[" + now + "]]" + history;
    note.setNote(noteTxt);
    note.setHistory(history);

    if (note.isSigned()) {
        note.setSigning_provider_no(providerNo);
        note.setSigned(true);
    } else {
        note.setSigning_provider_no("");
        note.setSigned(false);
    }

    note.setProviderNo(providerNo);
    if (provider != null)
        note.setProvider(provider);

    String programId = (String) session.getAttribute("case_program_id");
    note.setProgram_no(programId);

    WebApplicationContext ctx = this.getSpringContext();
    ProgramManager programManager = (ProgramManager) ctx.getBean("programManager");
    AdmissionManager admissionManager = (AdmissionManager) ctx.getBean("admissionManager");

    String role = null;
    try {
        role = String.valueOf((programManager.getProgramProvider(note.getProviderNo(), note.getProgram_no()))
                .getRole().getId());
    } catch (Throwable e) {
        logger.error("Error", e);
        role = "0";
    }

    note.setReporter_caisi_role(role);

    String team = null;
    try {
        team = String.valueOf(
                (admissionManager.getAdmission(note.getProgram_no(), Integer.valueOf(note.getDemographic_no())))
                        .getTeamId());
    } catch (Throwable e) {
        logger.error("Error", e);
        team = "0";
    }

    note.setReporter_program_team(team);

    String sessionName = "caseManagementEntryForm" + demo;
    CaseManagementEntryFormBean sessionFrm = (CaseManagementEntryFormBean) session.getAttribute(sessionName);
    List<CaseManagementIssue> issuelist = new ArrayList<CaseManagementIssue>();
    Set<CaseManagementIssue> issueset = new HashSet<CaseManagementIssue>();
    Set<CaseManagementNote> noteSet = new HashSet<CaseManagementNote>();

    int numIssues = ConversionUtils.fromIntString(request.getParameter("numIssues"));
    // CaseManagementEntryFormBean cform = (CaseManagementEntryFormBean) form;

    CheckBoxBean[] checkedlist = sessionFrm.getIssueCheckList();
    for (int i = 0; i < numIssues; i++) {
        String ischecked = request.getParameter("issue" + i);
        if (ischecked != null && ischecked.equalsIgnoreCase("on")) {
            checkedlist[i].setChecked("on");
            CaseManagementIssue iss = checkedlist[i].getIssue();
            iss.setNotes(noteSet);
            issueset.add(checkedlist[i].getIssue());
        } else {
            checkedlist[i].setChecked("off");
        }
        issuelist.add(checkedlist[i].getIssue());
    }

    note.setIssues(issueset);
    note.setIncludeissue(false);
    caseManagementMgr.saveAndUpdateCaseIssues(issuelist);
    sessionFrm.setIssueCheckList(checkedlist);

    int revision;

    if (note.getRevision() != null) {
        revision = ConversionUtils.fromIntString(note.getRevision());
        ++revision;
    } else
        revision = 1;

    note.setRevision(String.valueOf(revision));

    note.setUpdate_date(now);
    if (note.getCreate_date() == null)
        note.setCreate_date(now);

    note.setEncounter_type(request.getParameter("encType"));

    String hourOfEncounterTime = request.getParameter("hourOfEncounterTime");
    if (hourOfEncounterTime != null) {
        note.setHourOfEncounterTime(Integer.valueOf(hourOfEncounterTime));
    }
    String minuteOfEncounterTime = request.getParameter("minuteOfEncounterTime");
    if (minuteOfEncounterTime != null) {
        note.setMinuteOfEncounterTime(Integer.valueOf(minuteOfEncounterTime));
    }
    String hourOfEncTransportationTime = request.getParameter("hourOfEncTransportationTime");
    if (minuteOfEncounterTime != null) {
        note.setHourOfEncTransportationTime(Integer.valueOf(hourOfEncTransportationTime));
    }
    String minuteOfEncTransportationTime = request.getParameter("minuteOfEncTransportationTime");
    if (minuteOfEncounterTime != null) {
        note.setMinuteOfEncTransportationTime(Integer.valueOf(minuteOfEncTransportationTime));
    }

    // check if previous note is doc note.

    Long prevNoteId = note.getId();

    this.caseManagementMgr.saveNoteSimple(note);
    this.caseManagementMgr.getEditors(note);

    if (prevNoteId != null) {
        addNewNoteLink(prevNoteId);
    }

    try {
        this.caseManagementMgr.deleteTmpSave(providerNo, note.getDemographic_no(), note.getProgram_no());
    } catch (Throwable e) {
        logger.warn("Warning", e);
    }

    session.setAttribute(sessionName, sessionFrm);
    CaseManagementEntryFormBean newform = new CaseManagementEntryFormBean();
    newform.setCaseNote(note);
    newform.setIssueCheckList(checkedlist);
    request.setAttribute("caseManagementEntryForm", newform);
    String varName = "newNote";
    session.setAttribute(varName, false);
    request.setAttribute("ajaxsave", note.getId());
    request.setAttribute("origNoteId", noteId);

    String logAction;
    if (newNote) {
        logAction = LogConst.ADD;
    } else {
        logAction = LogConst.UPDATE;
    }

    LogAction.addLog((String) session.getAttribute("user"), logAction, LogConst.CON_CME_NOTE,
            String.valueOf(note.getId()), request.getRemoteAddr(), demo, note.getAuditString());

    return mapping.findForward("issueList_ajax");
    /*
     * CaseManagementEntryFormBean cform = (CaseManagementEntryFormBean) form;
     *
     * String oldId = cform.getCaseNote().getId() == null ? request.getParameter("newNoteIdx") : String.valueOf(cform.getCaseNote().getId()); long newId = noteSave(cform, request);
     *
     * if( newId > -1 ) { log.debug("OLD ID " + oldId + " NEW ID " + String.valueOf(newId)); cform.setMethod("view"); session.setAttribute("newNote", false); session.setAttribute("caseManagementEntryForm", cform);
     * request.setAttribute("caseManagementEntryForm", cform); request.setAttribute("ajaxsave", newId); request.setAttribute("origNoteId", oldId); return mapping.findForward("issueList_ajax"); }
     *
     * return null;
     */
}

From source file:org.oscarehr.document.web.ManageDocumentAction.java

private void saveDocNote(final HttpServletRequest request, String docDesc, String demog, String documentId) {

    Date now = EDocUtil.getDmsDateTimeAsDate();
    // String docDesc=d.getDocdesc();
    CaseManagementNote cmn = new CaseManagementNote();
    cmn.setUpdate_date(now);//ww  w . ja v a  2 s  . com
    cmn.setObservation_date(now);
    cmn.setDemographic_no(demog);
    HttpSession se = request.getSession();
    String user_no = (String) se.getAttribute("user");
    String prog_no = new EctProgram(se).getProgram(user_no);
    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(se.getServletContext());
    CaseManagementManager cmm = (CaseManagementManager) ctx.getBean("caseManagementManager");
    cmn.setProviderNo("-1");// set the provider no to be -1 so the editor appear as 'System'.
    Provider provider = EDocUtil.getProvider(user_no);
    String provFirstName = "";
    String provLastName = "";
    if (provider != null) {
        provFirstName = provider.getFirstName();
        provLastName = provider.getLastName();
    }
    String strNote = "Document" + " " + docDesc + " " + "created at " + now + " by " + provFirstName + " "
            + provLastName + ".";

    cmn.setNote(strNote);
    cmn.setSigned(true);
    cmn.setSigning_provider_no("-1");
    cmn.setProgram_no(prog_no);

    SecRoleDao secRoleDao = (SecRoleDao) SpringUtils.getBean("secRoleDao");
    SecRole doctorRole = secRoleDao.findByName("doctor");
    cmn.setReporter_caisi_role(doctorRole.getId().toString());

    cmn.setReporter_program_team("0");
    cmn.setPassword("NULL");
    cmn.setLocked(false);
    cmn.setHistory(strNote);
    cmn.setPosition(0);
    cmm.saveNoteSimple(cmn);
    // Add a noteLink to casemgmt_note_link
    CaseManagementNoteLink cmnl = new CaseManagementNoteLink();
    cmnl.setTableName(CaseManagementNoteLink.DOCUMENT);
    cmnl.setTableId(Long.parseLong(documentId));
    cmnl.setNoteId(Long.parseLong(EDocUtil.getLastNoteId()));
    EDocUtil.addCaseMgmtNoteLink(cmnl);
}

From source file:org.oscarehr.document.web.SplitDocumentAction.java

public ActionForward split(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) {/*from  w w  w  . j av a2 s.  c  o  m*/
    String docNum = request.getParameter("document");
    String[] commands = request.getParameterValues("page[]");
    String queueId = request.getParameter("queueID");

    LoggedInInfo loggedInInfo = LoggedInInfo.getLoggedInInfoFromSession(request);
    String providerNo = loggedInInfo.getLoggedInProviderNo();

    Document doc = documentDao.getDocument(docNum);

    String docdownload = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR");

    String newFilename = doc.getDocfilename();

    FileInputStream input = null;
    PDDocument pdf = null;
    PDDocument newPdf = null;

    try {

        input = new FileInputStream(docdownload + doc.getDocfilename());
        PDFParser parser = new PDFParser(input);
        parser.parse();
        pdf = parser.getPDDocument();

        newPdf = new PDDocument();

        List pages = pdf.getDocumentCatalog().getAllPages();

        if (commands != null) {
            for (String c : commands) {
                String[] command = c.split(",");
                int pageNum = Integer.parseInt(command[0]);
                int rotation = Integer.parseInt(command[1]);

                PDPage p = (PDPage) pages.get(pageNum - 1);
                p.setRotation(rotation);

                newPdf.addPage(p);
            }

        }

        //newPdf.save(docdownload + newFilename);

        if (newPdf.getNumberOfPages() > 0) {

            EDoc newDoc = new EDoc("", "", newFilename, "", providerNo, doc.getDoccreator(), "", 'A',
                    DateFormatUtils.format(new Date(), "yyyy-MM-dd"), "", "", "demographic", "-1", 0);
            newDoc.setDocPublic("0");
            newDoc.setContentType("application/pdf");
            newDoc.setNumberOfPages(newPdf.getNumberOfPages());

            String newDocNo = EDocUtil.addDocumentSQL(newDoc);

            newPdf.save(docdownload + newDoc.getFileName());
            newPdf.close();

            WebApplicationContext ctx = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getSession().getServletContext());
            ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx
                    .getBean("providerInboxRoutingDAO");
            providerInboxRoutingDao.addToProviderInbox("0", Integer.parseInt(newDocNo), "DOC");

            List<ProviderInboxItem> routeList = providerInboxRoutingDao
                    .getProvidersWithRoutingForDocument("DOC", Integer.parseInt(docNum));
            for (ProviderInboxItem i : routeList) {
                providerInboxRoutingDao.addToProviderInbox(i.getProviderNo(), Integer.parseInt(newDocNo),
                        "DOC");
            }

            providerInboxRoutingDao.addToProviderInbox(providerNo, Integer.parseInt(newDocNo), "DOC");

            QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx
                    .getBean("queueDocumentLinkDAO");
            Integer qid = queueId == null ? 1 : Integer.parseInt(queueId);
            Integer did = Integer.parseInt(newDocNo.trim());
            queueDocumentLinkDAO.addActiveQueueDocumentLink(qid, did);

            ProviderLabRoutingDao providerLabRoutingDao = (ProviderLabRoutingDao) SpringUtils
                    .getBean("providerLabRoutingDao");

            List<ProviderLabRoutingModel> result = providerLabRoutingDao
                    .getProviderLabRoutingDocuments(Integer.parseInt(docNum));
            if (!result.isEmpty()) {
                new ProviderLabRouting().route(newDocNo, result.get(0).getProviderNo(), "DOC");
            }

            PatientLabRoutingDao patientLabRoutingDao = (PatientLabRoutingDao) SpringUtils
                    .getBean("patientLabRoutingDao");
            List<PatientLabRouting> result2 = patientLabRoutingDao
                    .findDocByDemographic(Integer.parseInt(docNum));

            if (!result2.isEmpty()) {
                PatientLabRouting newPatientRoute = new PatientLabRouting();

                newPatientRoute.setDemographicNo(result2.get(0).getDemographicNo());
                newPatientRoute.setLabNo(Integer.parseInt(newDocNo));
                newPatientRoute.setLabType("DOC");

                patientLabRoutingDao.persist(newPatientRoute);
            }

            CtlDocumentDao ctlDocumentDao = SpringUtils.getBean(CtlDocumentDao.class);
            CtlDocument result3 = ctlDocumentDao.getCtrlDocument(Integer.parseInt(docNum));

            if (result3 != null) {
                CtlDocumentPK ctlDocumentPK = new CtlDocumentPK(Integer.parseInt(newDocNo), "demographic");
                CtlDocument newCtlDocument = new CtlDocument();
                newCtlDocument.setId(ctlDocumentPK);
                newCtlDocument.getId().setModuleId(result3.getId().getModuleId());
                newCtlDocument.setStatus(result3.getStatus());
                documentDao.persist(newCtlDocument);
            }

            if (result.isEmpty() || result2.isEmpty()) {
                String json = "{newDocNum:" + newDocNo + "}";
                JSONObject jsonObject = JSONObject.fromObject(json);
                response.setContentType("application/json");
                PrintWriter printWriter = response.getWriter();
                printWriter.print(jsonObject);
                printWriter.flush();
                return null;

            }

        }

    } catch (Exception e) {
        MiscUtils.getLogger().error(e.getMessage(), e);
        return null;
    } finally {
        try {

            if (pdf != null)
                pdf.close();
            if (input != null)
                input.close();

        } catch (IOException e) {
            //do nothing
        }
    }

    return mapping.findForward("success");
}

From source file:org.patientview.radar.util.DemographicsDecryptData2SqlMapper.java

public void run(ServletContext servletContext) throws Exception {
    WebApplicationContext webApplicationContext = WebApplicationContextUtils
            .getRequiredWebApplicationContext(servletContext);

    jdbcTemplate = new JdbcTemplate((DataSource) webApplicationContext.getBean("dataSource"));

    List<Patient> patientList = jdbcTemplate.query("SELECT * FROM patient",
            new EncryptedDemographicsRowMapper());

    StringBuilder outputText = new StringBuilder();
    for (Patient patient : patientList) {
        String updateStatement = "UPDATE patient SET ";

        if (patient.getNhsno() != null) {
            updateStatement += " nhsno = '" + patient.getNhsno() + "', ";
        }/*from   w w w. j a  va  2 s . c o m*/

        if (patient.getHospitalnumber() != null) {
            updateStatement += " hospitalnumber = \"" + patient.getHospitalnumber() + "\", ";
        }

        if (patient.getSurname() != null) {
            updateStatement += " surname = \"" + patient.getSurname() + "\", ";
        }

        if (patient.getForename() != null) {
            updateStatement += " forename = \"" + patient.getForename() + "\", ";
        }

        if (patient.getSurnameAlias() != null) {
            updateStatement += " surnameAlias = \"" + patient.getSurnameAlias() + "\", ";
        }

        if (patient.getDob() != null) {
            // just guess what a sane date format is
            updateStatement += " dateofbirth = \""
                    + new SimpleDateFormat(DATE_FORMAT_2).format(patient.getDob()) + "\", ";
        }

        if (patient.getAddress1() != null) {
            updateStatement += " address1 = \"" + patient.getAddress1() + "\", ";
        }

        if (patient.getAddress2() != null) {
            updateStatement += " address2 = \"" + patient.getAddress2() + "\", ";
        }

        if (patient.getAddress3() != null) {
            updateStatement += " address3 = \"" + patient.getAddress3() + "\", ";
        }

        if (patient.getAddress4() != null) {
            updateStatement += " address4 = \"" + patient.getAddress4() + "\", ";
        }

        if (patient.getPostcode() != null) {
            updateStatement += " POSTCODE = \"" + patient.getPostcode() + "\", ";
        }

        if (patient.getPostcodeOld() != null) {
            updateStatement += " postcodeOld = \"" + patient.getPostcodeOld() + "\", ";
        }

        updateStatement += " radarNo = " + patient.getId();
        updateStatement += " WHERE radarNo = " + patient.getId();
        updateStatement += " ;";

        outputText.append(updateStatement);
    }

    // output all sql stuff to file
    FileWriter fileWriter = new FileWriter(FILE);
    BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
    bufferedWriter.write(outputText.toString());
    //Close the output stream
    bufferedWriter.close();
}