Example usage for javax.servlet.http HttpServletRequest getRequestedSessionId

List of usage examples for javax.servlet.http HttpServletRequest getRequestedSessionId

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getRequestedSessionId.

Prototype

public String getRequestedSessionId();

Source Link

Document

Returns the session ID specified by the client.

Usage

From source file:com.fanya.p2p.front.user.jcaptcha.JCaptchaFilter.java

@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
        FilterChain filterChain) throws ServletException, IOException {

    response.setDateHeader("Expires", 0L);
    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
    response.addHeader("Cache-Control", "post-check=0, pre-check=0");
    response.setHeader("Pragma", "no-cache");
    response.setContentType("image/jpeg");

    String id = request.getRequestedSessionId();
    BufferedImage bi = JCaptcha.captchaService.getImageChallengeForID(id);

    ServletOutputStream out = response.getOutputStream();

    ImageIO.write(bi, "jpg", out);
    try {//w  w  w  .  j a v a2 s . c o  m
        out.flush();
    } finally {
        out.close();
    }
}

From source file:eu.smartenit.unada.web.ui.UnadaSessionBean.java

/**
 * The init() method that initializes the ConfigurationBean.
 * It checks for valid sessions, retrieves user's token and checks 
 * whether he is the machine owner and also retrieves stored 
 * uNaDa configuration parameters.//from w w w. j  av a  2s  . com
 * 
 */
@PostConstruct
public void init() {
    HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext()
            .getRequest();

    boolean validSession = req.getRequestedSessionId() != null && !req.isRequestedSessionIdValid();

    boolean noFacebook = false;
    try {
        noFacebook = (Boolean) FacesContext.getCurrentInstance().getExternalContext().getApplicationMap()
                .get("noFacebook");
        if (noFacebook) {
            name = "admin";
            return;
        }
    } catch (Exception e) {
        // do nothing
    }

    // check if session has expired
    if (!validSession) {
        String error = req.getParameter("error_reason");
        if (error != null) {
            redirectToLoginPage();
        }

        String code = req.getParameter("code");
        if (code != null) {
            String token = null;
            try {
                token = retrieveToken(code);
            } catch (Exception e) {
                logger.error("Error while retrieving token: " + e.getMessage());
                redirectToLoginPage();
            }
            if (token != null) {
                Owner owner = DAOFactory.getOwnerDAO().findLast();
                Owner currentUser = getOwner(token);

                if (owner == null) {
                    logger.info("Currently there is no owner for this uNaDa.");
                    try {
                        //insert owner of this unada
                        getExtendedToken(currentUser);
                        DAOFactory.getOwnerDAO().insert(currentUser);

                        //add owner as trusted user and update MAC address
                        TrustedUser trustedUser = new TrustedUser();
                        trustedUser.setFacebookID(currentUser.getFacebookID());
                        String ipAddress = req.getRemoteAddr();
                        trustedUser.setMacAddress(ARP.getArpInstance().execute(ipAddress));
                        DAOFactory.getTrustedUserDAO().insert(trustedUser);

                    } catch (Exception e) {
                        logger.error("Error while inserting new owner and trusted user: " + e.getMessage());
                    }
                } else {
                    logger.info("Current owner id = " + owner.getFacebookID());
                    if (owner.getFacebookID().equals(currentUser.getFacebookID())) {
                        logger.info(
                                "Existing owner successfully logins to the uNaDa. " + "Updating his token.");
                        getExtendedToken(currentUser);
                        DAOFactory.getOwnerDAO().update(currentUser);
                        logger.debug("Updated token = " + currentUser.getOauthToken());

                        //update trusted user and his MAC address
                        /*
                        TrustedUser trustedUser = new TrustedUser();
                        trustedUser.setFacebookID(currentUser.getFacebookID());
                        String ipAddress = req.getRemoteAddr();
                        trustedUser.setMacAddress(ARP.getArpInstance().execute(ipAddress));
                        try {
                        DAOFactory.getTrustedUserDAO().insert(trustedUser);
                        } catch (Exception e) {
                        logger.error("Error while updating trusted user: "
                                + e.getMessage());
                        }
                        */

                    } else {
                        redirectToLoginPage();
                    }
                }
            } else {
                redirectToLoginPage();
            }
        } else {
            redirectToLoginPage();
        }
    }
}

From source file:cn.guoyukun.spring.web.filter.DebugRequestAndResponseFilter.java

private void debugRequest(HttpServletRequest request) {
    log.debug("=====================request begin==========================");
    String uri = request.getRequestURI();
    String queryString = request.getQueryString();
    if (StringUtils.isNotBlank(queryString)) {
        uri = uri + "?" + queryString;
    }/* ww w.j  a  v a  2  s.  c o  m*/
    log.debug("{}:{}", request.getMethod(), uri);
    log.debug("remote ip:{}  sessionId:{}  ", IpUtils.getIpAddr(request), request.getRequestedSessionId());
    log.debug("===header begin============================================");
    Enumeration<String> headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = headerNames.nextElement();
        String value = headersToString(request.getHeaders(name));
        log.debug("{}={}", name, value);
    }
    log.debug("===header   end============================================");
    log.debug("===parameter begin==========================================");
    Enumeration<String> parameterNames = request.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = parameterNames.nextElement();
        String value = StringUtils.join(request.getParameterValues(name), "||");
        log.debug("{}={}", name, value);
    }
    log.debug("===parameter   end==========================================");
    log.debug("=====================request   end==========================");
}

From source file:org.ambraproject.user.EnsureUserAccountInterceptor.java

/**
 * Check for a user matching the SSO ticket, if one exists.  Forwards to new profile page if no matching user exists.
 * <p/>//from   w  w w . j av  a  2  s. c o  m
 * The work flow is as such:
 * <p/>
 * 1. Check if there is a ticket from CAS
 * If not, then we do nothing.
 * If there is, then we:
 * 2. Check if a user object is in the session.
 * a. If not, look up the user in the database, and put it in the session.
 * i.  if the user is not in the database, this must be a new profile.  forward to profile creation page.
 * 3. Update the database to ensure that the email address on file for this user matches the one from CAS
 * TODO: this next step may be deprecated
 * 4. Check if the user object in the session has a display name
 * a. If not, the user is an old account.  forward to the update profile page
 *
 * @param actionInvocation
 * @return
 * @throws Exception
 */
public String intercept(final ActionInvocation actionInvocation) throws Exception {
    log.debug("ensure user account interceptor called");

    Map<String, Object> session = actionInvocation.getInvocationContext().getSession();

    //STEP 1: check if there is an auth id from cas
    final String authId = (String) session.get(AUTH_KEY);
    if (authId == null) {
        //No auth id, nothing to do here
        if (log.isDebugEnabled()) {
            log.debug("no single sign on user key");
            log.debug("ticket is: " + session.get(SINGLE_SIGNON_RECEIPT));
        }
        return actionInvocation.invoke();
    } else {
        //STEP 2: check if there's a user object in the session
        UserProfile ambraUser = (UserProfile) session.get(AMBRA_USER_KEY);
        if (ambraUser == null) {
            //No user object, so we must just be returning from CAS.  Look up the user in the db, and record their login
            final HttpServletRequest request = ServletActionContext.getRequest();
            ambraUser = (UserProfile) new TransactionTemplate(transactionManager)
                    .execute(new TransactionCallback() {
                        @Override
                        public Object doInTransaction(TransactionStatus transactionStatus) {
                            return userService.login(authId, new UserLogin(request.getRequestedSessionId(), //session id
                                    request.getRemoteAddr(), //ip
                                    request.getHeader("user-agent") //user-agent
                            ));
                        }
                    });
            if (ambraUser == null) {
                //No matching user in the database. redirect to the profile creation page
                log.debug("This is a new user with auth id: {}", authId);
                return ReturnCode.NEW_PROFILE;
            }
            //put the user in the session
            session.put(AMBRA_USER_KEY, ambraUser);
        }

        //STEP 3: make sure that ambra's email address matches the one from CAS
        String emailFromCAS = (String) session.get(SINGLE_SIGNON_EMAIL_KEY);
        if (emailFromCAS == null) {
            emailFromCAS = userService.fetchUserEmailFromCas(authId);
            session.put(SINGLE_SIGNON_EMAIL_KEY, emailFromCAS);
        }
        if (ambraUser.getEmail() == null || (!ambraUser.getEmail().equals(emailFromCAS))) {
            userService.updateEmail(ambraUser.getID(), emailFromCAS);
        }

        //STEP 4: Check if the user has a display name  (this is only relevant for old users)
        if (!StringUtils.hasText(ambraUser.getDisplayName())) {
            return ReturnCode.UPDATE_PROFILE;
        }
        //continue with the action invocation
        return actionInvocation.invoke();
    }
}

From source file:com.sonicle.webtop.core.app.shiro.WTFormAuthFilter.java

private void writeAuthLog(UsernamePasswordDomainToken token, HttpServletRequest request, String action) {
    WebTopApp wta = WebTopApp.getInstance();
    if (wta != null) {
        String domainId = StringUtils.defaultIfBlank(token.getDomain(), "?");
        String userId = StringUtils.defaultIfBlank(token.getUsername(), "?");
        UserProfileId pid = new UserProfileId(domainId, userId);
        wta.getLogManager().write(pid, CoreManifest.ID, action, null, request, request.getRequestedSessionId(),
                null);//from  ww  w.  j a  va2s . c  om
    }
}

From source file:org.bedework.eventreg.web.AbstractController.java

/**
 * @param req request//from  ww w . j  a  v  a  2s .co m
 */
public void dumpRequest(final HttpServletRequest req) {
    try {
        @SuppressWarnings("unchecked")
        final Enumeration<String> names = req.getParameterNames();

        final String title = "Request parameters";

        debug(title + " - global info and uris");
        debug("getRequestURI = " + req.getRequestURI());
        debug("getRemoteUser = " + req.getRemoteUser());
        debug("getRequestedSessionId = " + req.getRequestedSessionId());
        debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL());
        debug("query=" + req.getQueryString());
        debug("contentlen=" + req.getContentLength());
        debug("request=" + req);
        debug("parameters:");

        debug(title);

        while (names.hasMoreElements()) {
            final String key = names.nextElement();
            final String[] vals = req.getParameterValues(key);
            for (final String val : vals) {
                debug("  " + key + " = \"" + val + "\"");
            }
        }
    } catch (final Throwable t) {
        error(t);
    }
}

From source file:net.hillsdon.reviki.web.pages.impl.DefaultPageImpl.java

private boolean isSessionIdValid(final HttpServletRequest request) {
    final String postedSessionId = request.getParameter(PARAM_SESSION_ID);
    final String requestedSessionId = request.getRequestedSessionId();
    return requestedSessionId != null && postedSessionId != null && postedSessionId.equals(requestedSessionId)
            && request.isRequestedSessionIdValid();
}

From source file:com.icesoft.faces.webapp.http.servlet.ServletEnvironmentRequest.java

public ServletEnvironmentRequest(Object request, HttpSession session, Authorization authorization) {
    HttpServletRequest initialRequest = (HttpServletRequest) request;
    this.session = session;
    this.authorization = authorization;
    //Copy common data
    authType = initialRequest.getAuthType();
    contextPath = initialRequest.getContextPath();
    remoteUser = initialRequest.getRemoteUser();
    userPrincipal = initialRequest.getUserPrincipal();
    requestedSessionId = initialRequest.getRequestedSessionId();
    requestedSessionIdValid = initialRequest.isRequestedSessionIdValid();

    attributes = new HashMap();
    Enumeration attributeNames = initialRequest.getAttributeNames();
    while (attributeNames.hasMoreElements()) {
        String name = (String) attributeNames.nextElement();
        Object attribute = initialRequest.getAttribute(name);
        if ((null != name) && (null != attribute)) {
            attributes.put(name, attribute);
        }/*from ww  w  .  j av a  2s. c o m*/
    }

    // Warning:  For some reason, the various javax.include.* attributes are
    // not available via the getAttributeNames() call.  This may be limited
    // to a Liferay issue but when the MainPortlet dispatches the call to
    // the MainServlet, all of the javax.include.* attributes can be
    // retrieved using this.request.getAttribute() but they do NOT appear in
    // the Enumeration of names returned by getAttributeNames().  So here
    // we manually add them to our map to ensure we can find them later.
    String[] incAttrKeys = Constants.INC_CONSTANTS;
    for (int index = 0; index < incAttrKeys.length; index++) {
        String incAttrKey = incAttrKeys[index];
        Object incAttrVal = initialRequest.getAttribute(incAttrKey);
        if (incAttrVal != null) {
            attributes.put(incAttrKey, initialRequest.getAttribute(incAttrKey));
        }
    }

    headers = new HashMap();
    Enumeration headerNames = initialRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String name = (String) headerNames.nextElement();
        Enumeration values = initialRequest.getHeaders(name);
        headers.put(name, Collections.list(values));
    }

    parameters = new HashMap();
    Enumeration parameterNames = initialRequest.getParameterNames();
    while (parameterNames.hasMoreElements()) {
        String name = (String) parameterNames.nextElement();
        parameters.put(name, initialRequest.getParameterValues(name));
    }

    scheme = initialRequest.getScheme();
    serverName = initialRequest.getServerName();
    serverPort = initialRequest.getServerPort();
    secure = initialRequest.isSecure();

    //Copy servlet specific data
    cookies = initialRequest.getCookies();
    method = initialRequest.getMethod();
    pathInfo = initialRequest.getPathInfo();
    pathTranslated = initialRequest.getPathTranslated();
    queryString = initialRequest.getQueryString();
    requestURI = initialRequest.getRequestURI();
    try {
        requestURL = initialRequest.getRequestURL();
    } catch (NullPointerException e) {
        //TODO remove this catch block when GlassFish bug is addressed
        if (log.isErrorEnabled()) {
            log.error("Null Protocol Scheme in request", e);
        }
        HttpServletRequest req = initialRequest;
        requestURL = new StringBuffer(
                "http://" + req.getServerName() + ":" + req.getServerPort() + req.getRequestURI());
    }
    servletPath = initialRequest.getServletPath();
    servletSession = initialRequest.getSession();
    isRequestedSessionIdFromCookie = initialRequest.isRequestedSessionIdFromCookie();
    isRequestedSessionIdFromURL = initialRequest.isRequestedSessionIdFromURL();
    characterEncoding = initialRequest.getCharacterEncoding();
    contentLength = initialRequest.getContentLength();
    contentType = initialRequest.getContentType();
    protocol = initialRequest.getProtocol();
    remoteAddr = initialRequest.getRemoteAddr();
    remoteHost = initialRequest.getRemoteHost();
    initializeServlet2point4Properties(initialRequest);
}

From source file:com.redhat.rhn.frontend.servlets.DumpFilter.java

/** {@inheritDoc} */
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {

    if (log.isDebugEnabled()) {
        // handle request
        HttpServletRequest request = (HttpServletRequest) req;
        log.debug("Entered doFilter() ===================================");
        log.debug("AuthType: " + request.getAuthType());
        log.debug("Method: " + request.getMethod());
        log.debug("PathInfo: " + request.getPathInfo());
        log.debug("Translated path: " + request.getPathTranslated());
        log.debug("ContextPath: " + request.getContextPath());
        log.debug("Query String: " + request.getQueryString());
        log.debug("Remote User: " + request.getRemoteUser());
        log.debug("Remote Host: " + request.getRemoteHost());
        log.debug("Remote Addr: " + request.getRemoteAddr());
        log.debug("SessionId: " + request.getRequestedSessionId());
        log.debug("uri: " + request.getRequestURI());
        log.debug("url: " + request.getRequestURL().toString());
        log.debug("Servlet path: " + request.getServletPath());
        log.debug("Server Name: " + request.getServerName());
        log.debug("Server Port: " + request.getServerPort());
        log.debug("RESPONSE encoding: " + resp.getCharacterEncoding());
        log.debug("REQUEST encoding: " + request.getCharacterEncoding());
        log.debug("JVM encoding: " + System.getProperty("file.encoding"));
        logSession(request.getSession());
        logHeaders(request);/*from   w w  w. j av a2  s.c  o  m*/
        logCookies(request.getCookies());
        logParameters(request);
        logAttributes(request);
        log.debug("Calling chain.doFilter() -----------------------------");
    }

    chain.doFilter(req, resp);

    if (log.isDebugEnabled()) {
        log.debug("Returned from chain.doFilter() -----------------------");
        log.debug("Handle Response, not much to print");
        log.debug("Response: " + resp.toString());
        log.debug("Leaving doFilter() ===================================");
    }
}

From source file:net.fenyo.mail4hotspot.web.BrowserServlet.java

@Override
protected void doGet(final HttpServletRequest request, final HttpServletResponse response) throws IOException {
    // debug informations
    log.debug("doGet");
    log.debug("context path: " + request.getContextPath());
    log.debug("character encoding: " + request.getCharacterEncoding());
    log.debug("content length: " + request.getContentLength());
    log.debug("content type: " + request.getContentType());
    log.debug("local addr: " + request.getLocalAddr());
    log.debug("local name: " + request.getLocalName());
    log.debug("local port: " + request.getLocalPort());
    log.debug("method: " + request.getMethod());
    log.debug("path info: " + request.getPathInfo());
    log.debug("path translated: " + request.getPathTranslated());
    log.debug("protocol: " + request.getProtocol());
    log.debug("query string: " + request.getQueryString());
    log.debug("requested session id: " + request.getRequestedSessionId());
    log.debug("Host header: " + request.getServerName());
    log.debug("servlet path: " + request.getServletPath());
    log.debug("request URI: " + request.getRequestURI());
    @SuppressWarnings("unchecked")
    final Enumeration<String> header_names = request.getHeaderNames();
    while (header_names.hasMoreElements()) {
        final String header_name = header_names.nextElement();
        log.debug("header name: " + header_name);
        @SuppressWarnings("unchecked")
        final Enumeration<String> header_values = request.getHeaders(header_name);
        while (header_values.hasMoreElements())
            log.debug("  " + header_name + " => " + header_values.nextElement());
    }/*  w  w  w.  j  a v  a2s  .  c  o  m*/
    if (request.getCookies() != null)
        for (Cookie cookie : request.getCookies()) {
            log.debug("cookie:");
            log.debug("cookie comment: " + cookie.getComment());
            log.debug("cookie domain: " + cookie.getDomain());
            log.debug("cookie max age: " + cookie.getMaxAge());
            log.debug("cookie name: " + cookie.getName());
            log.debug("cookie path: " + cookie.getPath());
            log.debug("cookie value: " + cookie.getValue());
            log.debug("cookie version: " + cookie.getVersion());
            log.debug("cookie secure: " + cookie.getSecure());
        }
    @SuppressWarnings("unchecked")
    final Enumeration<String> parameter_names = request.getParameterNames();
    while (parameter_names.hasMoreElements()) {
        final String parameter_name = parameter_names.nextElement();
        log.debug("parameter name: " + parameter_name);
        final String[] parameter_values = request.getParameterValues(parameter_name);
        for (final String parameter_value : parameter_values)
            log.debug("  " + parameter_name + " => " + parameter_value);
    }

    // parse request

    String target_scheme = null;
    String target_host;
    int target_port;

    // request.getPathInfo() is url decoded
    final String[] path_info_parts = request.getPathInfo().split("/");
    if (path_info_parts.length >= 2)
        target_scheme = path_info_parts[1];
    if (path_info_parts.length >= 3) {
        target_host = path_info_parts[2];
        try {
            if (path_info_parts.length >= 4)
                target_port = new Integer(path_info_parts[3]);
            else
                target_port = 80;
        } catch (final NumberFormatException ex) {
            log.warn(ex);
            target_port = 80;
        }
    } else {
        target_scheme = "http";
        target_host = "www.google.com";
        target_port = 80;
    }

    log.debug("remote URL: " + target_scheme + "://" + target_host + ":" + target_port);

    // create forwarding request

    final URL target_url = new URL(target_scheme + "://" + target_host + ":" + target_port);
    final HttpURLConnection target_connection = (HttpURLConnection) target_url.openConnection();

    // be transparent for accept-language headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_languages = request.getHeaders("accept-language");
    while (accepted_languages.hasMoreElements())
        target_connection.setRequestProperty("Accept-Language", accepted_languages.nextElement());

    // be transparent for accepted headers
    @SuppressWarnings("unchecked")
    final Enumeration<String> accepted_content = request.getHeaders("accept");
    while (accepted_content.hasMoreElements())
        target_connection.setRequestProperty("Accept", accepted_content.nextElement());

}