Java Code Examples for javax.servlet.http.HttpSession#getId()

The following examples show how to use javax.servlet.http.HttpSession#getId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SessionListener.java    From javamelody with Apache License 2.0 6 votes vote down vote up
void unregisterInvalidatedSessions() {
	for (final Map.Entry<String, HttpSession> entry : SESSION_MAP_BY_ID.entrySet()) {
		final HttpSession session = entry.getValue();
		if (session.getId() != null) {
			unregisterSessionIfNeeded(session);
		} else {
			// damned JIRA has sessions with null id, when shuting down
			final String sessionId = entry.getKey();
			SESSION_MAP_BY_ID.remove(sessionId);
		}
	}
	// issue 198: in JIRA 4.4.*, sessionCreated is called two times with different sessionId
	// but with the same attributes in the second than the attributes added in the first,
	// so SESSION_COUNT is periodically counted again
	SESSION_COUNT.set(SESSION_MAP_BY_ID.size());
}
 
Example 2
Source File: SessionAndTraceRegistrationFilter.java    From kieker with Apache License 2.0 6 votes vote down vote up
/**
 * If the given {@link ServletRequest} is an instance of {@link HttpServletRequest}, this methods extracts the session ID and registers it in the
 * {@link #SESSION_REGISTRY} in order to be accessible for other probes in this thread. In case no session is associated with this request (or if the request is
 * not an instance of {@link HttpServletRequest}), this method returns without any further actions and returns {@link OperationExecutionRecord#NO_SESSION_ID}.
 *
 * @param request
 *            The request.
 *
 * @return The session ID.
 */
protected String registerSessionInformation(final ServletRequest request) {
	String sessionId = OperationExecutionRecord.NO_SESSION_ID;

	if ((request == null) || !(request instanceof HttpServletRequest)) {
		return sessionId;
	}

	final HttpSession session = ((HttpServletRequest) request).getSession(false);
	if (session != null) {
		sessionId = session.getId();
		SESSION_REGISTRY.storeThreadLocalSessionId(sessionId);
	}

	return sessionId;
}
 
Example 3
Source File: SliceServlet.java    From dawnsci with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Remember with servlets each of these is done on a thread from the
 * pool. Therefore it should filter down giving each session its
 * own object with which to slice. In this way if a user decides to
 * do a long running slice, they only block themselves.
 * 
 * TODO User should be able to cancel slice...
 * 
 */
private void doHandle(HttpServletRequest  request,
					  HttpServletResponse response)  throws IOException, ServletException {
	
	HttpSession sess = request.getSession();
	
	SliceRequest slicer=null;
	
	// Assignment of slicer is synched
	synchronized(LOCK) {
		slicer = (SliceRequest)sess.getAttribute("slicer");
		if (slicer==null) {
			slicer = new SliceRequest(sess.getId());
			sess.setAttribute("slicer", slicer);
		}
	}
	
	try {
	    slicer.slice(request, response);
	    
	} catch (Exception ne) {
		ne.printStackTrace();
		response.setContentType("text/html;charset=utf-8");
		response.setStatus(HttpServletResponse.SC_FORBIDDEN);
		response.getWriter().println("<h1>"+ne.getMessage()+"</h1>");
	}
}
 
Example 4
Source File: SessionListener.java    From khan-session with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
     * Session Created
     * @param sessionEvent
     */
    @Override
    public void sessionCreated(HttpSessionEvent sessionEvent) {
        // Get the session that was created
        HttpSession session = sessionEvent.getSession();
        // Store something in the session, and log a message
        try {
            if( log.isDebugEnabled() ) {
                log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> created sessionEvent=" + sessionEvent);
                log.debug("Session created=" + session.getId());
            }
            String appName = sessionEvent.getSession().getServletContext().getContextPath();
            SessionMonitorMBean sessionMonitorMBean = KhanSessionManager.getInstance(appName).getSessionMonitor();
            if( sessionMonitorMBean != null )
                sessionMonitorMBean.sessionCreated();

            if( session != null && session.getId() != null) {
                SessionId.setKhanSessionId(session.getId(), SessionIdThreadStore.get());
            }
            SessionIdThreadStore.remove();

            if (KhanSessionFilter.getKhanSessionConfig().isAllowDuplicateLogin() == false) {
//                session.setAttribute("khan.uid", SessionLoginManager.getInstance());
                session.setAttribute("khan.uid", null);
            }
            //KhanSessionManager.getInstance(appName).putSessionId(session);

        } catch (Exception e) {
            log.error("Error in setting session attribute: "
                    + e.getMessage(), e);
        }
    }
 
Example 5
Source File: SessionFacade.java    From javalite with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a session ID from underlying session.
 *
 * @return a session ID from underlying session, or null if session does not exist.
 */
public String id(){
    HttpServletRequest r = RequestContext.getHttpRequest();
    if(r == null){
        return null;
    }
    HttpSession session = r.getSession(false);
    return session == null ? null : session.getId();
}
 
Example 6
Source File: MultiSessionAttributeAdapter.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
public static String info(HttpSession s) {
    if (s==null) return "null";
    String hh = getContextPath(s);
    if (Strings.isBlank(hh)) hh = getBundle(s);
    if (Strings.isBlank(hh)) {
        hh = s instanceof Session ? info( ((Session)s).getSessionHandler() ) : "<non-jetty>";
    }
    return ""+s+"["+s.getId()+" @ "+hh+"]";
}
 
Example 7
Source File: CustomListener.java    From XRTB with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionCreated(HttpSessionEvent ev) {
	HttpSession session = ev.getSession();
	String id = session.getId();

	sessions.add(session);
	//System.out.println("SESSION: " + id + " was created");
	
}
 
Example 8
Source File: CustomOAuth2AuthenticationDetails.java    From spring-microservice-boilerplate with MIT License 5 votes vote down vote up
/**
 * Records the access token value and remote address and will also set the session Id if a session
 * already exists (it won't create one).
 *
 * @param request that the authentication request was received from
 */
public CustomOAuth2AuthenticationDetails(HttpServletRequest request) {
  this.tokenValue = (String) request.getAttribute(ACCESS_TOKEN_VALUE);
  this.tokenType = (String) request.getAttribute(ACCESS_TOKEN_TYPE);
  this.remoteAddress = RemoteAddressUtils.getRealIp(request);

  HttpSession session = request.getSession(false);
  this.sessionId = (session != null) ? session.getId() : null;
  StringBuilder builder = new StringBuilder();
  if (remoteAddress != null) {
    builder.append("remoteAddress=").append(remoteAddress);
  }
  if (builder.length() > 1) {
    builder.append(", ");
  }
  if (sessionId != null) {
    builder.append("sessionId=<SESSION>");
    if (builder.length() > 1) {
      builder.append(", ");
    }
  }
  if (tokenType != null) {
    builder.append("tokenType=").append(this.tokenType);
  }
  if (tokenValue != null) {
    builder.append("tokenValue=<TOKEN>");
  }
  this.display = builder.toString();
}
 
Example 9
Source File: AbstractShiroClientFilter.java    From nano-framework with Apache License 2.0 5 votes vote down vote up
protected String localSessionId(final HttpServletRequest request) {
    final String sessionId = Cookies.get(request, sessionIdName);
    if(StringUtils.isNotBlank(sessionId)) {
        return sessionId;
    }
    
    final HttpSession session = request.getSession();
    if(session != null) {
        return session.getId();
    }
    
    throw new NullPointerException("Not found session id.");
}
 
Example 10
Source File: Jetty94RequestAuthenticator.java    From keycloak with Apache License 2.0 5 votes vote down vote up
@Override
protected String changeHttpSessionId(boolean create) {
    Request request = this.request;
    HttpSession session = request.getSession(false);
    if (session == null) {
        return request.getSession(true).getId();
    }
    if (!deployment.isTurnOffChangeSessionIdOnLogin()) return request.changeSessionId();
    else return session.getId();
}
 
Example 11
Source File: CustomListener.java    From XRTB with Apache License 2.0 5 votes vote down vote up
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
	HttpSession session = ev.getSession();
	String id = session.getId();

	sessions.remove(session);
	//System.out.println("SESSION: " + id + " was destroyed");
	
}
 
Example 12
Source File: InvocationContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the final response from the servlet. Note that this method should
 * only be invoked after all processing has been done to the servlet response.
 **/
public WebResponse getServletResponse() throws IOException {
    if (_contextStack.size() != 1) throw new IllegalStateException( "Have not returned from all request dispatchers" );
    if (_webResponse == null) {
        HttpSession session = getRequest().getSession( /* create */ false );
        if (session != null && session.isNew()) {
            Cookie cookie = new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, session.getId() );
            cookie.setPath( _application.getContextPath() );
            getResponse().addCookie( cookie );
        }
        _webResponse = new ServletUnitWebResponse( _client, _frame, _effectiveURL, getResponse(), _client.getExceptionsThrownOnErrorStatus() );
    }
    return _webResponse;
}
 
Example 13
Source File: ChangeSessionIdServlet.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
    HttpSession session = req.getSession(true);
    String old = session.getId();
    req.changeSessionId();
    String newId = session.getId();
    resp.getWriter().write(old + " "+ newId);
}
 
Example 14
Source File: UserActivityLogController.java    From openemm with GNU Affero General Public License v3.0 4 votes vote down vote up
@RequestMapping(value = "/list.action", method = {RequestMethod.GET, RequestMethod.POST})
public Pollable<ModelAndView> list(ComAdmin admin, UserActivityLogForm listForm, Model model, HttpSession session) {
    String sessionId = session.getId();
    DateTimeFormatter datePickerFormatter = admin.getDateFormatter();
    SimpleDateFormat localTableFormat = admin.getDateTimeFormat();

    FormUtils.syncNumberOfRows(webStorage, ComWebStorage.USERLOG_OVERVIEW, listForm);

    List<AdminEntry> admins = adminService.getAdminEntriesForUserActivityLog(admin);
    List<AdminEntry> adminsFilter = admin.permissionAllowed(Permission.MASTERLOG_SHOW) ? null : admins;

    model.addAttribute("userActions", Arrays.asList(UserActivityLogActions.values()));
    model.addAttribute("admins", admins);
    model.addAttribute("localeTableFormat", localTableFormat);
    AgnUtils.setAdminDateTimeFormatPatterns(admin, model);
    model.addAttribute("defaultDate", LocalDate.now().format(datePickerFormatter));

    LocalDate dateFrom = listForm.getDateFrom().get(LocalDate.now(), datePickerFormatter);
    LocalDate dateTo = listForm.getDateTo().get(LocalDate.now(), datePickerFormatter);

    Map<String, Object> argumentsMap = new HashMap<>();
    argumentsMap.put("sort", listForm.getSort());
    argumentsMap.put("order", listForm.getDir());
    argumentsMap.put("page", listForm.getPage());
    argumentsMap.put("numberOfRows", listForm.getNumberOfRows());
    argumentsMap.put("username", listForm.getUsername());
    argumentsMap.put("dateFrom.date", listForm.getDateFrom().getDate());
    argumentsMap.put("dateTo.date", listForm.getDateTo().getDate());
    argumentsMap.put("description", listForm.getDescription());

    PollingUid pollingUid = PollingUid.builder(sessionId, USER_ACTIVITY_LOG_KEY)
            .arguments(argumentsMap.values().toArray(ArrayUtils.EMPTY_OBJECT_ARRAY))
            .build();

    Callable<ModelAndView> worker = () -> {
        PaginatedListImpl<LoggedUserAction> loggedUserActions =
                userActivityLogService.getUserActivityLogByFilter(
                        admin,
                        listForm.getUsername(),
                        listForm.getUserAction(),
                        dateFrom,
                        dateTo,
                        listForm.getDescription(),
                        listForm.getPage(),
                        listForm.getNumberOfRows(),
                        listForm.getSort(),
                        listForm.getDir(),
                        adminsFilter);
        model.addAttribute(USER_ACTIVITY_LOG_KEY, loggedUserActions);

        return new ModelAndView("useractivitylog_list", model.asMap());
    };

    ModelAndView modelAndView = new ModelAndView("redirect:/administration/useractivitylog/list.action",
            argumentsMap);

    return new Pollable<>(pollingUid, Pollable.DEFAULT_TIMEOUT, modelAndView, worker);
}
 
Example 15
Source File: MockHttpServletRequest.java    From live-chat-engine with Apache License 2.0 4 votes vote down vote up
@Override
public String getRequestedSessionId() {
	HttpSession session = getSession();
	return (session != null ? session.getId() : null);
}
 
Example 16
Source File: HttpSessionDataResolver.java    From spring-soy-view with Apache License 2.0 4 votes vote down vote up
private void appendId(final SoyMapData root, final HttpSession session) {
    if (session.getId() != null) {
        root.put(prefix + "id", session.getId());
    }
}
 
Example 17
Source File: Jetty9SamlSessionStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
@Override
protected String changeSessionId(HttpSession session) {
    Request request = this.request;
    if (!deployment.turnOffChangeSessionIdOnLogin()) return request.changeSessionId();
    else return session.getId();
}
 
Example 18
Source File: JettySamlSessionStore.java    From keycloak with Apache License 2.0 4 votes vote down vote up
protected String changeSessionId(HttpSession session) {
    return session.getId();
}
 
Example 19
Source File: UtilHttp.java    From scipio-erp with Apache License 2.0 2 votes vote down vote up
/**
 * Obtains the session ID from the request, or "[none]" if no session present.
 * <p>
 * SCIPIO: 2018-12-11: This no longer forces session creation and now returns "[none]" instead of "unknown",
 * which was inaccurate. Note that this was primarily used for log display, and previously this was miscoded
 * such that it could never actually return "unknown"; therefore, if any code was checking the string "unknown",
 * it never did anything anyway.
 */
public static String getSessionId(HttpServletRequest request) {
    HttpSession session = request.getSession(false); // SCIPIO: use false!
    return (session == null ? "[none]" : session.getId());
}
 
Example 20
Source File: RequestHandler.java    From scipio-erp with Apache License 2.0 2 votes vote down vote up
/**
 * SCIPIO: Returns the session ID itself, for log display, without space and prefix; 
 * if no session, returns "[none]"; if hidden, returns "[hidden]".
 * <p>
 * NOTE: If request is available, prefer using {@link #getSessionIdForLog(HttpServletRequest)} instead.
 */
public static String getSessionIdForLog(HttpSession session) {
    return showSessionIdInLog ? (session != null ? session.getId() : "[none]") : "[hidden]";
}