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:neu.edu.lab08.HomeController.java

/**
 * Simply selects the home view to render by returning its name.
 * @throws Exception //from  ww  w .  ja  v  a2 s . co m
 */
@RequestMapping(value = "/", method = RequestMethod.GET)
public String initUserLoginForm(Model model, HttpServletRequest request) throws Exception {
    Cookie[] cookies = request.getCookies();
    String usernameCookie = "";
    String passwordCookie = "";
    for (Cookie cookie : cookies) {
        if (cookie.getName().equals("usernameCookie")) {
            usernameCookie = cookie.getValue();
        }
        if (cookie.getName().equals("passwordCookie")) {
            passwordCookie = cookie.getValue();
        }
    }
    User u = userDao.queryUserByNameAndPassword(usernameCookie, passwordCookie);
    if (u != null) {
        try {
            if (u.getRole().equals("admin")) {
                model.addAttribute("user", u);
                HttpSession session = request.getSession();
                session.setAttribute("username", u.getUsername());
                return "createUser";
            } else if (u.getRole().equals("CDC")) {
                HttpSession session = request.getSession();
                session.setAttribute("username", u.getUsername());
                model.addAttribute("user", u);
                ArrayList<Vaccine> vaccineList = vaccineDao.listVaccineByUsername(u.getUsername());
                ArrayList<Request> requestList = requestDao.listRequest();
                model.addAttribute("producedvaccineList", vaccineList);
                model.addAttribute("requestList", requestList);
                return "cdcMenu";
            } else if (u.getRole().equals("Hospital")) {
                HttpSession session = request.getSession();
                session.setAttribute("username", u.getUsername());
                model.addAttribute("user", u);
                ArrayList<Vaccine> vaccineList = vaccineDao.listVaccine();
                ArrayList<InsuredPatient> insuredPatientList = patientDao
                        .listInsuredPatientByUsername(u.getUsername());
                ArrayList<UninsuredPatient> uninsuredPatientList = patientDao
                        .listUninsuredPatientByUsername(u.getUsername());
                ArrayList<Inventory> inventoryList = inventoryDao.listInventoryByUser(u.getUsername());
                model.addAttribute("insuredPatientList", insuredPatientList);
                model.addAttribute("uninsuredPatientList", uninsuredPatientList);
                model.addAttribute("vaccineList", vaccineList);
                model.addAttribute("inventoryList", inventoryList);
                HttpSession inventorysession = request.getSession();
                inventorysession.setAttribute("inventoryList", inventoryList);
                ArrayList<UsedVaccine> usedvaccineList = vaccineDao.listUsedVaccineByUsername(u.getUsername());
                model.addAttribute("usedvaccineList", usedvaccineList);
                return "hospitalMenu";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    } else {
        User user = new User();
        model.addAttribute("user", user);

    }
    return "home";
}

From source file:com.medallia.spider.SpiderServlet.java

private RequestHandler makeRequest(HttpServletRequest req, final HttpServletResponse response) {
    final Map<String, String> m = Empty.hashMap();
    Cookie[] cookies = req.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            addCookie(m, c);/*from  w w  w .j  a v  a 2 s . c  o m*/
        }
    }
    return new RequestHandler() {
        @Implement
        public String getCookieValue(String name) {
            return m.get(name);
        }

        @Implement
        public void setCookieValue(String name, String value) {
            storeCookie(makeCookie(name, value));
        }

        @Implement
        public void setPersistentCookieValue(String name, String value, int expiry) {
            if (expiry <= 0)
                throw new IllegalArgumentException("expiry must be a positive number: " + expiry);

            Cookie c = makeCookie(name, value);
            c.setMaxAge(expiry);
            storeCookie(c);
        }

        @Implement
        public void removeCookieValue(String name) {
            Cookie c = makeCookie(name, null);
            c.setMaxAge(0);
            storeCookie(c);
        }

        private void storeCookie(Cookie c) {
            response.addCookie(c);
            addCookie(m, c);
        }

        private Cookie makeCookie(String name, String value) {
            return new Cookie(name, value);
        }
    };
}

From source file:com.xpn.xwiki.user.impl.xwiki.MyPersistentLoginManager.java

/**
 * Checks if the cookies are valid./*from  ww w  . ja va  2 s .  co m*/
 * 
 * @param request The servlet request.
 * @param response The servlet response.
 * @return True if the validation cookie holds a valid value or is not present, false otherwise.
 * @todo Don't ignore it when set to "false", check the validation method.
 */
private boolean checkValidation(HttpServletRequest request, HttpServletResponse response) {
    if (this.protection.equals(PROTECTION_ALL) || this.protection.equals(PROTECTION_VALIDATION)) {
        String username = getCookieValue(request.getCookies(), getCookiePrefix() + COOKIE_USERNAME,
                DEFAULT_VALUE);
        String password = getCookieValue(request.getCookies(), getCookiePrefix() + COOKIE_PASSWORD,
                DEFAULT_VALUE);
        String cookieHash = getCookieValue(request.getCookies(), getCookiePrefix() + COOKIE_VALIDATION,
                DEFAULT_VALUE);
        String calculatedHash = getValidationHash(username, password, getClientIP(request));
        if (cookieHash.equals(calculatedHash)) {
            return true;
        } else {
            LOGGER.warn("Login cookie validation hash mismatch! Cookies have been tampered with");
            LOGGER.info("Login cookie is being deleted!");
            forgetLogin(request, response);
        }
    }
    return false;
}

From source file:com.glaf.core.util.RequestUtils.java

public static String getActorId(HttpServletRequest request) {
    String actorId = null;//from   ww  w. java2  s  .  c  om
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    HttpSession session = request.getSession(false);
    if (session != null) {
        String value = (String) session.getAttribute(Constants.LOGIN_INFO);
        Map<String, String> cookieMap = decodeValues(ip, value);
        if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
            actorId = cookieMap.get(Constants.LOGIN_ACTORID);
            logger.debug("#actorId=" + actorId);
        }
    }

    if (actorId == null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                    String value = cookie.getValue();
                    Map<String, String> cookieMap = decodeValues(ip, value);
                    // logger.debug("#cookieMap=" + cookieMap);
                    if (StringUtils.equals(cookieMap.get(Constants.LOGIN_IP), ip)) {
                        String time = cookieMap.get(Constants.TS);
                        long now = Long.MAX_VALUE - System.currentTimeMillis();
                        if (StringUtils.isNumeric(time)
                                && (Long.parseLong(time) - now) < COOKIE_LIVING_SECONDS * 1000) {
                            actorId = cookieMap.get(Constants.LOGIN_ACTORID);
                            break;
                        }
                    }
                }
            }
        }
    }

    logger.debug("@actorId=" + actorId);

    return actorId;
}

From source file:com.example.web.Update_profile.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        String fileName = "";
        int f = 0;
        String user = null;/*from  w w  w . j  ava  2s .  c  o m*/
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals("user")) {
                    user = cookie.getValue();
                }
            }
        }
        String email = request.getParameter("email");
        String First_name = request.getParameter("First_name");
        String Last_name = request.getParameter("Last_name");
        String Phone_number_1 = request.getParameter("Phone_number_1");
        String Address = request.getParameter("Address");
        String message = "";
        int valid = 1;
        String query;
        ResultSet rs;
        Connection conn;
        String url = "jdbc:mysql://localhost:3306/";
        String dbName = "tworld";
        String driver = "com.mysql.jdbc.Driver";
        isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            // maximum size that will be stored in memory
            factory.setSizeThreshold(maxMemSize);
            // Location to save data that is larger than maxMemSize.
            //factory.setRepository(new File("/var/lib/tomcat7/webapps/www_term_project/temp/"));
            factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

            // Create a new file upload handler
            ServletFileUpload upload = new ServletFileUpload(factory);
            // maximum file size to be uploaded.
            upload.setSizeMax(maxFileSize);

            try {
                // Parse the request to get file items.
                List fileItems = upload.parseRequest(request);

                // Process the uploaded file items
                Iterator i = fileItems.iterator();

                while (i.hasNext()) {
                    FileItem fi = (FileItem) i.next();
                    if (!fi.isFormField()) {
                        // Get the uploaded file parameters
                        String fieldName = fi.getFieldName();
                        fileName = fi.getName();
                        String contentType = fi.getContentType();
                        boolean isInMemory = fi.isInMemory();
                        long sizeInBytes = fi.getSize();
                        String[] spliting = fileName.split("\\.");
                        // Write the file
                        System.out.println(sizeInBytes + " " + maxFileSize);
                        System.out.println(spliting[spliting.length - 1]);
                        if (!fileName.equals("")) {
                            if ((sizeInBytes < maxFileSize) && (spliting[spliting.length - 1].equals("jpg")
                                    || spliting[spliting.length - 1].equals("png")
                                    || spliting[spliting.length - 1].equals("jpeg"))) {

                                if (fileName.lastIndexOf("\\") >= 0) {
                                    file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
                                } else {
                                    file = new File(
                                            filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
                                }
                                fi.write(file);
                                System.out.println("Uploaded Filename: " + fileName + "<br>");
                            } else {
                                valid = 0;
                                message = "not a valid image";
                            }
                        }
                    }
                    BufferedReader br = null;
                    StringBuilder sb = new StringBuilder();

                    String line;
                    try {
                        br = new BufferedReader(new InputStreamReader(fi.getInputStream()));
                        while ((line = br.readLine()) != null) {
                            sb.append(line);
                        }
                    } catch (IOException e) {
                    } finally {
                        if (br != null) {
                            try {
                                br.close();
                            } catch (IOException e) {
                            }
                        }
                    }
                    if (f == 0) {
                        email = sb.toString();
                    } else if (f == 1) {
                        First_name = sb.toString();
                    } else if (f == 2) {
                        Last_name = sb.toString();
                    } else if (f == 3) {
                        Phone_number_1 = sb.toString();
                    } else if (f == 4) {
                        Address = sb.toString();
                    }
                    f++;

                }
            } catch (Exception ex) {
                System.out.println("hi");
                System.out.println(ex);

            }
        }
        try {
            Class.forName(driver).newInstance();
            conn = DriverManager.getConnection(url + dbName, "admin", "admin");
            if (!email.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `email`=? where `Username`=?");
                pst.setString(1, email);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!First_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `First_name`=? where `Username`=?");
                pst.setString(1, First_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Last_name.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Last_name`=? where `Username`=?");
                pst.setString(1, Last_name);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Phone_number_1.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Phone_number_1`=? where `Username`=?");
                pst.setString(1, Phone_number_1);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!Address.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Address`=? where `Username`=?");
                pst.setString(1, Address);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }
            if (!fileName.equals("")) {
                PreparedStatement pst = (PreparedStatement) conn
                        .prepareStatement("update `tworld`.`users` set `Fototitle`=? where `Username`=?");
                pst.setString(1, fileName);
                pst.setString(2, user);
                pst.executeUpdate();
                pst.close();
            }

        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | SQLException ex) {
            System.out.println("hi mom");
        }

        request.setAttribute("s_page", "4");
        request.getRequestDispatcher("/index.jsp").forward(request, response);
    }
}

From source file:com.yaodu.framework.controller.product.ProductSearchController.java

private List<ProductBascInfo> getRecentlyViewedList(HttpServletRequest request) {
    List<ProductBascInfo> recentlyViewedList = null;
    if (null != request) {
        Cookie[] cookie = request.getCookies();
        if (null == cookie) {
            return recentlyViewedList;
        }//from w ww  . j  a v  a  2s  .c  o  m
        for (int i = 0; i < cookie.length; i++) {
            Cookie cook = cookie[i];

            if (cook.getName().equalsIgnoreCase("relatedProducts")) { // ?
                if (!"".equals(cook.getValue().toString())) {
                    final String[] arrs = cook.getValue().split("\\|");
                    recentlyViewedList = productSolrjSearchService.findProductsByIds(arrs);

                    Collections.sort(recentlyViewedList, new Comparator<ProductBascInfo>() {
                        public int compare(ProductBascInfo p1, ProductBascInfo p2) {
                            return Integer.valueOf(ArrayUtils.indexOf(arrs, p1.getnId()))
                                    .compareTo(ArrayUtils.indexOf(arrs, p2.getnId()));
                        }
                    });
                }
                break;
            }
        }
    }

    return recentlyViewedList;
}

From source file:org.esgf.globusonline.GOauthView4Controller.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.POST)
public ModelAndView doPost(final HttpServletRequest request) {

    //grab the dataset name, file names and urls from the query string
    String dataset_name = request.getParameter("id");
    String[] file_names = request.getParameterValues("child_id");
    String[] file_urls = request.getParameterValues("child_url");

    Map<String, Object> model = new HashMap<String, Object>();

    String myproxyServerStr = null;

    HttpSession session = request.getSession(false);
    if (session == null) {
    } else {//from  ww  w .j a  va2  s  .co m
    }

    try {
        //get the openid here from the cookie
        Cookie[] cookies = request.getCookies();
        String openId = "";
        for (int i = 0; i < cookies.length; i++) {
            if (cookies[i].getName().equals("esgf.idp.cookie")) {
                openId = cookies[i].getValue();
            }
        }

        LOG.debug("Got User OpenID: " + openId);
        myproxyServerStr = Utils.resolveMyProxyViaOpenID(openId);
        LOG.debug("Using MyProxy Server: " + myproxyServerStr);

        ESGFProperties esgfProperties = new ESGFProperties();
        UserInfoDAO uid = new UserInfoDAO(esgfProperties);
        UserInfo userInfo = uid.getUserByOpenid(openId);
        String myproxyUserName = userInfo.getUserName();

        LOG.debug("Got MyProxy Username: " + myproxyUserName);
        //System.out.println("Got MyProxy Username: " + myproxyUserName);

        if (request.getParameter(GOFORMVIEW_MODEL) != null) {
            //it should never come here...
        } else {
            session.setAttribute("myproxyServerStr", myproxyServerStr);
            session.setAttribute("myproxyUserName", myproxyUserName);
            //place the dataset name, file names and urls into the model
            model.put(GOFORMVIEW_MYPROXY_SERVER, myproxyServerStr);
            model.put(GOFORMVIEW_SRC_MYPROXY_USER, myproxyUserName);
            //   model.put(GOFORMVIEW_FILE_URLS, file_urls);
            //   model.put(GOFORMVIEW_FILE_NAMES, file_names);
            model.put(GOFORMVIEW_DATASET_NAME, dataset_name);
        }
    } catch (YadisException ye) {
        String eMsg = ye.toString();
        if (eMsg.indexOf("0x702") != -1) {
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG,
                    "Please <a href=\"login\">Login</a>" + " before trying to download data!");
        } else {
            String errorMsg = "Failed to resolve OpenID: " + ye;
            LOG.error("Failed to resolve OpenID: " + ye);
            model.put(GOFORMVIEW_ERROR, "error");
            model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                    + " logged in as a valid user before trying to download data!<br><br>");
        }
    } catch (Exception e) {
        String errorMsg = "Failed to resolve OpenID: " + e;
        LOG.error("Failed to resolve OpenID: " + e);
        model.put(GOFORMVIEW_ERROR, "error");
        model.put(GOFORMVIEW_ERROR_MSG, errorMsg + "<br><br>Please make sure that you're"
                + " logged in as a valid user before trying to download data!<br><br>");
    }
    return new ModelAndView("goauthview4", model);
}

From source file:org.eclipse.userstorage.tests.util.USSServer.java

private Session getSession(HttpServletRequest request) {
    String csrfToken = request.getHeader("X-CSRF-Token");
    if (csrfToken != null) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("SESSION".equals(cookie.getName())) {
                    String sessionID = cookie.getValue();
                    Session session = sessions.get(sessionID);

                    if (session != null && session.getCSRFToken().equals(csrfToken)) {
                        return session;
                    }//from w  w w . j a v a 2s  . c  o  m

                    break;
                }
            }
        }
    }

    return null;
}

From source file:com.qlkh.client.server.proxy.ProxyServlet.java

/**
 * Retrieves all of the cookies from the servlet request and sets them on
 * the proxy request// ww w. j  a v  a  2 s .  co 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
 */
@SuppressWarnings("unchecked")
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.astamuse.asta4d.web.test.dispatch.RequestDispatcherTest.java

@Test(dataProvider = "data")
public void execute(String method, String url, int status, ContentProvider contentProvider) throws Exception {
    WebApplicationContext context = (WebApplicationContext) Context.getCurrentThreadContext();
    HttpServletRequest request = context.getRequest();
    HttpServletResponse response = context.getResponse();
    HttpSession session = mock(HttpSession.class);

    when(request.getParameterNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getCookies()).thenReturn(new Cookie[0]);
    when(request.getHeaderNames()).thenReturn(Collections.emptyEnumeration());
    when(request.getSession(true)).thenReturn(session);

    when(request.getRequestURI()).thenReturn(url);
    when(request.getContextPath()).thenReturn("");
    when(request.getMethod()).thenReturn(method);

    final ByteArrayOutputStream responseBos = new ByteArrayOutputStream();
    when(response.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override//from w  ww.  j av a2  s  .  c  o m
        public void write(int b) throws IOException {
            responseBos.write(b);
        }
    });

    HandyRuleSet ruleSet = new HandyRuleSet();
    initTestRules(ruleSet);

    if (url.equals("/index-rewrite")) {
        context.setAccessURI("/index");
    }

    dispatcher.dispatchAndProcess(ruleSet.getArrangedRuleList());

    // verify status at first then when contentProvider is null, we do not
    // need to do more verification
    if (status != 0) {
        verify(response).setStatus(status);
    }

    if (contentProvider == null) {
        return;
    }

    // prepare expected results
    HttpServletResponse expectedResponse = mock(HttpServletResponse.class);

    final ByteArrayOutputStream expectedBos = new ByteArrayOutputStream();
    when(expectedResponse.getOutputStream()).thenReturn(new ServletOutputStream() {
        @Override
        public void write(int b) throws IOException {
            expectedBos.write(b);
        }
    });

    final List<Pair<String, String>> expectedHeaderList = new LinkedList<>();

    doAnswer(new Answer<Object>() {
        public Object answer(InvocationOnMock invocation) {
            Object[] args = invocation.getArguments();
            expectedHeaderList.add(Pair.of((String) args[0], (String) args[1]));
            return null;
        }
    }).when(expectedResponse).addHeader(anyString(), anyString());

    UrlMappingRule currentRule = context.getCurrentRule();
    contentProvider.produce(currentRule, expectedResponse);

    // verify extra contents like headers and output stream

    for (Pair<String, String> pair : expectedHeaderList) {
        verify(response).addHeader(pair.getKey(), pair.getValue());
    }

    Assert.assertEquals(new String(responseBos.toByteArray()), new String(expectedBos.toByteArray()));

}