Example usage for javax.servlet.http HttpSession getId

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

Introduction

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

Prototype

public String getId();

Source Link

Document

Returns a string containing the unique identifier assigned to this session.

Usage

From source file:edu.harvard.i2b2.fhir.server.ws.I2b2FhirWS.java

public Response generateResponse(@HeaderParam("accept") String acceptHeader,
        @Context HttpServletRequest request, Resource r)
        throws JAXBException, IOException, ParserConfigurationException, SAXException {
    if (r == null)
        throw new IllegalArgumentException("input resource is null");
    String mediaType;//from  w ww .j  a  v  a 2  s  .  c  o m
    String outTxt = "-";
    HttpSession session = request.getSession();
    if (acceptHeader.contains("application/json") || acceptHeader.contains("application/json+fhir")) {
        outTxt = FhirUtil.resourceToJsonString(r);
        mediaType = "application/json";
    } else {
        outTxt = JAXBUtil.toXml(r);
        mediaType = "application/xml+fhir";
    }
    outTxt = I2b2Helper.removeSpace(outTxt);
    logger.info("acceptHeader:" + acceptHeader);

    return Response.ok().type(mediaType).header("session_id", session.getId()).entity(outTxt).build();

}

From source file:com.haulmont.cuba.web.sys.CubaApplicationServlet.java

protected void redirectToApp(HttpServletRequest request, HttpServletResponse response, String contextName,
        String[] uriParts, String action) throws IOException {
    StringBuilder redirectAddress = new StringBuilder();
    for (int i = 0; i < uriParts.length; i++) {
        redirectAddress.append(uriParts[i]);
        if (uriParts[i].equals(contextName)) {
            break;
        }//  w  w  w.  ja  va  2  s. c  om
        if (i < uriParts.length - 1) {
            redirectAddress.append("/");
        }
    }

    // redirect to ROOT context
    if (redirectAddress.length() == 0) {
        redirectAddress.append("/");
    }

    HttpSession httpSession = request.getSession();
    if (action != null) {
        httpSession.setAttribute(AppUI.LAST_REQUEST_ACTION_ATTR, action);
    }
    if (request.getParameterNames().hasMoreElements()) {
        Map<String, String> params = new HashMap<>();
        Enumeration parameterNames = request.getParameterNames();
        while (parameterNames.hasMoreElements()) {
            String name = (String) parameterNames.nextElement();
            if (!FROM_HTML_REDIRECT_PARAM.equals(name)) {
                params.put(name, request.getParameter(name));
            }
        }
        httpSession.setAttribute(AppUI.LAST_REQUEST_PARAMS_ATTR, params);
    }

    statisticsCounter.incWebRequestsCount();
    String httpSessionId = httpSession.getId();
    log.debug("Redirect to application {}", httpSessionId);

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if ("JSESSIONID".equals(cookie.getName()) && !httpSessionId.equals(cookie.getValue())) {
                cookie.setValue(httpSessionId);
                break;
            }
        }
    }
    response.sendRedirect(redirectAddress.toString());
}

From source file:com.bluexml.xforms.controller.navigation.NavigationManager.java

/**
 * Send XForms to Chiba filter.<br>
 * Inserts session id into form.<br>
 * No data manipulation has to be made here.
 * /*from   w  w w. j a  v  a 2s .  c om*/
 * @param req
 *            the req
 * @param resp
 *            the resp
 * @throws ServletException
 *             the servlet exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public void sendXForms(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession session = req.getSession(true);
    String sessionId = session.getId();

    controller = getController();

    String testStr = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_SERVE_TEST_PAGE.getText()));
    boolean serveTestPage = StringUtils.equals(testStr, "true");
    String pageId = StringUtils.trimToNull(req.getParameter(PAGE_ID));

    // called from a direct link? set our info (pageId, stackId)
    if (pageId == null) {
        // check for a possible initialisation call
        boolean isInit = StringUtils.equals(req.getParameter(MsgId.PARAM_INIT_CALL.getText()), "true");
        if (isInit) {
            ServletOutputStream stream = resp.getOutputStream();
            String result = (loadConfiguration(req, true) == -1) ? "success" : "failure";
            stream.write(result.getBytes());
            stream.close();
            return;
        }
        pageId = NavigationSessionListener.getPageId(sessionId);
        NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);

        // check whether reloading of the mapping.xml file was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_MAPPING_FILE.getText()), "true")) {
            controller.performDynamicReload();
        }
        // check whether reloading of properties/configuration files was asked for
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_RELOAD_PROPERTIES.getText()), "true")) {
            int resLoad = loadConfiguration(req, false);
            if (logger.isDebugEnabled()) {
                if (resLoad == -1) {
                    logger.debug("Reloaded properties: OK.");
                } else {
                    String reason = "";
                    switch (resLoad) {
                    case 0:
                        reason = "an exception occured";
                        break;
                    case 1:
                        reason = "properties files";
                        break;
                    case 2:
                        reason = "redirection file";
                        break;
                    }
                    logger.debug("Failed in loading the configuration. Reason: " + reason);
                }
            }
        }
        // set specific CSS if given
        this.setCssUrl(req);
        // initial status message. CAUTION: may be overridden later in case of errors.
        String statusMsg = StringUtils.trimToNull(req.getParameter(MsgId.PARAM_STATUS_MSG.getText()));
        if (statusMsg != null) {
            navigationPath.setStatusMsg(statusMsg);
        }
        // deal with standalone mode
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "true")) {
            controller.setStandaloneMode(true);
        }
        if (StringUtils.equals(req.getParameter(MsgId.PARAM_STANDALONE.getText()), "false")) {
            controller.setStandaloneMode(false);
        }

        PageInfoBean pageInfo = collectPageInfo(req);
        // save session and URL we were called with (useful when a host is multi-domain'ed)
        String curServletURL = this.registerSessionURL(req, sessionId);
        // remember where we are
        navigationPath.setCurrentPage(pageInfo);
        String location = curServletURL + "?pageId=" + pageId + "&stackId=" + navigationPath.getSize();
        // propagate queryString
        location += "&" + req.getQueryString();
        if (serveTestPage == false) {
            // redirect the web client, providing ids we need
            resp.sendRedirect(resp.encodeRedirectURL(location));
            return;
        }
    }
    // the ids are available
    NavigationPath navigationPath = NavigationSessionListener.getNavigationPath(sessionId, pageId);
    if (navigationPath.isEmpty()) {
        // the servlet is called directly with ids we did not register
        throw new ServletException(MsgPool.getMsg(MsgId.MSG_SESSION_TIMED_OUT));
    }
    Page currentPage = navigationPath.peekCurrentPage();
    // set the warning if page was called with an object it can't display
    if (currentPage.isWrongCallType()) {
        navigationPath.setStatusMsg("WARNING: the data Id provided is not appropriate for this form.");
    }

    // get the form template as a string
    String statusDisplayedMsg = navigationPath.getStatusDisplayedMsg();
    Document doc = loadXFormsDocument(req, sessionId, pageId, statusDisplayedMsg, currentPage);

    req.setAttribute(WebFactory.XFORMS_NODE, doc);
    resp.getOutputStream().close();
}

From source file:gov.nih.nci.security.upt.actions.CommonAssociationAction.java

public String loadAssociation(BaseAssociationForm baseAssociationForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logAssociation.isDebugEnabled())
            logAssociation.debug("||" + baseAssociationForm.getFormName()
                    + "|loadAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }/*from  w w  w.j ava2  s. co m*/
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        baseAssociationForm.setRequest(request);
        baseAssociationForm.buildAssociationObject(userProvisioningManager);
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logAssociation.isDebugEnabled())
            logAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + baseAssociationForm.getFormName()
                    + "|loadAssociation|Failure|Error Loading Association for the "
                    + baseAssociationForm.getFormName() + "|" + cse.getMessage());
    }
    if (logAssociation.isDebugEnabled())
        logAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseAssociationForm.getFormName()
                + "|loadAssociation|Success|Success in loading association for "
                + baseAssociationForm.getFormName() + " object|");
    return ForwardConstants.LOAD_ASSOCIATION_SUCCESS;
}

From source file:org.apache.cocoon.transformation.XSLTTransformer.java

/**
 * Get the parameters for the logicsheet
 *//*from   w w w .ja  va2s .c om*/
protected Map getLogicSheetParameters() {
    if (this.logicSheetParameters != null) {
        return this.logicSheetParameters;
    }
    HashMap map = null;
    if (par != null) {
        String[] params = par.getNames();
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                String name = params[i];
                if (isValidXSLTParameterName(name)) {
                    String value = par.getParameter(name, null);
                    if (value != null) {
                        if (map == null) {
                            map = new HashMap(params.length);
                        }
                        map.put(name, value);
                    }
                }
            }
        }
    }

    if (this._useParameters) {
        Request request = ObjectModelHelper.getRequest(objectModel);

        Enumeration parameters = request.getParameterNames();
        if (parameters != null) {
            while (parameters.hasMoreElements()) {
                String name = (String) parameters.nextElement();
                if (isValidXSLTParameterName(name)) {
                    String value = request.getParameter(name);
                    if (map == null) {
                        map = new HashMap();
                    }
                    map.put(name, value);
                }
            }
        }
    }

    if (this._useSessionInfo) {
        final Request request = ObjectModelHelper.getRequest(objectModel);
        if (map == null) {
            map = new HashMap(6);
        }

        final HttpSession session = request.getSession(false);
        if (session != null) {
            map.put("session-available", "true");
            map.put("session-is-new", BooleanUtils.toStringTrueFalse(session.isNew()));
            map.put("session-id-from-cookie",
                    BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdFromCookie()));
            map.put("session-id-from-url",
                    BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdFromURL()));
            map.put("session-valid", BooleanUtils.toStringTrueFalse(request.isRequestedSessionIdValid()));
            map.put("session-id", session.getId());
        } else {
            map.put("session-available", "false");
        }
    }

    if (this._useCookies) {
        Request request = ObjectModelHelper.getRequest(objectModel);
        Cookie cookies[] = request.getCookies();
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                String name = cookies[i].getName();
                if (isValidXSLTParameterName(name)) {
                    String value = cookies[i].getValue();
                    if (map == null) {
                        map = new HashMap(cookies.length);
                    }
                    map.put(name, value);
                }
            }
        }
    }
    this.logicSheetParameters = map;
    return this.logicSheetParameters;
}

From source file:com.flexive.shared.FxContext.java

/**
 * Constructor//from   w w  w  .j  ava2  s  .  c om
 *
 * @param request    the request
 * @param divisionId the division
 * @param isWebdav   true if this is an webdav request
 * @param forceSession
 */
private FxContext(HttpServletRequest request, int divisionId, boolean isWebdav, boolean forceSession) {
    final HttpSession session = request.getSession(forceSession);
    this.sessionID = session != null ? session.getId() : null;
    this.requestURI = request.getRequestURI();
    this.contextPath = request.getContextPath();
    this.serverName = request.getServerName();
    this.serverPort = request.getServerPort();
    this.requestUriNoContext = request.getRequestURI().substring(request.getContextPath().length());
    this.webDAV = isWebdav;
    if (this.webDAV) {
        // Cut away servlet path, eg. "/webdav/"
        this.requestUriNoContext = this.requestUriNoContext.substring(request.getServletPath().length());
    }
    this.globalAuthenticated = session != null && session.getAttribute(ADMIN_AUTHENTICATED) != null;
    //get the real remote host incase a proxy server is used
    String forwardedFor = request.getHeader("x-forwarded-for");
    if (forwardedFor != null && !StringUtils.isBlank(String.valueOf(forwardedFor))) {
        final int clientSplit = forwardedFor.indexOf(',');
        final String clientIp = clientSplit == -1 ? forwardedFor : forwardedFor.substring(0, clientSplit);
        this.remoteHost = clientIp.replace("[", "").replace("]", "");
    } else {
        this.remoteHost = request.getRemoteAddr();
    }
    this.division = divisionId;
    initFormatters();
}

From source file:com.haulmont.cuba.web.security.idp.BaseIdpSessionFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    // send static files without authentication
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (StringUtils.startsWith(httpRequest.getRequestURI(), httpRequest.getContextPath() + "/VAADIN/")) {
        chain.doFilter(request, response);
        return;//from   w  w w  .j  av  a  2 s . co  m
    }

    HttpServletResponse httpResponse = (HttpServletResponse) response;
    String idpBaseURL = webIdpConfig.getIdpBaseURL();
    if (Strings.isNullOrEmpty(idpBaseURL)) {
        log.error("Application property cuba.web.idp.url is not set");
        httpResponse.setStatus(500);
        return;
    }

    if (!idpBaseURL.endsWith("/")) {
        idpBaseURL += "/";
    }

    String requestUrl = httpRequest.getRequestURL().toString();
    if (StringUtils.startsWith(requestUrl, idpBaseURL)) {
        chain.doFilter(httpRequest, response);
        return;
    }

    HttpSession session = httpRequest.getSession(true);
    Lock sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    if (sessionLock == null) {
        sessionCheckLock.lock();
        try {
            sessionLock = (Lock) session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
            if (sessionLock == null) {
                sessionLock = new ReentrantLock();
                session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            }
        } finally {
            sessionCheckLock.unlock();
        }
    }

    IdpSession boundIdpSession;
    sessionLock.lock();

    try {
        session.getAttribute(IDP_SESSION_LOCK_ATTRIBUTE);
    } catch (IllegalStateException e) {
        // Someone might have invalidated the session between fetching the lock and acquiring it.
        sessionLock.unlock();

        log.debug("Invalidated session {}", session.getId());
        httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
        return;
    }

    try {
        if ("GET".equals(httpRequest.getMethod())
                && httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM) != null) {
            String idpTicket = httpRequest.getParameter(IDP_TICKET_REQUEST_PARAM);

            IdpSession idpSession;
            try {
                idpSession = getIdpSession(idpTicket);
            } catch (IdpActivationException e) {
                log.error("Unable to obtain IDP session by ticket", e);
                httpResponse.setStatus(500);
                return;
            }

            if (idpSession == null) {
                log.warn("Used old IDP ticket {}, send redirect", idpTicket);
                // used old ticket, send redirect
                httpResponse.sendRedirect(getIdpRedirectUrl());
                return;
            }

            session.invalidate();

            session = httpRequest.getSession(true);
            session.setAttribute(IDP_SESSION_LOCK_ATTRIBUTE, sessionLock);
            session.setAttribute(IDP_SESSION_ATTRIBUTE, idpSession);

            log.debug("IDP session {} obtained, redirect to application", idpSession);

            // redirect to application without parameters
            httpResponse.sendRedirect(httpRequest.getRequestURL().toString());
            return;
        }

        if (session.getAttribute(IDP_SESSION_ATTRIBUTE) == null) {
            if ("GET".equals(httpRequest.getMethod()) && !StringUtils.startsWith(httpRequest.getRequestURI(),
                    httpRequest.getContextPath() + "/PUSH")) {
                httpResponse.sendRedirect(getIdpRedirectUrl());
            }
            return;
        }

        boundIdpSession = (IdpSession) session.getAttribute(IDP_SESSION_ATTRIBUTE);
    } finally {
        sessionLock.unlock();
    }

    HttpServletRequest authenticatedRequest = new IdpServletRequestWrapper(httpRequest,
            new IdpSessionPrincipalImpl(boundIdpSession));

    chain.doFilter(authenticatedRequest, response);
}

From source file:UsingContexts.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    HttpSession session = request.getSession(true);

    Integer counter2 = (Integer) getServletContext().getAttribute("counter2");

    if (counter2 == null) {
        counter2 = new Integer(1);
    } else {/*from   www  .j a  va  2 s  . c o m*/
        counter2 = new Integer(counter2.intValue() + 1);
    }

    getServletContext().setAttribute("counter2", counter2);

    Integer counter = (Integer) session.getAttribute("counter");

    if (counter == null) {
        counter = new Integer(1);
    } else {
        counter = new Integer(counter.intValue() + 1);
    }

    session.setAttribute("counter", counter);

    out.println("<HTML>");
    out.println("<HEAD>");
    out.println("<TITLE>");
    out.println("Using Contexts");
    out.println("</TITLE>");
    out.println("</HEAD>");
    out.println("<BODY>");
    out.println("<H1>Using Contexts</H1>");

    out.println("Welcome! You have been here " + counter + " times.<BR>");

    out.println("Total page accesses: " + counter2 + "<BR>");

    if (session.isNew()) {
        out.println("This is a new session.<BR>");
    } else {
        out.println("This is not a new session.<BR>");
    }

    out.println("The session ID: " + session.getId() + "<BR>");
    out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>");
    out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>");

    out.println("</BODY>");
    out.println("</HTML>");
}

From source file:gov.nih.nci.security.upt.actions.CommonDBAction.java

public String loadAdd(BaseDBForm baseDBForm) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logDB.isDebugEnabled())
            logDB.debug("||" + baseDBForm.getFormName()
                    + "|loadAdd|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from  w ww  .ja va 2  s .  c o  m

    baseDBForm.resetForm();

    session.setAttribute(DisplayConstants.CURRENT_ACTION, DisplayConstants.ADD);
    session.setAttribute(DisplayConstants.CURRENT_FORM, baseDBForm);
    session.removeAttribute(DisplayConstants.SEARCH_RESULT);
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, DisplayConstants.CREATE_WORKFLOW);

    if (logDB.isDebugEnabled())
        logDB.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + baseDBForm.getFormName() + "|loadAdd|Success|Loading the Add Page||");
    return ForwardConstants.LOAD_ADD_SUCCESS;
}

From source file:gov.nih.nci.security.upt.actions.ApplicationAction.java

public String loadAssociation() throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession();
    session.setAttribute(DisplayConstants.CREATE_WORKFLOW, "0");

    if (session.isNew() || (session.getAttribute(DisplayConstants.LOGIN_OBJECT) == null)) {
        if (logAssociation.isDebugEnabled())
            logAssociation.debug("||" + applicationForm.getFormName()
                    + "|loadAssociation|Failure|No Session or User Object Forwarding to the Login Page||");
        return ForwardConstants.LOGIN_PAGE;
    }//from ww  w. ja v a 2 s  .  c om
    try {
        UserProvisioningManager userProvisioningManager = (UserProvisioningManager) (request.getSession())
                .getAttribute(DisplayConstants.USER_PROVISIONING_MANAGER);
        applicationForm.setRequest(request);
        applicationForm.buildDisplayForm(userProvisioningManager);
        applicationForm.buildAssociationObject(userProvisioningManager);
    } catch (CSException cse) {
        addActionError(org.apache.commons.lang.StringEscapeUtils.escapeHtml(cse.getMessage()));
        if (logAssociation.isDebugEnabled())
            logAssociation.debug(session.getId() + "|"
                    + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                    + applicationForm.getFormName()
                    + "|loadAssociation|Failure|Error Loading Association for the "
                    + applicationForm.getFormName() + "|" + cse.getMessage());
    }
    if (logAssociation.isDebugEnabled())
        logAssociation.debug(session.getId() + "|"
                + ((LoginForm) session.getAttribute(DisplayConstants.LOGIN_OBJECT)).getLoginId() + "|"
                + applicationForm.getFormName() + "|loadAssociation|Success|Success in loading association for "
                + applicationForm.getFormName() + " object|");
    return ForwardConstants.LOAD_ASSOCIATION_SUCCESS;
}