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:net.gplatform.sudoor.server.captcha.model.CaptchaEngine.java

/**
 * //from w w  w  .ja v  a2 s. c  om
 * @param request
 * @return
 */
public boolean validate(HttpServletRequest request) {
    String captchaFromPage = request.getParameter("_captcha");
    HttpSession session = request.getSession();
    String captchaFromSession = (String) session.getAttribute(Constants.KAPTCHA_SESSION_KEY);

    logger.debug("CaptchaValidator: Session ID:{} captchaFromPage:{} captchaFromSession:{}", session.getId(),
            captchaFromPage, captchaFromSession);

    if (masterKey.checkWithMasterKey(captchaFromPage)) {
        return true;
    }

    if (StringUtils.equalsIgnoreCase(captchaFromSession, captchaFromPage)) {
        return true;
    }
    return false;
}

From source file:it.cnr.isti.hpc.dexter.annotate.controller.SuccessController.java

@RequestMapping(value = "/authSuccess")
public ModelAndView getRedirectURL(final HttpServletRequest request, HttpServletResponse response)
        throws Exception {
    SocialAuthManager manager = socialAuthTemplate.getSocialAuthManager();
    AuthProvider provider = manager.getCurrentAuthProvider();

    HttpSession session = request.getSession();

    System.out.println("session-id = " + session.getId());
    if (provider == null) {
        logger.error("cannot find provider");
        RedirectView view = new RedirectView("index.html");
        ModelAndView mv = new ModelAndView(view);
        return mv;

    }//ww w .j  a v  a  2  s .co  m
    Profile profile = provider.getUserProfile();
    System.out.println("profile: \n" + profile);
    User user = new User();
    String mail = profile.getEmail();
    if (mail == null) {
        mail = profile.getValidatedId() + "@" + profile.getProviderId() + ".app";
    }
    user.setEmail(mail);
    String first = profile.getFirstName();
    String last = profile.getLastName();
    String display = profile.getDisplayName();

    user.setFirstName((first == null) ? "" : first);

    user.setLastName((last == null || last.isEmpty()) ? mail : last);

    user.setDisplayName(display);
    if (display == null) {
        user.setDisplayName(mail);

    }
    String pwd = pswGenerator.nextSessionId();
    user.setPassword(pwd);

    User u = dao.getUserByMail(user.getEmail());
    System.out.println("------------success---------------");
    if (u != null)
        System.out.println(u.toString());
    System.out.println("----------------------------------");
    if (u != null) {
        logger.info("user ", user.getEmail() + " logged in");
        user = u;
    } else {
        logger.info("add user {}", user.getEmail());
        dao.addUser(user);
    }
    // String type = null;
    // if (session.getAttribute(Constants.REQUEST_TYPE) != null) {
    // type = (String) session.getAttribute(Constants.REQUEST_TYPE);
    // }
    // if (type != null) {
    // if (Constants.REGISTRATION.equals(type)) {
    // return registration(provider);
    // } else if (Constants.IMPORT_CONTACTS.equals(type)) {
    // return importContacts(provider);
    // } else if (Constants.SHARE.equals(type)) {
    // return new ModelAndView("shareForm", "connectedProvidersIds",
    // manager.getConnectedProvidersIds());
    // }
    // }

    RedirectView view = new RedirectView("index.html");
    ModelAndView mv = new ModelAndView(view);

    Cookie cookie = new Cookie("mail", user.getEmail());
    response.addCookie(cookie);
    cookie = new Cookie("psw", user.getPassword());
    response.addCookie(cookie);
    cookie = new Cookie("uid", String.valueOf(user.getId()));
    response.addCookie(cookie);

    // mv.addObject("uid", user.getId());
    // mv.addObject("pwd", user.getPassword());
    return mv;

}

From source file:eu.freme.broker.tools.loggingfilter.LoggingFilter.java

private void logRequest(final HttpServletRequest request) {
    StringBuilder msg = new StringBuilder();
    msg.append(REQUEST_PREFIX);/*w w  w  . jav a 2  s  .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";
            if (request.getContentLength() == 0 || checkAgainstWhitelist(request)) {
                String body = new String(requestWrapper.toByteArray(), charEncoding);
                if (request.getContentLength() >= maxSize) {
                    try {
                        body = body.substring(0, maxSize).concat("... (truncated by LoggingFilter)");
                    } catch (StringIndexOutOfBoundsException e) {
                        logger.warn(
                                "A Request was made whose Content-Length Header is longer than its actual content");
                    }
                }
                msg.append("; payload=").append(body);
            } else {
                msg.append("; payload ommitted from logging as it is not in the whitelisted mime-types");
            }

        } catch (UnsupportedEncodingException e) {
            logger.warn("Failed to parse request payload", e);
        }

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

From source file:org.apache.struts.webapp.example.LogonAction.java

/**
 * <p>Store User object in client session.
 * If user object is null, any existing user object is removed.</p>
 *
 * @param request The request we are processing
 * @param user The user object returned from the database
 *//*from w ww  .ja va2  s . c  o m*/
void SaveUser(HttpServletRequest request, User user) {

    HttpSession session = request.getSession();
    session.setAttribute(Constants.USER_KEY, user);
    if (log.isDebugEnabled()) {
        log.debug("LogonAction: User '" + user.getUsername() + "' logged on in session " + session.getId());
    }

}

From source file:org.frat.common.security.BaseSecurityContext.java

/**
 * .//from   w w w  .j  a  v  a  2s. c o m
 * 
 * @param username
 */
public static void kickOutUnLogin() {
    try {
        WebApplicationContext webApplicationContext = ContextLoader.getCurrentWebApplicationContext();
        ServletContext servletContext = webApplicationContext.getServletContext();

        // applicationHashSet?session
        @SuppressWarnings("unchecked")
        HashSet<HttpSession> sessions = (HashSet<HttpSession>) servletContext.getAttribute("loginSessions");
        List<HttpSession> sessionList = new ArrayList<HttpSession>();
        if (StringUtil.isObjNotNull(sessions)) {
            for (HttpSession session : sessions) {
                SysUserDto user = (SysUserDto) session.getAttribute("shiro.user");
                if (null != session && StringUtil.isObjNull(user)) {
                    // LOGGER.debug("getLastAccessedTime="+ new
                    // Date(session.getLastAccessedTime()));
                    // LOGGER.debug("now="+ new Date());
                    int diffTime = DateUtil.diffTime(new Date(), new Date(session.getLastAccessedTime()));
                    // LOGGER.debug("diffTime="+diffTime);
                    if (diffTime > 300) {
                        sessionList.add(session);
                    }
                }
            }
            for (HttpSession session : sessionList) {
                session.invalidate();
                LOGGER.debug("success kick out UnLogin session [" + session.getId() + "]");
            }
        }
    } catch (Exception e) {
        LOGGER.error("");
        LOGGER.error(StackTraceUtil.getStackTrace(e));
    }

}

From source file:MyServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    HttpSession session = request.getSession();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Simple Session Tracker</title>");
    out.println("</head>");
    out.println("<body>");

    out.println("<h2>Session Info</h2>");
    out.println("session Id: " + session.getId() + "<br><br>");
    out.println("The SESSION TIMEOUT period is " + session.getMaxInactiveInterval() + " seconds.<br><br>");
    out.println("Now changing it to 20 minutes.<br><br>");
    session.setMaxInactiveInterval(20 * 60);
    out.println("The SESSION TIMEOUT period is now " + session.getMaxInactiveInterval() + " seconds.");

    out.println("</body>");
    out.println("</html>");

}

From source file:org.owasp.webgoat.service.BaseService.java

/**
 * <p>getWebSession.</p>/*from w w w.  j av  a2  s  . co  m*/
 *
 * @param session a {@link javax.servlet.http.HttpSession} object.
 * @return a {@link org.owasp.webgoat.session.WebSession} object.
 */
public WebSession getWebSession(HttpSession session) {
    WebSession ws;
    Object o = session.getAttribute(WebSession.SESSION);
    if (o == null) {
        throw new IllegalArgumentException(
                "No valid WebSession object found, has session timed out? [" + session.getId() + "]");
    }
    if (!(o instanceof WebSession)) {
        throw new IllegalArgumentException("Invalid WebSession object found, this is probably a bug! ["
                + o.getClass() + " | " + session.getId() + "]");
    }
    ws = (WebSession) o;
    return ws;
}

From source file:pivotal.au.se.gemfirexdweb.controller.LogoutController.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model, HttpSession session, HttpServletResponse response, HttpServletRequest request)
        throws Exception {
    logger.debug("Received request to logout of GemFireXD*Web");

    // remove connection from list
    ConnectionManager cm = ConnectionManager.getInstance();
    cm.removeConnection(session.getId());

    session.invalidate();/*from   ww w  .j a  va2  s.c om*/

    Login login = new Login();
    login.setUrl("jdbc:gemfirexd://localhost:1527/");

    model.addAttribute("loginAttribute", login);
    // This will resolve to /WEB-INF/jsp/loginpage.jsp
    return "loginpage";

    //response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
    //return null;
}

From source file:net.duckling.ddl.service.authenticate.impl.AuthenticationServiceImpl.java

public void invalidateSession(HttpServletRequest request) {
    if (request == null) {
        LOGGER.error("No HTTP reqest provided; cannot log out.");
        return;/*  w  w w .  ja  va  2s. c  o  m*/
    }

    HttpSession session = request.getSession();
    String sid = (session == null) ? "(null)" : session.getId();
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Invalidating WikiSession for session ID=" + sid);
    }
    VWBSession vwbsession = VWBSession.findSession(request);
    vwbsession.invalidate();
    session.invalidate();
}

From source file:gr.upatras.ece.nam.baker.impl.BakerClientAPIImpl.java

@GET
@Path("/ibuns/example")
@Produces("application/json")
public Response getJsonInstalledBunExample(@Context HttpHeaders headers, @Context HttpServletRequest request) {

    String userAgent = headers.getRequestHeader("user-agent").get(0);
    logger.info("Received GET for Example. user-agent= " + userAgent);

    if (headers.getRequestHeaders().get("X-Baker-API-Version") != null) {
        String XBakerAPIVersion = headers.getRequestHeader("X-Baker-API-Version").get(0);
        logger.info("Received GET for Example. X-Baker-API-Version= " + XBakerAPIVersion);
    }/*from  ww  w. j  a  v  a2  s. c  o  m*/

    Map<String, Cookie> cookies = headers.getCookies();
    logger.info("cookies for Example = " + cookies.toString());
    HttpSession session = request.getSession(true);
    logger.info("session = " + session.getId());

    URI endpointUrl = uri.getBaseUri();

    InstalledBun installedBun = new InstalledBun(("12cab8b8-668b-4c75-99a9-39b24ed3d8be"),
            endpointUrl + "repo/ibuns/12cab8b8-668b-4c75-99a9-39b24ed3d8be");
    installedBun.setName("ServiceName");

    ResponseBuilder response = Response.ok(installedBun);

    CacheControl cacheControl = new CacheControl();
    cacheControl.setNoCache(true);
    response.cacheControl(cacheControl);

    return response.build();
}