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.safasoft.treeweb.auth.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication auth) throws IOException, ServletException {
    //login info//from  ww  w  .j a  va  2s  . co m
    HttpSession session = request.getSession();
    String cnname = (String) session.getAttribute("cnname");
    if (cnname == null || cnname.equals("")) {
        try {
            String principal = auth.getPrincipal().toString();
            int start = principal.indexOf("cn=");
            String tmp = principal.substring(start + 3);
            int end = tmp.indexOf(",");
            cnname = tmp.substring(0, end);
            session.setAttribute("cnname", cnname);
            session.setAttribute("uid", auth.getName());
            session.setAttribute("sessionid", session.getId());
        } catch (Exception ex) {
            authLogger.error(ex);
        }
    }
    //logging login
    FfLogFocus logFocus = new FfLogFocus();
    logFocus.setUserName(auth.getName());
    DataConverter dc = new DataConverter();
    dc.setConverter(new Date(), "dd-MMM-yyyy kk:mm:ss");
    logFocus.setLoginTime(dc.getConverter());
    FfLogFocus logFocusSave = new SessionUtil<FfLogFocusService>().getAppContext("ffLogFocusService")
            .save(logFocus);
    session.setAttribute("logParentId", logFocusSave.getId());
    //redirect
    setDefaultTargetUrl("/apps/main/home");
    super.onAuthenticationSuccess(request, response, auth);
}

From source file:de.itsvs.cwtrpc.controller.RemoteServiceControllerServlet.java

protected void invalidateSession(HttpServletRequest request) throws ServletException {
    final HttpSession session;

    session = request.getSession(false);
    if (session != null) {
        if (log.isDebugEnabled()) {
            log.debug("Invalidating session " + session.getId());
        }/*from   w  w w .j a v a2  s . c om*/
        session.invalidate();
    }
}

From source file:SessionTracker.java

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

    HttpSession session = req.getSession(true);

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

    if (count == null) {
        count = new Integer(1);
    } else {/*from  w  w  w .  ja  v a2 s.  c o  m*/
        count = new Integer(count.intValue() + 1);
    }

    session.setAttribute("count", count);
    out.println("<html><head><title>SessionSnoop</title></head>");
    out.println("<body><h1>Session Details</h1>");
    out.println(
            "You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.") + "<br/>");
    out.println("<h3>Details of this session:</h3>");
    out.println("Session id: " + session.getId() + "<br/>");
    out.println("New session: " + session.isNew() + "<br/>");
    out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>");
    out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>");
    out.println("</body></html>");
}

From source file:fr.smile.liferay.EsigatePortlet.java

/**
 * Transform request to IncominqRequest/* ww w . j  a  v  a 2 s .  c om*/
 *
 * @param request
 * @param method
 * @return an incoming request
 * @throws IOException
 */
public IncomingRequest create(PortletRequest request, String method) throws IOException {

    HttpServletRequest httpServletRequest = PortalUtil
            .getOriginalServletRequest(PortalUtil.getHttpServletRequest(request));

    StringBuilder uri = new StringBuilder(HTTP_BASE_INCOMING_URL);

    StringBuilder query = new StringBuilder();
    Enumeration<String> parameters = request.getParameterNames();
    String sep = "";
    while (parameters.hasMoreElements()) {
        String name = parameters.nextElement();
        String[] values = request.getParameterValues(name);
        if (!name.equals(ACTION_PARAMETER)) {
            for (String value : values) {
                query.append(sep);
                query.append(name).append("=").append(URLEncoder.encode(value, "UTF-8"));
                sep = "&";
            }
        }
    }

    ProtocolVersion protocolVersion = HttpVersion.HTTP_1_1.forVersion(1, 0);

    if (method.equals("GET")) {
        if (!query.toString().isEmpty()) {
            if (!uri.toString().contains("?")) {
                uri.append("?");
            } else {
                uri.append("&");
            }
            uri.append(query);
        }
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Creating Incoming request with method " + method + ", URI " + uri + ", protocoleVersion "
                + protocolVersion);
    }
    IncomingRequest.Builder builder = IncomingRequest
            .builder(new BasicRequestLine(method, uri.toString(), protocolVersion));

    if (method.equals("POST")) {
        // create entity
        InputStream inputStream = IOUtils.toInputStream(query.toString());

        if (inputStream != null) {
            // Copy entity-related headers
            InputStreamEntity entity = new InputStreamEntity(inputStream, query.length());
            String contentTypeHeader = httpServletRequest.getContentType();
            if (contentTypeHeader != null) {
                entity.setContentType(contentTypeHeader);
            }
            String contentEncodingHeader = httpServletRequest.getCharacterEncoding();
            if (contentEncodingHeader != null) {
                entity.setContentEncoding(contentEncodingHeader);
            }
            builder.setEntity(entity);
        }
    }

    HttpServletRequestContext context = new HttpServletRequestContext(httpServletRequest, null, null);
    builder.setContext(context);
    builder.setRemoteAddr(httpServletRequest.getRemoteAddr());
    builder.setRemoteUser(request.getRemoteUser());
    HttpSession session = httpServletRequest.getSession(false);
    if (session != null) {
        builder.setSessionId(session.getId());
    }
    builder.setUserPrincipal(request.getUserPrincipal());
    // Copy cookies
    javax.servlet.http.Cookie[] src = request.getCookies();

    if (src != null) {
        LOG.debug("Copying " + src.length + " cookie(s) to response.");
        for (int i = 0; i < src.length; i++) {
            javax.servlet.http.Cookie c = src[i];
            BasicClientCookie dest = new BasicClientCookie(c.getName(), c.getValue());
            dest.setSecure(c.getSecure());
            dest.setDomain(c.getDomain());
            dest.setPath(c.getPath());
            dest.setComment(c.getComment());
            dest.setVersion(c.getVersion());
            builder.addCookie(dest);
        }
    }

    builder.setSession(new HttpServletSession(httpServletRequest));

    IncomingRequest incomingRequest = builder.build();
    return incomingRequest;

}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/weather", produces = "application/json")
public GetWeather serviceWeather(HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/weather");
        }//from  w w  w. j a va 2s  .c  om

        return null;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("user get weather. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : /service/weather");
    }

    return serviceWeather.getWeather();
}

From source file:com.hiperium.web.restful.authentication.AuthenticationREST.java

/**
 * Used by JavaScript in the presentation layer to authenticate the user.
 *
 * @param credentialsDTO/*  www. j  a va2 s  . c o  m*/
 * @return
 * @throws InformationException
 * @throws PropertyValidationException
 */
@POST
@Produces(MediaType.TEXT_PLAIN)
public Response login(@NotNull UserCredentialDTO credentialsDTO)
        throws InformationException, PropertyValidationException {
    LOGGER.debug("login - BEGIN");

    // Validates that the username property was not set for security reasons
    if (StringUtils.isNotBlank(credentialsDTO.getUsername())) {
        throw InformationException.generate(EnumI18N.SECURITY, EnumInformationException.USER_NOT_FOUND,
                Locale.getDefault());
    }

    // Validate object parameter
    Set<ConstraintViolation<UserCredentialDTO>> violations = this.validator.validate(credentialsDTO);
    if (!violations.isEmpty()) {
        throw new PropertyValidationException(new HashSet<ConstraintViolation<?>>(violations));
    }

    // Validates the credentials
    String urlNavigation = EnumNavigation.ERROR.getURL();
    if (this.securityBusinessDelegate.getAuthenticationBO().validateUserCredentials(credentialsDTO.getEmail(),
            credentialsDTO.getPassword())) {

        // Invalidate the actual session and creates a new one
        HttpSession sessionOld = this.servletRequest.getSession(false);
        sessionOld.invalidate();
        HttpSession sessionNew = this.servletRequest.getSession(true);

        // Creates a session register with a new HTTP session
        String userAgent = this.servletRequest.getHeader("User-Agent");
        String remoteIpAddress = this.servletRequest.getRemoteAddr();
        SessionRegisterDTO sessionRegisterDTO = this.securityBusinessDelegate.getAuthenticationBO()
                .userAuthentication(credentialsDTO.getEmail(), userAgent, remoteIpAddress, false,
                        sessionNew.getId());

        // Sets the application language based in the user language
        LanguageBean languageBean = (LanguageBean) sessionNew.getAttribute(LanguageBean.BEAN_NAME);
        UserSessionBean userSessionBean = (UserSessionBean) sessionNew.getAttribute(UserSessionBean.BEAN_NAME);
        languageBean.setLocale(new Locale(sessionRegisterDTO.getLocale().getLanguage()));

        // Verify if user needs to change the password
        if (this.securityBusinessDelegate.getAuthenticationBO().userNeedToChangePasswd(sessionNew.getId())) {
            urlNavigation = EnumNavigation.UPDATE_PASSWORD.getURL();
            userSessionBean.getSessionInformationDTO()
                    .setBreadCrumb(new BreadCrumbDTO(0,
                            Resources.getResourceBundle(EnumI18N.SECURITY, languageBean.getLocale())
                                    .getString("passwordChange"),
                            urlNavigation));
        } else {
            urlNavigation = EnumNavigation.HOME_SELECTION.getURL();
            userSessionBean.getSessionInformationDTO()
                    .setBreadCrumb(new BreadCrumbDTO(0,
                            Resources.getResourceBundle(EnumI18N.SECURITY, languageBean.getLocale())
                                    .getString("homeSelection"),
                            urlNavigation));
        }
        // Sets the absolute session timeout.
        sessionNew.setAttribute(NavigationControl.SESSION_TIME_LABEL, System.currentTimeMillis());
    } else {
        throw InformationException.generate(EnumI18N.SECURITY, EnumInformationException.USER_NOT_FOUND,
                Locale.getDefault());
    }
    LOGGER.debug("login - END");
    return Response.status(Status.OK).entity(urlNavigation).type(MediaType.TEXT_PLAIN).build();
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/dispatcher/typeMachine", produces = "application/json")
public FlyingMachineType serviceDispatcherTypeMachine(@RequestParam(name = "typeMachine") String typeMachine,
        HttpServletRequest request, HttpServletResponse response) {
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/dispatcher/typeMachine");
        }/*ww  w . j  a  va 2 s  .com*/

        return null;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("user get dispatcher type machine. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : /service/dispatcher/typeMachine");
    }

    return serviceFlyingType.getFlyingMachineType(typeMachine);
}

From source file:airport.web.controller.ServicesController.java

@RequestMapping(value = "/service/dispatcher")
public Dispatcher serviceDispatcher(@RequestParam(name = "login") String login, HttpServletRequest request,
        HttpServletResponse response) {//from  w w  w.  j  ava2 s  .  c  o m
    HttpSession httpSession = request.getSession();
    User user = (User) httpSession.getAttribute("user");

    if (!serviceUsers.checkUserOnline(user)) {
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);

        if (LOG.isInfoEnabled()) {
            LOG.info("the user isn't authorized. Session id : " + httpSession.getId()
                    + ". URL : /service/dispatcher/typeMachine");
        }

        return null;
    }

    if (LOG.isInfoEnabled()) {
        LOG.info("user get dispacther. Session id : " + httpSession.getId() + ". User : " + user
                + ". URL : /service/dispatcher/typeMachine");
    }

    return serviceDispatcherName.getDispatcher(user);
}

From source file:org.apache.felix.http.itest.SessionHandlingTest.java

private void setupServlet(final String name, String[] path, int rank, final String context) throws Exception {
    Dictionary<String, Object> servletProps = new Hashtable<String, Object>();
    servletProps.put(HTTP_WHITEBOARD_SERVLET_NAME, name);
    servletProps.put(HTTP_WHITEBOARD_SERVLET_PATTERN, path);
    servletProps.put(SERVICE_RANKING, rank);
    if (context != null) {
        servletProps.put(HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=" + context + ")");
    }//from   ww  w  .j  ava 2  s .  c o  m

    Servlet sessionServlet = new TestServlet(initLatch, destroyLatch) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            final boolean create = req.getParameter("create") != null;
            if (create) {
                req.getSession();
            }
            final boolean destroy = req.getParameter("destroy") != null;
            if (destroy) {
                req.getSession().invalidate();
            }
            final HttpSession s = req.getSession(false);
            if (s != null) {
                s.setAttribute("value", context);
            }

            final PrintWriter pw = resp.getWriter();
            pw.println("{");
            if (s == null) {
                pw.println(" \"session\" : false");
            } else {
                pw.println(" \"session\" : true,");
                pw.println(" \"sessionId\" : \"" + s.getId() + "\",");
                pw.println(" \"value\" : \"" + s.getAttribute("value") + "\"");
            }
            pw.println("}");
        }
    };

    registrations.add(m_context.registerService(Servlet.class.getName(), sessionServlet, servletProps));
}