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.acc.storefront.filters.StorefrontFilter.java

protected void fixSecureHttpJSessionIdCookie(final HttpServletRequest httpServletRequest,
        final HttpServletResponse httpServletResponse) {
    final HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        getCookieGenerator().addCookie(httpServletResponse, session.getId());
    }//from  w ww . j a  v a  2 s.  c  om

}

From source file:nl.ordina.jtech.http2.java8.server.tomcat.SimpleImagePush.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    System.out.println("request path: " + req.getContextPath() + " >> " + req.getServletPath() + " >> "
            + req.getPathTranslated());//from   w ww. j a  v a 2  s .  c  om

    if (req.getPathTranslated() != null && req.getPathTranslated().contains("dynamic-image")) {
        handleDynamicImage(req, resp);
    }

    final HttpSession session = req.getSession(true);
    System.out.println(" (possibly new) sessionid: " + session.getId() + ", requested sessionid: "
            + req.getRequestedSessionId() + ", from cookie: " + req.isRequestedSessionIdFromCookie()
            + ", valid: " + req.isRequestedSessionIdValid());

    /*
     * Result:
     * GET https://localhost:8443/http2-java8-example-1.0/return.gif?answer=42
     *  header: x-my-header=[bar]
     *  header: x-my-header-1=[foo]
     *  header: x-my-header-1=[zaphod]
     */
    // Tomcat impl: http://svn.apache.org/viewvc/tomcat/tc9.0.x/branches/gsoc-jaspic/java/org/apache/catalina/core/ApplicationPushBuilder.java?view=markup
    PushBuilder pb = req.getPushBuilder().path("return.gif") // path is the only required value

            // note: the browser does not show these headers - only the ones delivered in the pushed resource itself
            .setHeader("x-my-header", "overwritten by subsequent setHeader").setHeader("x-my-header", "bar")
            .addHeader("x-my-header-1", "foo").addHeader("x-my-header-1", "zaphod") // note: had expected this to be reported as x-my-header-1=[foo,zaphod] ?

            // GET is default
            // ?! "IllegalArgumentException - if the method set expects a request body (eg POST)"; does not happen; Tomcat does not enforce it!
            .method("POST")

            .queryString("answer=42")

            //.sessionId("some-session-id") // dropped?! "pushed request will include the session ID either as a Cookie or as a URI parameter"
            .sessionId(session.getId())

    ;
    final boolean pushResult;
    try {
        //pb.push(); // results in 'java.lang.NoSuchMethodError: javax.servlet.http.PushBuilder.push()V'
        // - Tomcat's Servlet 4.0 API version return type is boolean, not void!
        final Method push = pb.getClass().getMethod("push");
        pushResult = (boolean) push.invoke(pb);
    } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
        if (e.getCause() instanceof UnsupportedOperationException) {
            respondWith(resp,
                    "<p>The following image was NOT provided via a push request! "
                            + "Cannot push over plain HTTP/1.x.</p>" + "<img src=\"" + req.getContextPath()
                            + "/return.gif\"/>");
            return;
        }
        respondWith(resp, e.getClass().getName() + ": " + e.getMessage() + ", cause: " + e.getCause());
        return;
    }

    simplePush(req, "Chrome Pony.png");
    simplePush(req, "second.html");

    respondWith(resp,
            "<p>The following static image was provided via a push request with result " + pushResult + "</p>"
                    + "<img src=\"" + req.getContextPath() + "/return.gif\"/><br/>"
                    + "<p>Dynamic push request: </p><img src=\"push/dynamic-image\"/><br/>"
                    + "<p><a href=\"second.html\">Link naar gepushte pagina</a></p>");
}

From source file:edu.uiowa.icts.authentication.AuthHandle.java

/** {@inheritDoc} */
@Override//  w ww .  j ava2 s  .  c  om
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse res, Authentication auth)
        throws IOException, ServletException {

    log.debug("successfully authenticated " + String.valueOf(auth.getPrincipal()));

    if (req.getSession().getAttribute("SPRING_SECURITY_LAST_EXCEPTION") != null) {
        req.getSession().removeAttribute("SPRING_SECURITY_LAST_EXCEPTION");
    }

    for (GrantedAuthority ga : auth.getAuthorities()) {
        log.debug(ga.getAuthority());
    }

    HttpSession session = req.getSession();
    String username = req.getParameter("j_username");
    session.setAttribute("username", username);

    AuditLogger.info(session.getId(), username, "logged in from", req.getRemoteHost());

    target.onAuthenticationSuccess(req, res, auth);

}

From source file:org.iqvis.nvolv3.request.filter.LoggingFilter.java

@SuppressWarnings("unused")
private void logRequest(final HttpServletRequest request) {
    StringBuilder msg = new StringBuilder();
    msg.append(REQUEST_PREFIX);//from   w ww .j a va  2s.  c  o m
    if (request instanceof RequestWrapper) {
        msg.append("request id=").append(((RequestWrapper) request).getId()).append("; ");
    }
    HttpSession session = request.getSession(false);
    if (session != null) {
        msg.append("session id=").append(session.getId()).append("; ");
    }
    if (request.getContentType() != null) {
        msg.append("content type=").append(request.getContentType()).append("; ");
    }
    msg.append("uri=").append(request.getRequestURI());
    if (request.getQueryString() != null) {
        msg.append('?').append(request.getQueryString());
    }

    if (request instanceof RequestWrapper && !isMultipart(request)) {
        RequestWrapper requestWrapper = (RequestWrapper) request;
        try {
            String charEncoding = requestWrapper.getCharacterEncoding() != null
                    ? requestWrapper.getCharacterEncoding()
                    : "UTF-8";
            msg.append("; payload=").append(new String(requestWrapper.toByteArray(), charEncoding));
        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse request payload", e);
        }

    }
    logger.debug(msg.toString());
}

From source file:org.workspace7.moviestore.controller.HomeController.java

@PostMapping("/logout")
public ModelAndView clear(ModelAndView modelAndView, HttpServletRequest request) {
    final String hostname = System.getenv().getOrDefault("HOSTNAME", "unknown");
    List<Movie> movies = movieDBHelper.getAll();

    List<MovieCartItem> movieList = movies.stream()
            .map((Movie movie) -> MovieCartItem.builder().movie(movie).quantity(0).total(0).build())
            .collect(Collectors.toList());

    HttpSession session = request.getSession(false);

    if (session != null) {
        log.info("Invalidating session:{}", session.getId());
        session.invalidate();/*from w ww  . j a  va2  s.  co  m*/
    }

    log.info("New Session");
    modelAndView.addObject("movies", movieList);
    modelAndView.setViewName("home");
    modelAndView.addObject("hostname", hostname);
    return modelAndView;
}

From source file:net.ymate.framework.core.support.TokenProcessHelper.java

/**
 * Generate a new transaction token, to be used for enforcing a single
 * request for a particular transaction.
 *
 * @param request The request we are processing
 * @return a new transaction token/*from   w w  w .  ja va2 s  . c om*/
 */
public synchronized String generateToken(HttpServletRequest request) {
    HttpSession session = request.getSession();
    return generateToken(session.getId());
}

From source file:org.acegisecurity.captcha.CaptchaValidationProcessingFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String captchaResponse = request.getParameter(captchaValidationParameter);

    if ((request != null) && request instanceof HttpServletRequest && (captchaResponse != null)) {
        logger.debug("captcha validation parameter found");

        // validate the request against CaptchaServiceProxy
        boolean valid = false;

        logger.debug("try to validate");

        //get session
        HttpSession session = ((HttpServletRequest) request).getSession();

        if (session != null) {
            String id = session.getId();
            valid = this.captchaService.validateReponseForId(id, captchaResponse);
            logger.debug("captchaServiceProxy says : request is valid = " + valid);

            if (valid) {
                logger.debug("update the context");
                ((CaptchaSecurityContext) SecurityContextHolder.getContext()).setHuman();

                //logger.debug("retrieve original request from ")
            } else {
                logger.debug("captcha test failed");
            }/*from  w  ww  . j av  a2 s.  c  o  m*/
        } else {
            logger.debug("no session found, user don't even ask a captcha challenge");
        }
    } else {
        logger.debug("captcha validation parameter not found, do nothing");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("chain ...");
    }

    chain.doFilter(request, response);
}

From source file:com.edgenius.wiki.security.acegi.CaptchaValidationProcessingFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {
    String captchaResponse = request.getParameter(captchaValidationParameter);
    //        if(true)
    //           throw new IOException("EOF");
    if ((request != null) && request instanceof HttpServletRequest && (captchaResponse != null)) {
        logger.debug("captcha validation parameter found");

        //get session
        HttpSession session = ((HttpServletRequest) request).getSession();

        if (session != null) {
            String id = session.getId();
            boolean valid = this.captchaService.validateReponseForId(id, captchaResponse);
            processVerify(request, response, chain, valid);
        } else {/*from www.  ja  v  a 2s. c om*/
            logger.debug("no session found, user don't even ask a captcha challenge");
        }
    } else {
        chain.doFilter(request, response);
    }

}

From source file:eu.forgestore.ws.util.ShiroBasicAuthInterceptor.java

public void handleMessage(Message message) throws Fault {

    Subject currentUser = SecurityUtils.getSubject();
    if (currentUser != null) {
        logger.info("handleMessage currentUser = " + currentUser.toString());
        logger.info("currentUser.getPrincipal() = " + currentUser.getPrincipal());
        logger.info("SecurityUtils.getSubject().getSession() = " + currentUser.getSession().getId());
        logger.info("currentUser.getSession().getAttribute(  aKey ) = "
                + currentUser.getSession().getAttribute("aKey"));
        logger.info("message.getId() = " + message.getId());

        // Here We are getting session from Message
        HttpServletRequest request = (HttpServletRequest) message.get(AbstractHTTPDestination.HTTP_REQUEST);
        HttpSession session = request.getSession();

        logger.info("HttpSession session.getId() = " + session.getId());

        if (currentUser.getPrincipal() != null) {
            logger.info("User [" + currentUser.getPrincipal()
                    + "] IS ALREADY logged in successfully. =========================");

            if (currentUser.isAuthenticated()) {
                logger.info("User [" + currentUser.getPrincipal()
                        + "] IS isAuthenticated and logged in successfully. =========================");
                return;
            }//  ww  w  .  j av a  2 s  .  co m

            if (currentUser.isRemembered()) {
                logger.info("User [" + currentUser.getPrincipal()
                        + "] IS REMEMBERED and logged in successfully. =========================");
                return;
            }
        }
    }

    AuthorizationPolicy policy = message.get(AuthorizationPolicy.class);
    if (policy == null || policy.getUserName() == null || policy.getPassword() == null) {
        String name = null;
        if (policy != null) {
            name = policy.getUserName();
        }
        String error = "No user credentials are available";
        logger.warn(error + " " + "for name: " + name);
        throw new SecurityException(error);
    }

    try {

        UsernameToken token = convertPolicyToToken(policy);

        String s = validator.validate(token);
        //
        // Create a Principal/SecurityContext
        //bale principal apo to validator
        //         Principal p = null;
        //         if (s!=null) {
        //            p = new SimplePrincipal( s );
        //         }
        //
        //         message.put(SecurityContext.class, createSecurityContext(p));
        currentUser.getSession().setAttribute("aKey", UUID.randomUUID().toString());

    } catch (Exception ex) {
        throw new Fault(ex);
    }
}

From source file:com.huateng.ebank.framework.web.struts.BaseAction.java

public String getValueFromDataBus(HttpServletRequest request, String databusId, String fieldId)
        throws AppException {
    try {//w  ww  .j a  va 2s.c o m
        HttpSession session = null;
        session = request.getSession();
        DataBus dataBus = CommonQueryDataBusMng.getDataBus(session.getId(), databusId, session);
        return dataBus.getFieldValue(fieldId);
    } catch (AppException appEx) {
        throw new AppException(appEx.getModuleName(), appEx.getErrCd(),
                ErrorCodeUtil.convertErrorMessage(log, appEx), appEx);
    } catch (Exception ex) {
        throw new AppException(Module.SYSTEM_MODULE, Rescode.DEFAULT_RESCODE, ex);
    }
}