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:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationFilterTest.java

@Test
public void doFilterTestAnyPath() throws IOException, ServletException {
    HttpServletRequest servletRequest = mock(HttpServletRequest.class);
    HttpServletResponse servletResponse = mock(HttpServletResponse.class);
    FilterChain filterChain = mock(FilterChain.class);
    HttpSession httpSession = mock(HttpSession.class);
    Authentication authResult = mock(Authentication.class);
    PaasManagerUser paasUser = mock(PaasManagerUser.class);

    when(servletRequest.getHeader(OpenStackAuthenticationFilter.OPENSTACK_HEADER_TOKEN))
            .thenReturn("3df25213cac246f8bccad5c70cb3582e").thenReturn("00000000000000000000000000000194")
            .thenReturn("1234");
    when(servletRequest.getRequestURI()).thenReturn("/vdc/00000000000000000000000000000194/");
    when(servletRequest.getPathInfo()).thenReturn("/path");
    when(servletRequest.getSession()).thenReturn(httpSession);
    when(httpSession.getId()).thenReturn("1234");
    when(authenticationManager.authenticate(any(Authentication.class))).thenReturn(authResult);

    when(authResult.getPrincipal()).thenReturn(paasUser);

    openStackAuthenticationFilter.doFilter(servletRequest, servletResponse, filterChain);
}

From source file:com.nec.harvest.servlet.listener.HarvestSessionListener.java

@Override
public void sessionDestroyed(HttpSessionEvent event) {
    activeSessions--;//w w w  .jav a2s  . c o m

    // ?
    HttpSession session = event.getSession();
    Assert.notNull(session, "No HttpSession Specified");

    ServletContext ctx = session.getServletContext();
    ctx.removeAttribute(Constants.USER_LOGGED_IN_LASTTIME);
    ctx.removeAttribute(Constants.SESS_ORGANIZATION_CODE);
    ctx.removeAttribute(Constants.SESS_BUSINESS_DAY);

    if (SecurityContextHolder.getContext().getAuthentication() != null) {
        // Remove from LRU Cache
        AuthenticatedUserDetails.removeUserPrincipal();

        // Empty authentication
        SecurityContextHolder.getContext().setAuthentication(null);
    }

    // ??????
    logger.info("A HttpSession [{}] is going to be destroyed", session.getId());
}

From source file:jp.terasoluna.fw.web.thin.SessionLockControlFilter.java

/**
 * ZbV???s?B/*from   ww w.  j  ava 2s .  c o m*/
 * @param req HTTPNGXg
 * @param res HTTPX|X
 * @param chain tB^`F?[
 * @throws IOException I/OG?[
 * @throws ServletException T?[ubgO
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse,
 *      javax.servlet.FilterChain)
 */
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
        throws IOException, ServletException {
    HttpSession session = ((HttpServletRequest) req).getSession(false);
    if (session != null) {
        // ZbVpL?A??s?B
        if (threshold < 0) {
            // l???A
            // Xbh?A?A
            // P?synchronized?s?B
            log.debug("use synchronized lock.");
            synchronized (session.getId().intern()) {
                chain.doFilter(req, res);
            }
        } else {
            // ?g?ASessionLockReferencel?A
            // limitedLockMapGg?[???B
            // (LimitedLockQ???AGC?(LimitedLockCX^X)?A
            // SessionLockReference?g?B)
            SessionLockReference oldRef = null;
            while ((oldRef = (SessionLockReference) sessionLockRefQueue.poll()) != null) {

                // limitedLockMapGg?[???A
                // mF???B
                // (LimitedLockQ??A
                // SessionLockReference(WeakReference)ReferenceQueue
                // ^CO?A
                // limitedLockMapSessionLockReference??AmF?B)
                // mF???AZbVIDput?A???A
                // put?bN?AZbVID?bN?B
                synchronized (oldRef.getSessionId().intern()) {
                    if (oldRef == limitedLockMap.get(oldRef.getSessionId())) {
                        limitedLockMap.remove(oldRef.getSessionId());
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("LimitedLock is deallocated. sessionId = " + oldRef.getSessionId()
                                + ", SessionLockReference = " + oldRef);
                    }
                }
            }

            LimitedLock lock = null;
            synchronized (session.getId().intern()) {
                SessionLockReference sessionLockRef = limitedLockMap.get(session.getId());
                if (sessionLockRef != null) {
                    lock = sessionLockRef.get();
                }
                if (lock == null) {
                    lock = createLimitedLock();
                    sessionLockRef = new SessionLockReference(session.getId(), lock, sessionLockRefQueue);

                    limitedLockMap.put(session.getId(), sessionLockRef);
                    if (log.isDebugEnabled()) {
                        log.debug("LimitedLock is allocated. sessionId = " + session.getId() + ", "
                                + INIT_PARAM_THRESHOLD + " = " + threshold + ", SessionLockReference = "
                                + sessionLockRef);
                    }
                }
            }

            try {
                log.debug("use LimitedLock.");
                lockLimitedLock((HttpServletRequest) req, lock);
                chain.doFilter(req, res);
            } catch (InterruptedException e) {
                // ZbV???A
                // x?d??[h?A?bNXbhl?A
                // NGXg???s?A
                // X|X?I?B
                log.info("interrupt wait for lock.");
                if (interruptResponseCode >= 0) {
                    ((HttpServletResponse) res).sendError(interruptResponseCode);
                }
            } finally {
                unlockLimitedLock((HttpServletRequest) req, lock);
            }
        }
    } else {
        log.debug("not lock.");
        chain.doFilter(req, res);
    }
}

From source file:org.apache.struts.webapp.example2.SaveSubscriptionAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//w ww  .  j  a va  2  s. c  o m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param form The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes and parameters we will need
    Locale locale = getLocale(request);
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();
    SubscriptionForm subform = (SubscriptionForm) form;
    String action = subform.getAction();
    if (action == null) {
        action = "?";
    }
    if (log.isDebugEnabled()) {
        log.debug("SaveSubscriptionAction:  Processing " + action + " action");
    }

    // Is there a currently logged on user?
    User user = (User) session.getAttribute(Constants.USER_KEY);
    if (user == null) {
        if (log.isTraceEnabled()) {
            log.trace(" User is not logged on in session " + session.getId());
        }
        return (mapping.findForward("logon"));
    }

    // Was this transaction cancelled?
    if (isCancelled(request)) {
        if (log.isTraceEnabled()) {
            log.trace(" Transaction '" + action + "' was cancelled");
        }
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        return (mapping.findForward("success"));
    }

    // Is there a related Subscription object?
    Subscription subscription = (Subscription) session.getAttribute(Constants.SUBSCRIPTION_KEY);
    if ("Create".equals(action)) {
        if (log.isTraceEnabled()) {
            log.trace(" Creating subscription for mail server '" + subform.getHost() + "'");
        }
        subscription = user.createSubscription(subform.getHost());
    }
    if (subscription == null) {
        if (log.isTraceEnabled()) {
            log.trace(" Missing subscription for user '" + user.getUsername() + "'");
        }
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, messages.getMessage("error.noSubscription"));
        return (null);
    }

    // Was this transaction a Delete?
    if (action.equals("Delete")) {
        if (log.isTraceEnabled()) {
            log.trace(" Deleting mail server '" + subscription.getHost() + "' for user '" + user.getUsername()
                    + "'");
        }
        user.removeSubscription(subscription);
        session.removeAttribute(Constants.SUBSCRIPTION_KEY);
        try {
            UserDatabase database = (UserDatabase) servlet.getServletContext()
                    .getAttribute(Constants.DATABASE_KEY);
            database.save();
        } catch (Exception e) {
            log.error("Database save", e);
        }
        return (mapping.findForward("success"));
    }

    // All required validations were done by the form itself

    // Update the persistent subscription information
    if (log.isTraceEnabled()) {
        log.trace(" Populating database from form bean");
    }
    try {
        PropertyUtils.copyProperties(subscription, subform);
    } catch (InvocationTargetException e) {
        Throwable t = e.getTargetException();
        if (t == null)
            t = e;
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    } catch (Throwable t) {
        log.error("Subscription.populate", t);
        throw new ServletException("Subscription.populate", t);
    }

    try {
        UserDatabase database = (UserDatabase) servlet.getServletContext().getAttribute(Constants.DATABASE_KEY);
        database.save();
    } catch (Exception e) {
        log.error("Database save", e);
    }

    // Remove the obsolete form bean and current subscription
    if (mapping.getAttribute() != null) {
        if ("request".equals(mapping.getScope()))
            request.removeAttribute(mapping.getAttribute());
        else
            session.removeAttribute(mapping.getAttribute());
    }
    session.removeAttribute(Constants.SUBSCRIPTION_KEY);

    // Forward control to the specified success URI
    if (log.isTraceEnabled()) {
        log.trace(" Forwarding to success page");
    }
    return (mapping.findForward("success"));

}

From source file:it.scoppelletti.programmerpower.web.security.CasClient.java

/**
 * Colleziona una sessione autenticata.//from  w  w  w. j  a va 2s .c  o  m
 * 
 * @param serviceTicket Ticket di servizio.
 * @param session       Sessione.
 */
public void addAuthenticatedSession(String serviceTicket, HttpSession session) {
    if (Strings.isNullOrEmpty(serviceTicket)) {
        throw new ArgumentNullException("serviceTicket");
    }
    if (session == null) {
        throw new ArgumentNullException("session");
    }
    if (mySessionStorage == null) {
        throw new PropertyNotSetException(toString(), "sessionMappingStorage");
    }

    myLogger.debug("Storing authenticated session {}.", session.getId());
    try {
        mySessionStorage.removeBySessionById(session.getId());
    } catch (Exception ex) {
        // NOP
    }
    mySessionStorage.addSessionById(serviceTicket, session);
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public AdminSession newAdminSession(HttpServletRequest req, HTTPRequestHeader h)
        throws InvalidPasswordException, WebMailException {
    final HttpSession sess = req.getSession(true);

    if (sess.getAttribute("webmail.session") == null) {
        final AdminSession n = new AdminSession(this, req, h);
        timer.addTimeableConnection(n);/*from w  ww  .j a  v a 2s  .c  o  m*/
        n.login(h);
        sess.setAttribute("webmail.session", n);
        sessions.put(sess.getId(), n);
        log.debug("Created new Session: " + sess.getId());
        return n;
    } else {
        final Object tmp = sess.getAttribute("webmail.session");
        if (tmp instanceof AdminSession) {
            final AdminSession n = (AdminSession) tmp;
            n.login(h);
            log.debug("Using old Session: " + sess.getId());
            return n;
        } else {
            sess.setAttribute("webmail.session", null);
            log.debug("Reusing old UserSession: " + sess.getId());
            return newAdminSession(req, h);
        }
    }
}

From source file:net.wastl.webmail.server.WebMailServlet.java

public WebMailSession newSession(HttpServletRequest req, HTTPRequestHeader h)
        throws UserDataException, InvalidPasswordException, WebMailException {
    final HttpSession sess = req.getSession(true);

    if (sess.getAttribute("webmail.session") == null) {
        final WebMailSession n = new WebMailSession(this, req, h);
        timer.addTimeableConnection(n);/*from   w  w  w.  j  av a 2  s.co m*/
        n.login();
        sess.setAttribute("webmail.session", n);
        sessions.put(sess.getId(), n);
        log.debug("Created new Session: " + sess.getId());
        return n;
    } else {
        final Object tmp = sess.getAttribute("webmail.session");
        if (tmp instanceof WebMailSession) {
            final WebMailSession n = (WebMailSession) tmp;
            n.login();
            log.debug("Using old Session: " + sess.getId());
            return n;
        } else {
            /*
             * If we have an admin session, get rid of it and create a new
             * session
             */
            sess.setAttribute("webmail.session", null);
            log.debug("Reusing old AdminSession: " + sess.getId());
            return newSession(req, h);
        }
    }
}

From source file:com.primeleaf.krystal.web.action.console.NewDocumentAction.java

@SuppressWarnings("rawtypes")
public WebView execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    HttpSession session = request.getSession();
    User loggedInUser = (User) session.getAttribute(HTTPConstants.SESSION_KRYSTAL);
    String classId = request.getParameter("classid") != null ? request.getParameter("classid") : "0";

    if (request.getMethod().equalsIgnoreCase("POST")) {
        try {/*from   ww w  .  j  a  va  2s . c om*/
            String userName = loggedInUser.getUserName();
            String sessionid = (String) session.getId();

            String tempFilePath = System.getProperty("java.io.tmpdir");

            if (!(tempFilePath.endsWith("/") || tempFilePath.endsWith("\\"))) {
                tempFilePath += System.getProperty("file.separator");
            }
            tempFilePath += userName + "_" + sessionid;

            //variables
            String fileName = "", ext = "", comments = "";
            File file = null;
            // Create a factory for disk-based file items
            FileItemFactory factory = new DiskFileItemFactory();
            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(HTTPConstants.CHARACTER_ENCODING);

            //Create a file upload progress listener
            FileUploadProgressListener listener = new FileUploadProgressListener();
            upload.setProgressListener(listener);
            //put the listener in session
            session.setAttribute("LISTENER", listener);
            session.setAttribute("UPLOAD_ERROR", null);
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));

            DocumentClass documentClass = null;

            Hashtable<String, String> indexRecord = new Hashtable<String, String>();
            String name = "";
            String value = "";

            List listItems = upload.parseRequest((HttpServletRequest) request);

            Iterator iter = listItems.iterator();
            FileItem fileItem = null;
            while (iter.hasNext()) {
                fileItem = (FileItem) iter.next();
                if (fileItem.isFormField()) {
                    name = fileItem.getFieldName();
                    value = fileItem.getString(HTTPConstants.CHARACTER_ENCODING);
                    if (name.equals("classid")) {
                        classId = value;
                    }
                    if (name.equals("txtNote")) {
                        comments = value;
                    }
                } else {
                    try {
                        fileName = fileItem.getName();
                        file = new File(fileName);
                        fileName = file.getName();
                        ext = fileName.substring(fileName.lastIndexOf(".") + 1).toUpperCase();
                        file = new File(tempFilePath + "." + ext);
                        fileItem.write(file);
                    } catch (Exception ex) {
                        session.setAttribute("UPLOAD_ERROR", ex.getLocalizedMessage());
                        return null;
                    }
                }
            } //if

            if (file.length() <= 0) { //code for checking minimum size of file
                session.setAttribute("UPLOAD_ERROR", "Zero length document");
                return null;
            }
            documentClass = DocumentClassDAO.getInstance().readDocumentClassById(Integer.parseInt(classId));
            if (documentClass == null) {
                session.setAttribute("UPLOAD_ERROR", "Invalid document class");
                return null;
            }
            AccessControlManager aclManager = new AccessControlManager();
            ACL acl = aclManager.getACL(documentClass, loggedInUser);

            if (!acl.canCreate()) {
                session.setAttribute("UPLOAD_ERROR", "Access Denied");
                return null;
            }

            long usedStorage = DocumentDAO.getInstance().documentSize();
            long availableStorage = ServerConstants.MAX_STORAGE - usedStorage;

            if (file.length() > availableStorage) {
                session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(0));
                session.setAttribute("UPLOAD_ERROR", "Document upload failed. Storage limit exceeded.");
                return null;
            }
            String indexValue = "";
            String indexName = "";
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(50));

            for (IndexDefinition indexDefinition : documentClass.getIndexDefinitions()) {
                indexName = indexDefinition.getIndexColumnName();
                Iterator iter1 = listItems.iterator();
                while (iter1.hasNext()) {
                    FileItem item1 = (FileItem) iter1.next();
                    if (item1.isFormField()) {
                        name = item1.getFieldName();
                        value = item1.getString(HTTPConstants.CHARACTER_ENCODING);
                        if (name.equals(indexName)) {
                            indexValue = value;
                            String errorMessage = "";
                            if (indexValue != null) {
                                if (indexDefinition.isMandatory()) {
                                    if (indexValue.trim().length() <= 0) {
                                        errorMessage = "Invalid input for "
                                                + indexDefinition.getIndexDisplayName();
                                        session.setAttribute("UPLOAD_ERROR", errorMessage);
                                        return null;
                                    }
                                }
                                if (IndexDefinition.INDEXTYPE_NUMBER
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.matchRegexp(indexValue,
                                                HTTPConstants.NUMERIC_REGEXP)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                } else if (IndexDefinition.INDEXTYPE_DATE
                                        .equalsIgnoreCase(indexDefinition.getIndexType())) {
                                    if (indexValue.trim().length() > 0) {
                                        if (!GenericValidator.isDate(indexValue, "yyyy-MM-dd", true)) {
                                            errorMessage = "Invalid input for "
                                                    + indexDefinition.getIndexDisplayName();
                                            session.setAttribute("UPLOAD_ERROR", errorMessage);
                                            return null;
                                        }
                                    }
                                }
                                if (indexValue.trim().length() > indexDefinition.getIndexMaxLength()) { //code for checking index field length
                                    errorMessage = "Document index size exceeded for " + "Index Name : "
                                            + indexDefinition.getIndexDisplayName() + " [ " + "Index Length : "
                                            + indexDefinition.getIndexMaxLength() + " , " + "Actual Length : "
                                            + indexValue.length() + " ]";
                                    session.setAttribute("UPLOAD_ERROR", errorMessage);
                                    return null;
                                }
                            }
                            indexRecord.put(indexName, indexValue);
                        }
                    }
                } //while iter
            } //while indexCfgList
            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(70));

            DocumentRevision documentRevision = new DocumentRevision();
            documentRevision.setClassId(documentClass.getClassId());
            documentRevision.setDocumentId(0);
            documentRevision.setRevisionId("1.0");
            documentRevision.setDocumentFile(file);
            documentRevision.setUserName(loggedInUser.getUserName());
            documentRevision.setIndexRecord(indexRecord);
            documentRevision.setComments(comments);

            DocumentManager documentManager = new DocumentManager();
            documentManager.storeDocument(documentRevision, documentClass);

            //Log the entry to audit logs 
            AuditLogManager.log(new AuditLogRecord(documentRevision.getDocumentId(),
                    AuditLogRecord.OBJECT_DOCUMENT, AuditLogRecord.ACTION_CREATED, userName,
                    request.getRemoteAddr(), AuditLogRecord.LEVEL_INFO, "", "Document created"));

            session.setAttribute("UPLOAD_PERCENT_COMPLETE", new Long(100));
        } catch (Exception e) {
            e.printStackTrace(System.out);
        }
        return null;
    } else {
        try {
            ArrayList<DocumentClass> availableDocumentClasses = DocumentClassDAO.getInstance()
                    .readDocumentClasses(" ACTIVE = 'Y'");
            ArrayList<DocumentClass> documentClasses = new ArrayList<DocumentClass>();
            AccessControlManager aclManager = new AccessControlManager();
            for (DocumentClass documentClass : availableDocumentClasses) {
                ACL acl = aclManager.getACL(documentClass, loggedInUser);
                if (acl.canCreate()) {
                    documentClasses.add(documentClass);
                }
            }
            int documentClassId = 0;
            try {
                documentClassId = Integer.parseInt(classId);
            } catch (Exception ex) {
                request.setAttribute(HTTPConstants.REQUEST_ERROR, "Invalid input");
                return (new NewDocumentView(request, response));
            }
            if (documentClassId > 0) {
                DocumentClass selectedDocumentClass = DocumentClassDAO.getInstance()
                        .readDocumentClassById(documentClassId);
                request.setAttribute("DOCUMENTCLASS", selectedDocumentClass);
            }
            request.setAttribute("CLASSID", documentClassId);
            request.setAttribute("CLASSLIST", documentClasses);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    return (new NewDocumentView(request, response));
}

From source file:com.curl.orb.servlet.DestroyInstanceServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
    super.doPost(request, response);
    Log log = LogFactory.getLog(getClass());
    DestroyInstanceRequest destroyInstanceRequest = (DestroyInstanceRequest) InstanceManagementUtil
            .getRequest(request);/*from   w  w  w. j  a va  2 s  .c om*/
    try {
        HttpSession session = request.getSession(false);
        if (session == null)
            throw new InstanceManagementException("Does not exist HttpSession.");
        String objectId = destroyInstanceRequest.getObjectId();
        Object obj = session.getAttribute(objectId);
        // security
        RemoteServiceAnnotationChecker.check(obj.getClass(), environment);
        // remove the object from session
        session.removeAttribute(objectId);

        // kill session
        if (destroyInstanceRequest.getHeader() != null
                && destroyInstanceRequest.getHeader().containsKey(KILL_SESSION)
                && (Boolean) destroyInstanceRequest.getHeader().get(KILL_SESSION)) {
            log.debug("Killed HttpSession:" + session.getId());
            session.invalidate();
        }
        InstanceManagementUtil.setResponse(request, null, null);
        log.debug("Request destroyed");
    }
    // IOException, SerializerException, InstanceManagementException
    catch (Exception e) {
        InstanceManagementUtil.setResponse(request, e, null);
    }
}

From source file:org.wso2.carbon.ml.rest.api.LoginLogoutApiV10.java

/**
 * Login/*from w  w  w.j ava2s . c o  m*/
 */
@POST
@Path("/login")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response login() {
    //create session if not found
    HttpSession httpSession = httpServletRequest.getSession();
    PrivilegedCarbonContext carbonContext = PrivilegedCarbonContext.getThreadLocalCarbonContext();
    String username = carbonContext.getUsername();
    httpSession.setAttribute("userName", username);
    String tenantDomain = carbonContext.getTenantDomain();
    httpSession.setAttribute("tenantDomain", tenantDomain);
    int tenantId = carbonContext.getTenantId();
    httpSession.setAttribute("tenantId", tenantId);
    auditLog.info(
            String.format(
                    "User [name] %s of tenant [id] %s [domain] %s is logged-in into WSO2 Machine Learner. "
                            + "Granted session id is %s",
                    username, tenantId, tenantDomain, httpSession.getId()));
    return Response.status(Response.Status.OK).entity("User logged in: " + username).build();
}