Example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

List of usage examples for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext

Introduction

In this page you can find the example usage for org.springframework.web.context.support WebApplicationContextUtils getRequiredWebApplicationContext.

Prototype

public static WebApplicationContext getRequiredWebApplicationContext(ServletContext sc)
        throws IllegalStateException 

Source Link

Document

Find the root WebApplicationContext for this web app, typically loaded via org.springframework.web.context.ContextLoaderListener .

Usage

From source file:org.springframework.web.struts.DelegatingActionUtils.java

/**
 * Find most specific context available: check ContextLoaderPlugIn's
 * WebApplicationContext first, fall back to root WebApplicationContext else.
 * <p>When checking the ContextLoaderPlugIn context: checks for a module-specific
 * context first, falling back to the context for the default module else.
 * @param actionServlet the associated ActionServlet
 * @param moduleConfig the associated ModuleConfig (can be <code>null</code>)
 * @return the WebApplicationContext//from ww w  .j a va 2s . c o  m
 * @throws IllegalStateException if no WebApplicationContext could be found
 * @see #getWebApplicationContext
 * @see org.springframework.web.context.support.WebApplicationContextUtils#getRequiredWebApplicationContext
 */
public static WebApplicationContext findRequiredWebApplicationContext(ActionServlet actionServlet,
        ModuleConfig moduleConfig) throws IllegalStateException {

    WebApplicationContext wac = getWebApplicationContext(actionServlet, moduleConfig);
    // If no Struts-specific context found, fall back to root context.
    if (wac == null) {
        wac = WebApplicationContextUtils.getRequiredWebApplicationContext(actionServlet.getServletContext());
    }
    return wac;
}

From source file:org.squale.jraf.bootstrap.ApplicationContextFactoryInitializer.java

/**
 * Retourne l'application context selon le type d'environnement
 * d'excution.//from w ww .j a v  a2 s.c o  m
 * @return ApplicationCOntext.
 */
public static ApplicationContext getApplicationContext() {
    if (initObject == null) {
        throw new JrafIllegalStateException("Application context n'est pas initialise ...");
        // Test si l'instance de l'objet pass en paramtre est 
        // un ServletContext.
    } else if (initObject instanceof ServletContext) {
        log.debug("Dbut d'initialisation du fichier de configuration spring en mode servlet.");
        ServletContext servletContext = (ServletContext) initObject;
        return WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
        // Test si l'instance de l'objet est une chaine de caractre.
    } else if (initObject instanceof String) {
        log.debug("Initialisation du fichier de configuration spring : " + initObject);
        String contextResourceLocation = (String) initObject;
        ApplicationContext applicationContext = null;
        try {
            applicationContext = new ClassPathXmlApplicationContext(contextResourceLocation);
        } catch (BeansException e) {
            e.printStackTrace();
            throw e;
        }

        return applicationContext;
    } else {
        // Lancement de l'exception.
        throw new JrafIllegalStateException(
                "Le contexte doit tre initialis avec un String ou un ServletContext .");
    }
}

From source file:org.unitedinternet.cosmo.db.DbListener.java

/**
 * Resolves dependencies using the Spring <code>WebApplicationContext</code> and performs startup maintenance tasks.
 *///  w w  w  .j a  va2s  .c om
@SuppressWarnings("unchecked")
public void contextInitialized(ServletContextEvent sce) {
    ServletContext sc = sce.getServletContext();
    WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);

    DbInitializer initializer = beanForName(BEAN_DB_INITIALIZER, wac, DbInitializer.class);

    initializer.initialize();

    delegates = beanForName(DELEGATES_BEAN_NAME, wac, List.class);

    for (ServletContextListenerDelegate delegate : delegates) {
        delegate.contextInitialized(sce);
    }
}

From source file:org.vosao.servlet.BaseSpringServlet.java

public Object getSpringBean(final String name) {
    return WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext()).getBean(name);
}

From source file:org.wwarn.cms.authentication.CasAuthenticationFilter.java

public void init(FilterConfig config) throws ServletException {
    this.context = config.getServletContext();
    WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(context);
    ServiceRegistry serviceRegistry = (ServiceRegistry) ctx.getBean(ServiceRegistry.SERVICE_REGISTRY);
    transactionService = serviceRegistry.getTransactionService();
    nodeService = serviceRegistry.getNodeService();

    authComponent = (AuthenticationComponent) ctx.getBean("authenticationComponent");
    authService = (AuthenticationService) ctx.getBean("authenticationService");
    personService = (PersonService) ctx.getBean("personService");

    // Get a list of the available locales
    ConfigService configServiceService = (ConfigService) ctx.getBean("webClientConfigService");
    LanguagesConfigElement configElement = (LanguagesConfigElement) configServiceService.getConfig("Languages")
            .getConfigElement(LanguagesConfigElement.CONFIG_ELEMENT_ID);

    m_languages = configElement.getLanguages();
}

From source file:oscar.dms.actions.DocumentUploadAction.java

public ActionForward executeUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    DocumentUploadForm fm = (DocumentUploadForm) form;

    HashMap<String, Object> map = new HashMap<String, Object>();
    FormFile docFile = fm.getFiledata();
    String destination = request.getParameter("destination");
    java.util.Locale locale = (java.util.Locale) request.getSession()
            .getAttribute(org.apache.struts.Globals.LOCALE_KEY);
    ResourceBundle props = ResourceBundle.getBundle("oscarResources", locale);
    if (docFile == null) {
        map.put("error", 4);
    } else if (destination != null && destination.equals("incomingDocs")) {
        String fileName = docFile.getFileName();
        if (!fileName.toLowerCase().endsWith(".pdf")) {
            map.put("error", props.getString("dms.documentUpload.onlyPdf"));
        } else if (docFile.getFileSize() == 0) {
            map.put("error", 4);
            throw new FileNotFoundException();
        } else {//w ww.  j a v a2s .  c  om

            String queueId = request.getParameter("queue");
            String destFolder = request.getParameter("destFolder");

            File f = new File(
                    IncomingDocUtil.getAndCreateIncomingDocumentFilePathName(queueId, destFolder, fileName));
            if (f.exists()) {
                map.put("error", fileName + " " + props.getString("dms.documentUpload.alreadyExists"));

            } else {
                writeToIncomingDocs(docFile, queueId, destFolder, fileName);
                map.put("name", docFile.getFileName());
                map.put("size", docFile.getFileSize());
            }
            request.getSession().setAttribute("preferredQueue", queueId);
            if (docFile != null) {
                docFile.destroy();
                docFile = null;
            }

        }
    } else {
        int numberOfPages = 0;
        String fileName = docFile.getFileName();
        String user = (String) request.getSession().getAttribute("user");
        EDoc newDoc = new EDoc("", "", fileName, "", user, user, fm.getSource(), 'A',
                oscar.util.UtilDateUtilities.getToday("yyyy-MM-dd"), "", "", "demographic", "-1", 0);
        newDoc.setDocPublic("0");
        fileName = newDoc.getFileName();
        // save local file;
        if (docFile.getFileSize() == 0) {
            map.put("error", 4);
            throw new FileNotFoundException();
        }

        // write file to local dir
        writeLocalFile(docFile, fileName);
        newDoc.setContentType(docFile.getContentType());
        if (fileName.endsWith(".PDF") || fileName.endsWith(".pdf")) {
            newDoc.setContentType("application/pdf");
            // get number of pages when document is a PDF
            numberOfPages = countNumOfPages(fileName);
        }
        newDoc.setNumberOfPages(numberOfPages);
        String doc_no = EDocUtil.addDocumentSQL(newDoc);
        LogAction.addLog((String) request.getSession().getAttribute("user"), LogConst.ADD,
                LogConst.CON_DOCUMENT, doc_no, request.getRemoteAddr());

        String providerId = request.getParameter("provider");
        if (providerId != null) {
            WebApplicationContext ctx = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getSession().getServletContext());
            ProviderInboxRoutingDao providerInboxRoutingDao = (ProviderInboxRoutingDao) ctx
                    .getBean("providerInboxRoutingDAO");
            providerInboxRoutingDao.addToProviderInbox(providerId, Integer.parseInt(doc_no), "DOC");
        }

        String queueId = request.getParameter("queue");
        if (queueId != null && !queueId.equals("-1")) {
            WebApplicationContext ctx = WebApplicationContextUtils
                    .getRequiredWebApplicationContext(request.getSession().getServletContext());
            QueueDocumentLinkDao queueDocumentLinkDAO = (QueueDocumentLinkDao) ctx
                    .getBean("queueDocumentLinkDAO");
            Integer qid = Integer.parseInt(queueId.trim());
            Integer did = Integer.parseInt(doc_no.trim());
            queueDocumentLinkDAO.addActiveQueueDocumentLink(qid, did);
            request.getSession().setAttribute("preferredQueue", queueId);
        }

        map.put("name", docFile.getFileName());
        map.put("size", docFile.getFileSize());

        if (docFile != null) {
            docFile.destroy();
            docFile = null;
        }
    }
    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = JSONObject.fromObject(map);
    jsonArray.add(jsonObject);
    response.getOutputStream().write(jsonArray.toString().getBytes());
    return null;
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.EctMeasurementsAction.java

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

    HttpSession session = request.getSession();
    //request.getSession().setAttribute("EctMeasurementsForm", frm);

    EctSessionBean bean = (EctSessionBean) request.getSession().getAttribute("EctSessionBean");

    String demographicNo = null;//from  ww  w  .  jav  a 2 s. c o  m
    String providerNo = (String) session.getAttribute("user");

    //if form has demo use it since session bean could have been overwritten
    if ((demographicNo = (String) frm.getValue("demographicNo")) == null) {
        if (bean != null)
            demographicNo = bean.getDemographicNo();
    }

    String template = request.getParameter("template");
    MeasurementFlowSheet mFlowsheet = null;
    if (template != null) {
        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(session.getServletContext());
        FlowSheetCustomizationDao flowSheetCustomizationDao = (FlowSheetCustomizationDao) ctx
                .getBean("flowSheetCustomizationDao");
        MeasurementTemplateFlowSheetConfig templateConfig = MeasurementTemplateFlowSheetConfig.getInstance();

        List<FlowSheetCustomization> custList = flowSheetCustomizationDao.getFlowSheetCustomizations(template,
                (String) session.getAttribute("user"), demographicNo);
        mFlowsheet = templateConfig.getFlowSheet(template, custList);
    }

    //request.getSession().setAttribute("EctSessionBean", bean);
    //TODO replace with a date format call.  Actually revamp to use hibernate
    java.util.Calendar calender = java.util.Calendar.getInstance();
    String day = Integer.toString(calender.get(java.util.Calendar.DAY_OF_MONTH));
    String month = Integer.toString(calender.get(java.util.Calendar.MONTH) + 1);
    String year = Integer.toString(calender.get(java.util.Calendar.YEAR));
    String hour = Integer.toString(calender.get(java.util.Calendar.HOUR_OF_DAY));
    String min = Integer.toString(calender.get(java.util.Calendar.MINUTE));
    String second = Integer.toString(calender.get(java.util.Calendar.SECOND));
    String dateEntered = year + "-" + month + "-" + day + " " + hour + ":" + min + ":" + second;

    String numType = (String) frm.getValue("numType");
    int iType = Integer.parseInt(numType);

    MsgStringQuote str = new MsgStringQuote();

    Properties p = (Properties) session.getAttribute("providerBean");
    String by = "";
    if (p != null) {
        by = p.getProperty(providerNo, "");
    }

    String textOnEncounter = ""; //"**"+StringUtils.rightPad(by,80,"*")+"\\n";

    //if parent window content has changed then we need to propagate change so
    //we do not write to parent
    String parentChanged = (String) frm.getValue("parentChanged");
    request.setAttribute("parentChanged", parentChanged);

    boolean valid = true;
    try {

        EctValidation ectValidation = new EctValidation();
        ActionMessages errors = new ActionMessages();

        String inputValueName, inputTypeName, inputTypeDisplayName, mInstrcName, commentsName;
        String dateName, validationName, inputValue, inputType, inputTypeDisplay, mInstrc;
        String comments, dateObserved, validation;

        String regExp = null;
        double dMax = 0;
        double dMin = 0;
        int iMax = 0;
        int iMin = 0;

        ResultSet rs;
        String regCharExp;
        //goes through each type to check if the input value is valid
        for (int i = 0; i < iType; i++) {
            inputValueName = "inputValue-" + i;
            inputTypeName = "inputType-" + i;
            inputTypeDisplayName = "inputTypeDisplayName-" + i;
            mInstrcName = "inputMInstrc-" + i;
            commentsName = "comments-" + i;
            dateName = "date-" + i;
            inputValue = (String) frm.getValue(inputValueName);
            inputType = (String) frm.getValue(inputTypeName);
            inputTypeDisplay = (String) frm.getValue(inputTypeDisplayName);
            mInstrc = (String) frm.getValue(mInstrcName);
            comments = (String) frm.getValue(commentsName);
            dateObserved = (String) frm.getValue(dateName);

            regExp = null;
            dMax = 0;
            dMin = 0;
            iMax = 0;
            iMin = 0;

            rs = ectValidation.getValidationType(inputType, mInstrc);
            regCharExp = ectValidation.getRegCharacterExp();

            if (rs.next()) {
                dMax = rs.getDouble("maxValue");
                dMin = rs.getDouble("minValue");
                iMax = rs.getInt("maxLength");
                iMin = rs.getInt("minLength");
                regExp = oscar.Misc.getString(rs, "regularExp");
            }
            rs.close();

            if (!ectValidation.isInRange(dMax, dMin, inputValue)) {
                errors.add(inputValueName, new ActionMessage("errors.range", inputTypeDisplay,
                        Double.toString(dMin), Double.toString(dMax)));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.maxLength(iMax, inputValue)) {
                errors.add(inputValueName,
                        new ActionMessage("errors.maxlength", inputTypeDisplay, Integer.toString(iMax)));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.minLength(iMin, inputValue)) {
                errors.add(inputValueName,
                        new ActionMessage("errors.minlength", inputTypeDisplay, Integer.toString(iMin)));
                saveErrors(request, errors);
                valid = false;
            }

            if (!ectValidation.matchRegExp(regExp, inputValue)) {
                errors.add(inputValueName, new ActionMessage("errors.invalid", inputTypeDisplay));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.isValidBloodPressure(regExp, inputValue)) {
                errors.add(inputValueName, new ActionMessage("error.bloodPressure"));
                saveErrors(request, errors);
                valid = false;
            }
            if (!ectValidation.isDate(dateObserved) && inputValue.compareTo("") != 0) {
                errors.add(dateName, new ActionMessage("errors.invalidDate", inputTypeDisplay));
                saveErrors(request, errors);
                valid = false;
            }
        }

        //Write to database and to encounter form if all the input values are valid
        if (valid) {
            for (int i = 0; i < iType; i++) {

                inputValueName = "inputValue-" + i;
                inputTypeName = "inputType-" + i;
                mInstrcName = "inputMInstrc-" + i;
                commentsName = "comments-" + i;
                validationName = "validation-" + i;
                dateName = "date-" + i;

                inputValue = (String) frm.getValue(inputValueName);
                inputType = (String) frm.getValue(inputTypeName);
                mInstrc = (String) frm.getValue(mInstrcName);
                comments = (String) frm.getValue(commentsName);
                comments = org.apache.commons.lang.StringEscapeUtils.escapeSql(comments);
                validation = (String) frm.getValue(validationName);
                dateObserved = (String) frm.getValue(dateName);

                org.apache.commons.validator.GenericValidator gValidator = new org.apache.commons.validator.GenericValidator();
                if (!GenericValidator.isBlankOrNull(inputValue)) {
                    //Find if the same data has already been entered into the system
                    String sql = "SELECT * FROM measurements WHERE demographicNo='" + demographicNo
                            + "' AND dataField='" + inputValue + "' AND measuringInstruction='" + mInstrc
                            + "' AND comments='" + comments + "' AND dateObserved='" + dateObserved
                            + "' and type = '" + inputType + "'";

                    rs = DBHandler.GetSQL(sql);
                    if (!rs.next()) {
                        //Write to the Dababase if all input values are valid
                        sql = "INSERT INTO measurements"
                                + "(type, demographicNo, providerNo, dataField, measuringInstruction, comments, dateObserved, dateEntered)"
                                + " VALUES ('" + str.q(inputType) + "','" + str.q(demographicNo) + "','"
                                + str.q(providerNo) + "','" + str.q(inputValue) + "','" + str.q(mInstrc) + "','"
                                + str.q(comments) + "','" + str.q(dateObserved) + "','" + str.q(dateEntered)
                                + "')";

                        DBHandler.RunSQL(sql);
                        //prepare input values for writing to the encounter form
                        if (mFlowsheet == null) {
                            textOnEncounter = textOnEncounter + inputType + "    " + inputValue + " " + mInstrc
                                    + " " + comments + "\\n";
                        } else {
                            textOnEncounter += mFlowsheet.getFlowSheetItem(inputType).getDisplayName() + "    "
                                    + inputValue + " " + comments + "\\n";
                        }
                    }
                    rs.close();
                }

            }
            // textOnEncounter = textOnEncounter + "**********************************************************************************\\n";

        } else {
            String groupName = (String) frm.getValue("groupName");
            String css = (String) frm.getValue("css");
            request.setAttribute("groupName", groupName);
            request.setAttribute("css", css);
            return (new ActionForward(mapping.getInput()));
        }
        /* select the correct db specific command */
        String db_type = OscarProperties.getInstance().getProperty("db_type").trim();
        String dbSpecificCommand;
        if (db_type.equalsIgnoreCase("mysql")) {
            dbSpecificCommand = "SELECT LAST_INSERT_ID()";
        } else if (db_type.equalsIgnoreCase("postgresql")) {
            dbSpecificCommand = "SELECT CURRVAL('consultationrequests_numeric')";
        } else
            throw new SQLException("ERROR: Database " + db_type + " unrecognized.");
    } catch (SQLException e) {
        MiscUtils.getLogger().error("Error", e);
    }

    //put the inputvalue to the encounter form
    session.setAttribute("textOnEncounter", textOnEncounter);

    return mapping.findForward("success");
}

From source file:oscar.oscarEncounter.oscarMeasurements.pageUtil.FormUpdateAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    java.util.Calendar calender = java.util.Calendar.getInstance();
    String day = Integer.toString(calender.get(java.util.Calendar.DAY_OF_MONTH));
    String month = Integer.toString(calender.get(java.util.Calendar.MONTH) + 1);
    String year = Integer.toString(calender.get(java.util.Calendar.YEAR));
    String dateEntered = request.getParameter("date");

    String testOutput = "";
    String textOnEncounter = "********Diabetes Flowsheet Update******** \\n";
    boolean valid = true;
    boolean errorPage = false;

    HttpSession session = request.getSession();

    String temp = "diab3";
    session.setAttribute("temp", "diab3");
    String demographic_no = request.getParameter("demographic_no");
    String providerNo = (String) session.getAttribute("user");
    String apptNo = (String) session.getAttribute("cur_appointment_no");

    WebApplicationContext ctx = WebApplicationContextUtils
            .getRequiredWebApplicationContext(session.getServletContext());

    FlowSheetCustomizationDao flowSheetCustomizationDao = (FlowSheetCustomizationDao) ctx
            .getBean("flowSheetCustomizationDao");

    List<FlowSheetCustomization> custList = flowSheetCustomizationDao.getFlowSheetCustomizations(temp,
            providerNo, demographic_no);

    MeasurementTemplateFlowSheetConfig templateConfig = MeasurementTemplateFlowSheetConfig.getInstance();
    MeasurementFlowSheet mFlowsheet = templateConfig.getFlowSheet(temp, custList);

    List<MeasurementTemplateFlowSheetConfig.Node> nodes = mFlowsheet.getItemHeirarchy();

    EctMeasurementTypeBeanHandler mType = new EctMeasurementTypeBeanHandler();

    FlowSheetItem item;/*from  w w  w.  j av a  2  s  .  c  o  m*/
    String measure;

    for (int i = 0; i < nodes.size(); i++) {
        MeasurementTemplateFlowSheetConfig.Node node = nodes.get(i);

        for (int j = 0; j < node.children.size(); j++) {
            MeasurementTemplateFlowSheetConfig.Node child = node.children.get(j);
            if (child.children == null && child.flowSheetItem != null) {
                item = child.flowSheetItem;
                measure = item.getItemName();
                Map h2 = mFlowsheet.getMeasurementFlowSheetInfo(measure);
                EctMeasurementTypesBean mtypeBean = mType.getMeasurementType(measure);

                String name = child.flowSheetItem.getDisplayName().replaceAll("\\W", "");

                if (request.getParameter(name) != null && !request.getParameter(name).equals("")) {

                    String comment = "";
                    if (request.getParameter(name + "_comments") != null
                            && !request.getParameter(name + "_comments").equals("")) {
                        comment = request.getParameter(name + "_comments");
                    }
                    valid = doInput(item, mtypeBean, mFlowsheet, mtypeBean.getType(),
                            mtypeBean.getMeasuringInstrc(), request.getParameter(name), comment, dateEntered,
                            apptNo, request);

                    if (!valid) {
                        testOutput += child.flowSheetItem.getDisplayName() + ": " + request.getParameter(name)
                                + "\n";
                        errorPage = true;
                    } else {
                        textOnEncounter += name + " " + request.getParameter(name) + "\\n";
                    }

                } else if (request.getParameter(name) != null
                        && request.getParameter(name + "_comments") != null
                        && !request.getParameter(name + "_comments").equals("")) {
                    String comment = request.getParameter(name + "_comments");
                    doCommentInput(item, mtypeBean, mFlowsheet, mtypeBean.getType(),
                            mtypeBean.getMeasuringInstrc(), comment, dateEntered, apptNo, request);
                }

            }
        }
    }

    //if (request.getParameter("ycoord") != null) {
    //   request.setAttribute("ycoord", request.getParameter("ycoord"));
    //}

    if (errorPage) {
        request.setAttribute("testOutput", testOutput);
        return mapping.findForward("failure");
    }
    session.setAttribute("textOnEncounter", textOnEncounter);
    if (request.getParameter("submit").equals("Update")) {
        return mapping.findForward("reload");
    } else {
        return mapping.findForward("success");
    }
}

From source file:oscar.oscarEncounter.pageUtil.EctDisplayDecisionSupportAlertsAction.java

public boolean getInfo(EctSessionBean bean, HttpServletRequest request, NavBarDisplayDAO Dao,
        MessageResources messages) {//from  w  ww . j  a  v a  2  s  .c om

    boolean a = true;
    Vector v = OscarRoleObjectPrivilege.getPrivilegeProp("_newCasemgmt.decisionSupportAlerts");
    String roleName = (String) request.getSession().getAttribute("userrole") + ","
            + (String) request.getSession().getAttribute("user");
    a = OscarRoleObjectPrivilege.checkPrivilege(roleName, (Properties) v.get(0), (Vector) v.get(1));
    if (!a) {
        return true; //decisionSupportAlerts link won't show up on new CME screen.
    } else {

        //set lefthand module heading and link
        String winName = "dsalert" + bean.demographicNo;
        String url = "popupPage(500,950,'" + winName + "','" + request.getContextPath()
                + "/oscarEncounter/decisionSupport/guidelineAction.do?method=list&provider_no="
                + bean.providerNo + "&demographic_no=" + bean.demographicNo + "&parentAjaxId=" + cmd
                + "'); return false;";
        Dao.setLeftHeading(messages.getMessage(request.getLocale(), "global.decisionSupportAlerts"));
        Dao.setLeftURL(url);

        //set the right hand heading link
        winName = "AddeForm" + bean.demographicNo;

        Dao.setRightURL(url);
        Dao.setRightHeadingID(cmd); //no menu so set div id to unique id for this action

        StringBuilder javascript = new StringBuilder("<script type=\"text/javascript\">");
        String js = "";

        WebApplicationContext ctx = WebApplicationContextUtils
                .getRequiredWebApplicationContext(getServlet().getServletContext());
        DSService dsService = (DSService) ctx.getBean("dsService");

        List<DSGuideline> dsGuidelines = dsService.getDsGuidelinesByProvider(bean.providerNo);

        String key;

        String BGCOLOUR = request.getParameter("hC");

        //ORN CKD Pilot Code
        if (OscarProperties.getInstance().getProperty("ORN_PILOT", "yes").equalsIgnoreCase("yes")
                && (OscarProperties.getInstance().getProperty("ckd_notification_scheme", "dsa").equals("dsa")
                        || OscarProperties.getInstance().getProperty("ckd_notification_scheme", "dsa")
                                .equals("all"))) {
            CkdScreener ckdScreener = new CkdScreener();
            List<String> reasons = new ArrayList<String>();
            boolean match = ckdScreener.screenDemographic(Integer.parseInt(bean.demographicNo), reasons, null);
            boolean notify = false;

            for (Dxresearch dr : dxResearchDao.find(Integer.parseInt(bean.demographicNo), "OscarCode",
                    "CKDSCREEN")) {
                //we have an active one, we should notify
                if (dr.getStatus() == 'A') {
                    notify = true;
                }
            }
            for (Dxresearch dr : dxResearchDao.find(Integer.parseInt(bean.demographicNo), "icd9", "585")) {
                if (dr.getStatus() == 'A') {
                    notify = false;
                }
            }
            if (!notify) {
                //there's no active ones, but let's look at the latest one
                List<Dxresearch> drs = dxResearchDao.find(Integer.parseInt(bean.demographicNo), "OscarCode",
                        "CKDSCREEN");
                if (drs.size() > 0) {
                    Dxresearch dr = drs.get(0);
                    Calendar aYearAgo = Calendar.getInstance();
                    aYearAgo.add(Calendar.MONTH, -12);
                    if (dr.getUpdateDate().before(aYearAgo.getTime())) {
                        notify = true;
                        //reopen it
                        dr.setStatus('A');
                        dr.setUpdateDate(new Date());
                        dxResearchDao.merge(dr);
                        //need some way to notify that tab to reload
                        javascript.append("jQuery(document).ready(function(){reloadNav('Dx');});");
                    }
                }
            }
            if (match && notify) {
                NavBarDisplayDAO.Item item = NavBarDisplayDAO.Item();
                url = "popupPage(500,950,'" + winName + "','" + request.getContextPath()
                        + "/renal/CkdDSA.do?method=detail&demographic_no=" + bean.demographicNo
                        + "&parentAjaxId=" + cmd + "'); return false;";
                item.setURL(url);
                item.setLinkTitle("Based on guidelines, a CKD screening should be performed.");
                item.setTitle("Screen for CKD");
                item.setColour("#ff5409;");
                Dao.addItem(item);
            }
        }

        for (DSGuideline dsGuideline : dsGuidelines) {
            if (OscarProperties.getInstance()
                    .getProperty("dsa.skip." + dsGuideline.getTitle().replaceAll(" ", "_"), "false")
                    .equals("true")) {
                continue;
            }
            try {
                List<DSConsequence> dsConsequences = dsGuideline.evaluate(bean.demographicNo);
                if (dsConsequences == null)
                    continue;
                for (DSConsequence dsConsequence : dsConsequences) {
                    if (dsConsequence.getConsequenceType() != DSConsequence.ConsequenceType.warning)
                        continue;

                    NavBarDisplayDAO.Item item = NavBarDisplayDAO.Item();
                    winName = dsConsequence.getConsequenceType().toString() + bean.demographicNo;

                    url = "popupPage(500,950,'" + winName + "','" + request.getContextPath()
                            + "/oscarEncounter/decisionSupport/guidelineAction.do?method=detail&guidelineId="
                            + dsGuideline.getId() + "&provider_no=" + bean.providerNo + "&demographic_no="
                            + bean.demographicNo + "&parentAjaxId=" + cmd + "'); return false;";
                    //Date date = (Date)curform.get("formDateAsDate");
                    //String formattedDate = DateUtils.getDate(date,dateFormat,request.getLocale());
                    key = StringUtils.maxLenString(dsConsequence.getText(), MAX_LEN_KEY, CROP_LEN_KEY,
                            ELLIPSES);
                    item.setLinkTitle(dsConsequence.getText());
                    key = StringEscapeUtils.escapeJavaScript(key);
                    js = "itemColours['" + key + "'] = '" + BGCOLOUR + "'; autoCompleted['" + key + "'] = \""
                            + url + "\"; autoCompList.push('" + key + "');";
                    javascript.append(js);
                    url += "return false;";
                    item.setURL(url);
                    String strTitle = StringUtils.maxLenString(dsConsequence.getText(), MAX_LEN_TITLE,
                            CROP_LEN_TITLE, ELLIPSES);
                    item.setTitle(strTitle);
                    if (dsConsequence.getConsequenceStrength() == DSConsequence.ConsequenceStrength.warning) {
                        item.setColour("#ff5409;");
                    }
                    //item.setDate(new Date());
                    Dao.addItem(item);
                }
            } catch (Exception e) {
                logger.error("Unable to evaluate patient against a DS guideline '" + dsGuideline.getTitle()
                        + "' of UUID '" + dsGuideline.getUuid() + "'", e);
            }
        }

        javascript.append("</script>");
        Dao.setJavaScript(javascript.toString());
        return true;
    }
}

From source file:springapp.web.controller.theme.DownloadController.java

public ModelAndView handleRequest(HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws Exception {

    String templateIdString = httpServletRequest.getParameter(ApplicationConstants.TEMPLATE_ID);

    byte templateId = null != templateIdString ? Byte.parseByte(templateIdString) : 0;
    String templateName = templateId == 0 ? "blue" : "gray";

    String shemaNameParam = httpServletRequest.getParameter(ApplicationConstants.NEW_SCHEMA_NAME);
    String newSchemaName = (null != shemaNameParam) && (!"".equals(shemaNameParam)) ? shemaNameParam
            : "default";

    String versionString = httpServletRequest.getParameter("version");
    String version = (null == versionString) ? "3.2" : versionString;

    HttpSession session = httpServletRequest.getSession();

    ServletContext servletContext = session.getServletContext();
    WebApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
    //String resourcesPath = (String)context.getBean("resourcesPath");

    ResourcesHolder currentSchema = (ResourcesHolder) session
            .getAttribute(ApplicationConstants.CURRENT_SCHEMA_ATTRIBUTE_NAME/*+version*/);
    String resourcesPath = currentSchema.getResourcesPath();
    ResourcesLoader loader = loaderFactory.getResourcesLoader(currentSchema, context);

    httpServletResponse.setContentType("application/zip");

    httpServletResponse.setHeader("Pragma", "no-cache");
    httpServletResponse.setHeader("Cache-Control", "no-cache");
    httpServletResponse.setHeader("Expires", "-1");
    httpServletResponse.setHeader("Content-Disposition",
            "attachment; filename=\"xtheme-" + newSchemaName + ".zip\";");
    //httpServletResponse.setContentLength(zipOS.size());
    ServletOutputStream servletOutputStream = httpServletResponse.getOutputStream();
    ZipOutputStream zipOS = new ZipOutputStream(servletOutputStream);

    zipOS = loader.outForZip(currentSchema, resourcesPath, zipOS, context, newSchemaName, templateName,
            version);//from  w ww. j a v  a2s .  c o  m

    zipOS.flush();
    zipOS.close();
    servletOutputStream.flush();
    servletOutputStream.close();

    logger.info("DownloadController processed! ");

    return null;
}