Example usage for javax.servlet.http HttpServletRequest getCookies

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

Introduction

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

Prototype

public Cookie[] getCookies();

Source Link

Document

Returns an array containing all of the Cookie objects the client sent with this request.

Usage

From source file:cn.vlabs.umt.ui.servlet.AuthorizationCodeServlet.java

/**
 * ????/* w  w w.  ja va 2  s.co m*/
 * @param request
 */
private void dealCoremailUserName(HttpServletRequest request) {
    Cookie[] cs = request.getCookies();
    if (cs != null) {
        for (Cookie c : cs) {
            if ("passport.remember.user".equals(c.getName())) {
                if (StringUtils.isNotEmpty(c.getValue())) {
                    request.setAttribute("userName", c.getValue());
                }
            }
        }
    }
}

From source file:EditImage.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    Security sec = new Security();

    PrintWriter out = response.getWriter();

    // Check to makes sure the user is logged in
    String userid = "";
    Cookie login_cookie = null;/* w  w w .j  a  va2  s .  c o m*/
    Cookie cookie = null;
    Cookie[] cookies = null;
    // Get an array of cookies associated with this domain
    cookies = request.getCookies();
    // If any cookies were found, see if any of them contain a valid login.
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookie = cookies[i];
            // out.println(cookie.getName()+"<br>");
            // However, we only want one cookie, the one whose name matches
            // the
            // userid that has logged in on this browser.
            if (i != 0 && userid == "") {
                userid = cookie.getName();
            }
        }
    }
    // If no login was detected, redirect the user to the login page.
    if (userid == "") {
        out.println("<a href=login.jsp>Please login to access this site.</a>");
    }
    // Else, we have a valid session.
    else {
        // Gets the photo_id from the Query String
        String photo_id = request.getQueryString();

        // Variables
        String command = "";
        InputStream instream = null;
        Statement stmt = null;
        PreparedStatement updateSub = null;
        PreparedStatement updateLoc = null;
        PreparedStatement updateDate = null;
        PreparedStatement updateDesc = null;
        PreparedStatement updatePrivacy = null;

        // Default variables to add to table
        String subject = null;
        String place = null;
        String timing = null;
        String description = null;
        String permission = null;
        String groupName = null;

        try {

            // Gets the parameters for subject, place, timing, & description
            subject = request.getParameter("subject");
            place = request.getParameter("place");
            timing = request.getParameter("SnapHost_Calendar");
            description = request.getParameter("description");
            permission = request.getParameter("permission");
            groupName = request.getParameter("group");
            response_message = response_message + subject + place + timing + description + "PHOTO ID = "
                    + photo_id;

            // Connect to the database and create a statement
            Connection conn;
            conn = getConnected(drivername, dbstring, username, password);
            stmt = conn.createStatement();
            response_message = response_message + "connection good";

            // Only updates fields that had input
            if (!subject.isEmpty()) {
                updateSub = conn.prepareStatement(
                        "UPDATE images SET subject = \'" + subject + "\' WHERE photo_id = " + photo_id);
                updateSub.executeUpdate();
            }

            if (!place.isEmpty()) {
                updateLoc = conn.prepareStatement(
                        "UPDATE images SET place = \'" + place + "\' WHERE photo_id = " + photo_id);
                updateLoc.executeUpdate();
            }

            if (!timing.isEmpty()) {
                updateDate = conn.prepareStatement("UPDATE images SET timing = to_date('" + timing
                        + "', 'YYYY-MM-DD') WHERE photo_id = " + photo_id);
                updateDate.executeUpdate();
            }

            if (!description.isEmpty()) {
                updateDesc = conn.prepareStatement(
                        "UPDATE images SET description = \'" + description + "\' WHERE photo_id = " + photo_id);
                updateDesc.executeUpdate();
            }
            if (!permission.isEmpty()) {
                // Sets the permissions Value depending on what the user specified
                // Default is private 
                int permissionValue = 2;
                if (permission.equals("everyone")) {
                    permissionValue = 1;
                } else if (permission.equals("useronly")) {
                    permissionValue = 2;
                } else if (permission.equals("group")) {
                    // Set permission value to 0 to indicate no
                    // valid group in the case the user does not
                    // supply a valid group ID.
                    permissionValue = 0;
                    // What we actually want is the group ID
                    String groupid = sec.find_group_id(userid, groupName, conn);
                    // If a matching group ID is found, add it.
                    if (groupid != "") {
                        permissionValue = Integer.parseInt(groupid);
                    }

                }

                updateDesc = conn.prepareStatement("UPDATE images SET permitted = \'" + permissionValue
                        + "\' WHERE photo_id = " + photo_id);
                updateDesc.executeUpdate();
            }

            response_message = "Image Updated!";

        } catch (Exception e) {
            response_message = response_message + "uh oh";
        }
        try {
            // Output response to the client
            response.setContentType("text/html");
            out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 " + "Transitional//EN\">\n" + "<HTML>\n"
                    + "<HEAD><TITLE>Upload Message</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>" + response_message
                    + "</H1>\n" + "</BODY></HTML>");
            out.println("<P><a href=\"GetBigPic?big" + photo_id + "\"> Back To Image </a>");
            out.println("</body>");
            out.println("</html>");
        } catch (Exception e) {
            response_message = response_message + "4";
        }
    }
}

From source file:com.datatorrent.stram.security.StramWSFilter.java

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
        throws IOException, ServletException {
    if (!(req instanceof HttpServletRequest)) {
        throw new ServletException("This filter only works for HTTP/HTTPS");
    }/*from   ww  w.  j  a  v  a  2s .c  om*/

    HttpServletRequest httpReq = (HttpServletRequest) req;
    HttpServletResponse httpResp = (HttpServletResponse) resp;
    if (LOG.isDebugEnabled()) {
        LOG.debug("Remote address for request is: " + httpReq.getRemoteAddr());
    }
    String requestURI = httpReq.getRequestURI();
    if (LOG.isDebugEnabled()) {
        LOG.debug("Request path " + requestURI);
    }
    boolean authenticate = true;
    String user = null;
    if (getProxyAddresses().contains(httpReq.getRemoteAddr())) {
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (WEBAPP_PROXY_USER.equals(c.getName())) {
                    user = c.getValue();
                    break;
                }
            }
        }
        if (requestURI.equals(WebServices.PATH) && (user != null)) {
            String token = createClientToken(user, httpReq.getLocalAddr());
            if (LOG.isDebugEnabled()) {
                LOG.debug("Create token " + token);
            }
            Cookie cookie = new Cookie(CLIENT_COOKIE, token);
            httpResp.addCookie(cookie);
        }
        authenticate = false;
    }
    if (authenticate) {
        Cookie cookie = null;
        if (httpReq.getCookies() != null) {
            for (Cookie c : httpReq.getCookies()) {
                if (c.getName().equals(CLIENT_COOKIE)) {
                    cookie = c;
                    break;
                }
            }
        }
        boolean valid = false;
        if (cookie != null) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Verifying token " + cookie.getValue());
            }
            user = verifyClientToken(cookie.getValue());
            valid = true;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Token valid");
            }
        }
        if (!valid) {
            httpResp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
    }

    if (user == null) {
        LOG.warn("Could not find " + WEBAPP_PROXY_USER + " cookie, so user will not be set");
        chain.doFilter(req, resp);
    } else {
        final StramWSPrincipal principal = new StramWSPrincipal(user);
        ServletRequest requestWrapper = new StramWSServletRequestWrapper(httpReq, principal);
        chain.doFilter(requestWrapper, resp);
    }
}

From source file:com.sourcesense.confluence.servlets.CMISProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request//from  w ww .  ja v a 2  s.c  o  m
 *
 * @param httpServletRequest     The request object representing the client's
 *                               request to the servlet engine
 * @param httpMethodProxyRequest The request that we are about to send to
 *                               the proxy host
 */
private void setProxyRequestCookies(HttpServletRequest httpServletRequest, HttpMethod httpMethodProxyRequest) {
    // Get an array of all of all the cookies sent by the client
    Cookie[] cookies = httpServletRequest.getCookies();
    if (cookies == null) {
        return;
    }

    for (Cookie cookie : cookies) {
        cookie.setDomain(stringProxyHost);
        cookie.setPath(httpServletRequest.getServletPath());
        httpMethodProxyRequest.setRequestHeader("Cookie",
                cookie.getName() + "=" + cookie.getValue() + "; Path=" + cookie.getPath());
    }
}

From source file:com.google.gsa.valve.rootAuth.RootAuthorizationProcess.java

/**
 * Deletes all cookies that start with "gsa"
 * /*from w  ww  .  j a v  a  2s. com*/
 * @param request HTTP request
 * @param response HTTP response
 */
public void deleteCookies(HttpServletRequest request, HttpServletResponse response) {

    // Retrieve cookies
    Cookie[] allCookies = request.getCookies();
    try {
        // Protection
        if (allCookies != null) {

            // Look for the authentication cookie
            for (int i = 0; i < allCookies.length; i++) {

                logger.debug("Cookie: " + allCookies[i].getName());

                //look for all the cookies start with "gsa" and delete them
                if ((allCookies[i].getName()).startsWith("gsa")) {

                    Cookie gsaCookie = new Cookie(allCookies[i].getName(), allCookies[i].getValue());

                    gsaCookie.setMaxAge(0);

                    response.addCookie(gsaCookie);

                    // Debug
                    if (logger.isDebugEnabled())
                        logger.debug("GSA cookie: [" + gsaCookie.getName() + " has been deleted ]");

                }

            }

        }
    } catch (Exception e) {
        logger.error("Error when deleting cookies: " + e.getMessage(), e);
    }
}

From source file:de.innovationgate.wgpublisher.filter.WGAFilter.java

private Cookie getCookie(HttpServletRequest request, String name) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(name)) {
                return cookie;
            }//from ww  w.ja va2  s.  c  o  m
        }
    }
    return null;
}

From source file:com.vmware.demo.HomeController.java

@RequestMapping(value = "/sso", method = RequestMethod.GET)
public String createForm(HttpServletRequest request, Locale locale, Model model) {
    if (null != request.getSession().getAttribute(ATTRIBUTE_SAML_CERTIFICATE)) {
        model.addAttribute(ATTRIBUTE_SAML_CERTIFICATE,
                request.getSession().getAttribute(ATTRIBUTE_SAML_CERTIFICATE));
    }/*from ww w.j a  v a  2 s. c o m*/
    if (null != request.getSession().getAttribute(ATTRIBUTE_IDP_URI)) {
        model.addAttribute(ATTRIBUTE_IDP_URI, request.getSession().getAttribute(ATTRIBUTE_IDP_URI));
    } else {
        String cookieValue = null;
        Cookie[] cookies = request.getCookies();
        if (null != cookies) {
            for (Cookie cookie : cookies) {
                if (COOKIE_NAME.equals(cookie.getName())) {
                    cookieValue = cookie.getValue();
                }
            }
        }
        if (null != cookieValue) {
        } else {
            model.addAttribute(ATTRIBUTE_IDP_URI, DEFAULT_SAML_CONSUMER);
        }
    }
    model.addAttribute(ATTRIBUTE_META_DATA, generateMetaData(request));
    model.addAttribute(ATTRIBUTE_RELAY_STATE, getURLWithContextPath(request));
    model.addAttribute("action", "setup");
    return "home";
}

From source file:neu.edu.lab08.HomeController.java

@RequestMapping(value = "/logout", method = RequestMethod.GET)
public String logout(Model model, HttpServletRequest request, HttpServletResponse response) throws Exception {
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            cookies[i].setValue("");
            cookies[i].setPath("/");
            cookies[i].setMaxAge(0);/*from w w  w .  ja  v  a2 s.  c om*/
            response.addCookie(cookies[i]);
        }
    }
    //      model.addAttribute("user", null);
    //      model.addAttribute("messageList", null);
    //      model.addAttribute("contactsList", null);
    //      HttpSession session = request.getSession();
    //        session.setAttribute("username", null);
    return initUserLoginForm(model, request);
}

From source file:org.apache.jsp.sources_jsp.java

public static String getBrowserInfiniteCookie(HttpServletRequest request) {
       Cookie[] cookieJar = request.getCookies();
       if (cookieJar != null) {
           for (Cookie cookie : cookieJar) {
               if (cookie.getName().equals("infinitecookie")) {
                   return cookie.getValue() + ";";
               }/*w  w  w  . j  a v a2 s .c om*/
           }
       }
       return null;
   }

From source file:eu.europeana.core.util.web.ClickStreamLoggerImpl.java

private String printLogAffix(HttpServletRequest request) {
    String ip = request.getRemoteAddr();
    String reqUrl = getRequestUrl(request);
    final User user = ControllerUtil.getUser();
    String userId;/* w w  w . j  a v a2 s. com*/
    if (user != null) {
        userId = user.getEmail(); // todo: is this desirable?  was id.toString()
    } else {
        userId = "";
    }
    String language = ControllerUtil.getLocale(request).toString();
    String userAgent = request.getHeader("User-Agent");
    String referer = request.getHeader("referer");
    Cookie[] cookies = request.getCookies();
    String utma = "";
    String utmb = "";
    String utmc = "";
    String utmz = "";
    String languageCookie = "";
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (cookie.getName().equalsIgnoreCase("__utma")) {
                utma = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmb")) {
                utmb = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmc")) {
                utmc = cookie.getValue();
            } else if (cookie.getName().equalsIgnoreCase("__utmz")) {
                utmz = cookie.getValue();
            } else if (cookie.getName()
                    .equalsIgnoreCase("org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE")) {
                languageCookie = cookie.getValue();
            }
        }
    }
    PortalTheme theme = themeHandler.getByRequest(request);
    return MessageFormat.format(
            "userId={0}, lang={1}, req={4}, date={2}, ip={3}, user-agent={5}, referer={6}, utma={8}, "
                    + "utmb={9}, utmc={10}, utmz={13}, v={7}, duration={11}, langCookie={12}, defaultLanguage={14}",
            userId, language, new DateTime(), ip, reqUrl, userAgent, referer, VERSION, utma, utmb, utmc,
            ClickStreamLoggerInterceptor.getTimeElapsed(), languageCookie, utmz, theme.getDefaultLanguage());
}