Example usage for javax.servlet.http HttpSession getServletContext

List of usage examples for javax.servlet.http HttpSession getServletContext

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession getServletContext.

Prototype

public ServletContext getServletContext();

Source Link

Document

Returns the ServletContext to which this session belongs.

Usage

From source file:edu.lternet.pasta.portal.HarvesterServlet.java

/**
 * The doPost method of the servlet. <br>
 * // ww w  . j a v  a2 s  .c o m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    ServletContext servletContext = httpSession.getServletContext();
    ArrayList<String> documentURLs = null;
    File emlFile = null;
    String emlTextArea = null;
    Harvester harvester = null;
    String harvestId = null;
    String harvestListURL = null;
    String harvestReportId = null;
    boolean isDesktopUpload = false;
    boolean isEvaluate = false;
    String uid = (String) httpSession.getAttribute("uid");
    String urlTextArea = null;
    String warningMessage = "";

    try {
        if (uid == null) {
            throw new PastaAuthenticationException(LOGIN_WARNING);
        } else {
            /*
             * The "metadataSource" request parameter can have a value of
             * "emlText", "emlFile", "urlList", "harvestList", or
             * "desktopHarvester". It is set as a hidden input field in 
             * each of the harvester forms.
             */
            String metadataSource = request.getParameter("metadataSource");

            /*
             * "mode" can have a value of "evaluate" or "upgrade". It is set
             * as the value of the submit button in each of the harvester
             * forms.
             */
            String mode = request.getParameter("submit");
            if ((mode != null) && (mode.equalsIgnoreCase("evaluate"))) {
                isEvaluate = true;
            }

            if ((metadataSource != null) && (!metadataSource.equals("desktopHarvester"))) {
                harvestId = generateHarvestId();
                if (isEvaluate) {
                    harvestReportId = uid + "-evaluate-" + harvestId;
                } else {
                    harvestReportId = uid + "-upload-" + harvestId;
                }
            }

            if (metadataSource != null) {
                if (metadataSource.equals("emlText")) {
                    emlTextArea = request.getParameter("emlTextArea");
                    if (emlTextArea == null || emlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the text of an EML document into the text area.</p>";
                    }
                } else if (metadataSource.equals("emlFile")) {
                    Collection<Part> parts = request.getParts();
                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save EML file to disk
                            emlFile = processUploadedFile(part);
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.equals("desktopUpload")
                                        && fieldValue.equalsIgnoreCase("1")) {
                                    isDesktopUpload = true;
                                }
                            }
                        }
                    }
                } else if (metadataSource.equals("urlList")) {
                    urlTextArea = request.getParameter("urlTextArea");
                    if (urlTextArea == null || urlTextArea.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter one or more EML document URLs into the text area.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromTextArea(urlTextArea);
                        warningMessage = CHECK_BACK_LATER;
                    }
                } else if (metadataSource.equals("harvestList")) {
                    harvestListURL = request.getParameter("harvestListURL");
                    if (harvestListURL == null || harvestListURL.trim().isEmpty()) {
                        warningMessage = "<p class=\"warning\">Please enter the URL to a Metacat Harvest List.</p>";
                    } else {
                        documentURLs = parseDocumentURLsFromHarvestList(harvestListURL);
                        warningMessage = CHECK_BACK_LATER;
                    }
                }
                /*
                 * If the metadata source is "desktopHarvester", we already have the
                 * EML file stored in a session attribute. Now we need to retrieve
                 * the data files from the brower's form fields and write the
                 * data files to a URL accessible location.
                 */
                else if (metadataSource.equals("desktopHarvester")) {
                    emlFile = (File) httpSession.getAttribute("emlFile");
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    harvestReportId = (String) httpSession.getAttribute("harvestReportId");
                    String dataPath = servletContext.getRealPath(DESKTOP_DATA_DIR);
                    String harvestPath = String.format("%s/%s", dataPath, harvestReportId);

                    Collection<Part> parts = request.getParts();
                    String objectName = null;
                    Part filePart = null;

                    for (Part part : parts) {
                        if (part.getContentType() != null) {
                            // save data file to disk
                            //processDataFile(part, harvestPath);
                            filePart = part;
                        } else {
                            /*
                             * Parse the request parameters.
                             */
                            String fieldName = part.getName();
                            String fieldValue = request.getParameter(fieldName);
                            if (fieldName != null && fieldValue != null) {
                                if (fieldName.equals("submit") && fieldValue.equalsIgnoreCase("evaluate")) {
                                    isEvaluate = true;
                                } else if (fieldName.startsWith("object-name-")) {
                                    objectName = fieldValue;
                                }
                            }
                        }

                        if (filePart != null && objectName != null) {
                            processDataFile(filePart, harvestPath, objectName);
                            objectName = null;
                            filePart = null;
                        }

                    }

                    emlFile = transformDesktopEML(harvestPath, emlFile, harvestReportId, entityList);
                }
            } else {
                throw new IllegalStateException("No value specified for request parameter 'metadataSource'");
            }

            if (harvester == null) {
                harvester = new Harvester(harvesterPath, harvestReportId, uid, isEvaluate);
            }

            if (emlTextArea != null) {
                harvester.processSingleDocument(emlTextArea);
            } else if (emlFile != null) {
                if (isDesktopUpload) {
                    ArrayList<Entity> entityList = parseEntityList(emlFile);
                    httpSession.setAttribute("entityList", entityList);
                    httpSession.setAttribute("emlFile", emlFile);
                    httpSession.setAttribute("harvestReportId", harvestReportId);
                    httpSession.setAttribute("isEvaluate", new Boolean(isEvaluate));
                } else {
                    harvester.processSingleDocument(emlFile);
                }
            } else if (documentURLs != null) {
                harvester.setDocumentURLs(documentURLs);
                ExecutorService executorService = Executors.newCachedThreadPool();
                executorService.execute(harvester);
                executorService.shutdown();
            }
        }
    } catch (Exception e) {
        handleDataPortalError(logger, e);
    }

    request.setAttribute("message", warningMessage);

    /*
     * If we have a new reportId, and either there is no warning message or
     * it's the "Check back later" message, set the harvestReportID session
     * attribute to the new reportId value.
     */
    if (harvestReportId != null && harvestReportId.length() > 0
            && (warningMessage.length() == 0 || warningMessage.equals(CHECK_BACK_LATER))) {
        httpSession.setAttribute("harvestReportID", harvestReportId);
    }

    if (isDesktopUpload) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./desktopHarvester.jsp");
        requestDispatcher.forward(request, response);
    } else if (warningMessage.length() == 0) {
        response.sendRedirect("./harvestReport.jsp");
    } else {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher("./harvester.jsp");
        requestDispatcher.forward(request, response);
    }

}

From source file:org.ambraproject.wombat.controller.StaticResourceController.java

@RequestMapping(name = "staticResource", value = "/" + AssetUrls.RESOURCE_NAMESPACE + "/**")
public void serveResource(HttpServletRequest request, HttpServletResponse response, HttpSession session,
        @SiteParam Site site) throws IOException {
    Theme theme = site.getTheme();/*from   ww w . j  a v  a 2  s .c  om*/

    // Kludge to get "resource/**"
    String servletPath = request.getRequestURI();
    String filePath = pathFrom(servletPath, AssetUrls.RESOURCE_NAMESPACE);
    if (filePath.length() <= AssetUrls.RESOURCE_NAMESPACE.length() + 1) {
        throw new NotFoundException(); // in case of a request to "resource/" root
    }

    if (corsEnabled(site, filePath)) {
        response.setHeader(HttpHeaders.ACCESS_CONTROL_ALLOW_ORIGIN, "*");
    }

    response.setContentType(session.getServletContext().getMimeType(servletPath));
    if (filePath.startsWith(COMPILED_NAMESPACE)) {
        serveCompiledAsset(filePath, request, response);
    } else {
        serveFile(filePath, request, response, theme);
    }
}

From source file:com.mobileman.projecth.web.controller.PublicController.java

@RequestMapping(method = RequestMethod.GET, value = "/behandlung/{page}")
public String getPage(HttpSession session, HttpServletRequest request, @PathVariable String page) {
    return processPage(session.getServletContext(), page);
}

From source file:org.wso2.carbon.ui.CarbonUILoginUtil.java

/**
 * //from   ww  w . java 2s.  co  m
 * @param authenticator
 * @param request
 * @param response
 * @param session
 * @param authenticated
 * @param contextPath
 * @param indexPageURL
 * @param httpLogin
 * @return
 * @throws IOException
 */
protected static boolean handleLogout(CarbonUIAuthenticator authenticator, HttpServletRequest request,
        HttpServletResponse response, HttpSession session, boolean authenticated, String contextPath,
        String indexPageURL, String httpLogin) throws IOException {
    log.debug("Handling Logout..");
    // Logout the user from the back-end
    try {
        authenticator = (CarbonUIAuthenticator) session
                .getAttribute(CarbonSecuredHttpContext.CARBON_AUTHNETICATOR);
        if (authenticator != null) {
            authenticator.unauthenticate(request);
            log.debug("Backend session invalidated");
        }
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        response.sendRedirect("../admin/login.jsp");
        return false;
    }

    // Only applicable if this is SAML2 based SSO. Complete the logout action after receiving
    // the Logout response.
    if ("true".equals(request.getParameter("logoutcomplete"))) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
            } catch (Exception ignored) { // Ignore exception when
                // invalidating and
                // invalidated session
            }
            log.debug("Frontend session invalidated");
        }
        response.sendRedirect("../../carbon/admin/login.jsp");
        return false;
    }

    if (request.getAttribute("ExternalLogoutPage") != null) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            session.removeAttribute("logged-user");
            session.getServletContext().removeAttribute("logged-user");
            try {
                session.invalidate();
            } catch (Exception ignored) {
            }
            log.debug("Frontend session invalidated");
        }

        response.sendRedirect((String) request.getAttribute("ExternalLogoutPage"));
        return false;
    }

    CarbonSSOSessionManager ssoSessionManager = CarbonSSOSessionManager.getInstance();

    if (!ssoSessionManager.skipSSOSessionInvalidation(request, authenticator)
            && !ssoSessionManager.isSessionValid(request.getSession().getId())) {
        HttpSession currentSession = request.getSession(false);
        if (currentSession != null) {
            // check if current session has expired
            session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
            try {
                session.invalidate();
                log.debug("SSO session session invalidated ");
            } catch (Exception ignored) { // Ignore exception when
                // Invalidating and invalidated session
                if (log.isDebugEnabled()) {
                    log.debug("Ignore exception when invalidating session", ignored);
                }
            }
        }
        response.sendRedirect("../.." + indexPageURL);
        return false;
    }

    // Memory clean up : remove invalid session from the invalid session list.
    ssoSessionManager.removeInvalidSession(request.getSession().getId());

    // This condition is evaluated when users are logged out in SAML2 based SSO
    if (request.getAttribute("logoutRequest") != null) {
        log.debug("Loging out from SSO session");
        response.sendRedirect("../../carbon/sso-acs/redirect_ajaxprocessor.jsp?logout=true");
        return false;
    }

    HttpSession currentSession = request.getSession(false);
    if (currentSession != null) {
        // Check if current session has expired
        session.removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        session.getServletContext().removeAttribute(CarbonSecuredHttpContext.LOGGED_USER);
        try {
            session.invalidate();
            log.debug("Frontend session invalidated");
        } catch (Exception ignored) {
            // Ignore exception when invalidating and invalidated session
        }
    }

    Cookie rmeCookie = new Cookie(CarbonConstants.REMEMBER_ME_COOKE_NAME, null);
    rmeCookie.setPath("/");
    rmeCookie.setSecure(true);
    rmeCookie.setMaxAge(0);
    response.addCookie(rmeCookie);
    response.sendRedirect(contextPath + indexPageURL);
    return false;
}

From source file:org.hyperic.hq.ui.security.UISessionInitializationStrategy.java

public void onAuthentication(Authentication authentication, HttpServletRequest request,
        HttpServletResponse response) throws SessionAuthenticationException {
    super.onAuthentication(authentication, request, response);

    final boolean debug = log.isDebugEnabled();

    if (debug)/*  ww  w . j  av a  2  s.  c o  m*/
        log.debug("Initializing UI session parameters...");

    HttpSession session = request.getSession();
    WebUser webUser = (WebUser) session.getAttribute(Constants.WEBUSER_SES_ATTR);

    assert (webUser != null); // At this point webUser should never be null

    if (webUser.getPreferences().getKeys().size() == 0) {
        // will be cleaned out during registration
        session.setAttribute(Constants.PASSWORD_SES_ATTR, authentication.getCredentials().toString());
        session.setAttribute(Constants.NEEDS_REGISTRATION, Boolean.TRUE);

        if (debug)
            log.debug("Stashing registration parameters in the session for later use");
    }

    ServletContext ctx = session.getServletContext();

    // Load up the user's dashboard preferences
    loadDashboard(ctx, webUser, authzBoss);

    // Determine if we can render chart images
    setXlibFlag(session);
}

From source file:edu.cornell.mannlib.vitro.webapp.edit.n3editing.configuration.generators.AddGrantRoleToPersonGenerator.java

/**
 * Prepare edit configuration for update
 * @param vreq/*from   w  w w  . j av  a2s. c o m*/
 * @param session
 * @param editConfiguration
 */

private void prepareForUpdate(VitroRequest vreq, HttpSession session, EditConfigurationVTwo editConfiguration) {
    //Here, retrieve model from 
    OntModel model = ModelAccess.on(session.getServletContext()).getOntModel();
    //Object property by definition
    String objectUri = EditConfigurationUtils.getObjectUri(vreq);
    if (objectUri != null) {
        //update existing object
        editConfiguration.prepareForObjPropUpdate(model);
    } else {
        //new object to be created
        editConfiguration.prepareForNonUpdate(model);
    }
}

From source file:gov.nih.nci.ncicb.cadsr.common.security.LogoutServlet.java

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    //unlock all forms locked by this session
    HttpSession session = request.getSession();
    String logTjsp = getServletConfig().getInitParameter("LogthroughJSP");
    if (logTjsp != null && !logTjsp.equals(""))
        LOGTHROUGH_JSP = logTjsp;//from  w w  w  .  ja va2s.  c  om

    String lojsp = getServletConfig().getInitParameter("LogoutJSP");
    if (lojsp != null && !lojsp.equals(""))
        LOGOUT_JSP = lojsp;
    String authjsp = getServletConfig().getInitParameter("ErrorJSP");
    if (authjsp != null && !authjsp.equals(""))
        AUTHORIZATION_ERROR_JSP = authjsp;

    if (!request.getContextPath().contains("CDEBrowser")) {
        getApplicationServiceLocator(session.getServletContext()).findLockingService()
                .unlockFormByUser(request.getRemoteUser());
    }
    synchronized (SessionUtils.sessionObjectCache) {
        log.error("LogoutServlet.doPost at start:" + TimeUtils.getEasternTime());
        String error = request.getParameter("authorizationError");
        String forwardUrl;
        //// GF29128 Begin. D.An, 20130729. 
        String un = (String) session.getAttribute("myUsername");
        ;
        ////   if (un == null)
        ////      un = "viewer";
        System.out.println("logoutServlet: " + session.getAttribute("myUsername"));
        if (error == null) {
            if (un.equals("viewer"))
                forwardUrl = LOGTHROUGH_JSP;
            //// GF29128  end.      
            else
                forwardUrl = LOGOUT_JSP;
        } else {
            forwardUrl = AUTHORIZATION_ERROR_JSP;
        }

        if ((session != null) && isLoggedIn(request)) {
            for (int i = 0; i < logoutKeys.length; i++) {
                session.removeAttribute(logoutKeys[i]);
            }

            //remove formbuilder specific objects
            //TODO has to be moved to an action
            Collection keys = (Collection) session.getAttribute(FormBuilderConstants.CLEAR_SESSION_KEYS);
            if (keys != null) {
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    session.removeAttribute((String) it.next());
                }
            }
            HashMap allMap = new HashMap();
            allMap.put(CaDSRConstants.GLOBAL_SESSION_KEYS, copyAllsessionKeys(session));
            allMap.put(CaDSRConstants.GLOBAL_SESSION_MAP, copyAllsessionObjects(session));
            SessionUtils.addToSessionCache(session.getId(), allMap);
            forwardUrl = forwardUrl + "?" + CaDSRConstants.PREVIOUS_SESSION_ID + "=" + session.getId();
            session.invalidate();
        }

        RequestDispatcher dispacher = request.getRequestDispatcher(forwardUrl);
        dispacher.forward(request, response);
        log.error("LogoutServlet.doPost at end:" + TimeUtils.getEasternTime());
    }
}

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   ww  w . j  a v 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:com.mobileman.projecth.web.controller.PublicController.java

@RequestMapping(method = RequestMethod.GET, value = "/behandlung/afterlogout")
public String afterLogout(HttpSession session, HttpServletRequest request) {
    new Conversation(request.getSession(), request).retrieve();
    return processPage(session.getServletContext(), null);
}