Example usage for javax.servlet.http Cookie Cookie

List of usage examples for javax.servlet.http Cookie Cookie

Introduction

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

Prototype

public Cookie(String name, String value) 

Source Link

Document

Constructs a cookie with the specified name and value.

Usage

From source file:com.paperfood.controller.Authenticate.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//* ww w .  j  a  v  a  2 s.c  o  m*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();
    HttpSession session = request.getSession(true);
    JSONObject resp = new JSONObject();
    MD5Hash md5;
    String status = "";
    try {
        md5 = new MD5Hash();
        String req_type = request.getParameter("type");
        if (req_type.equalsIgnoreCase("login")) //Request of Login
        {
            String loginEmail = request.getParameter("loginEmail");
            String loginPass = md5.getStringHash(request.getParameter("loginPass"));
            boolean loginRemember = request.getParameter("loginRemember").equalsIgnoreCase("true");

            DatabaseManager dm = new DatabaseManager();
            dm.open();
            PaperFoodUser user = new PaperFoodUser();
            user = (PaperFoodUser) dm.getLoggedUser(loginEmail, loginPass);
            dm.close();
            if (user != null) //Credentials are valid, create session.
            {
                session.setAttribute("paperfooduseremail", user.getEmail());
                if (loginRemember) {
                    int time = 60 * 60 * 24 * 30;
                    Cookie c = new Cookie("paperfood", user.getEmail());
                    c.setMaxAge(time);
                    response.addCookie(c);
                }
                status = "success";
            } else
                status = "invalid";
        } else if (req_type.equalsIgnoreCase("cookielogin")) //Request for Cookie-based Login.
        {
            String loginEmail = request.getParameter("loginEmail");
            session.setAttribute("paperfooduseremail", loginEmail);
            status = "success";
        } else if (req_type.equalsIgnoreCase("sessionlogin")) //Request for Session-based Login.
        {
            String useremail = (String) session.getAttribute("paperfooduseremail");
            if (useremail != null)
                status = "success";
        } else if (req_type.equalsIgnoreCase("logout")) //Request for Logout.
        {
            session.invalidate();
            Cookie[] c = request.getCookies();
            if (c != null) {
                for (int i = 0; i < c.length; i++) {
                    Cookie curr = c[i];
                    String cnm = curr.getName();
                    if (cnm.equalsIgnoreCase("paperfood")) {
                        curr.setMaxAge(0);
                        response.addCookie(curr);
                    }
                }
            }
            status = "success";
        }
    } catch (CommunicationsException e) {
        status = "unavailable";
    } catch (Exception e) {
        status = "fail";
        e.printStackTrace();
    }

    try {
        resp.put("status", status);
    } catch (JSONException e) {
        e.printStackTrace();
    }
    response.setContentType("application/json");
    response.setCharacterEncoding("UTF-8");
    out.println(resp);
}

From source file:com.ms.commons.summer.security.web.DefaultSecurityFormResolver.java

/**
 * ?token????InvalidTokenException/* w w  w  . j  av  a  2 s.com*/
 * 
 * @param request
 * @param response
 * @throws InvalidTokenException
 */
public void validSessionToken(final HttpServletRequest request, final HttpServletResponse response)
        throws InvalidTokenException {
    Cookie[] cookies = request.getCookies();
    String ctoken = null;
    if (cookies != null) {
        for (Cookie cookie : cookies) {
            if (FORM_RESUBMIT_TOKEN.equals(cookie.getName())) {
                ctoken = cookie.getValue();
                break;
            }
        }
    }
    String rtoken = request.getParameter(FORM_RESUBMIT_TOKEN);
    if (rtoken == null || rtoken.length() == 0) {
        throw new InvalidTokenException("can't find token in request");
    }
    if (ctoken == null || ctoken.length() == 0) {
        throw new InvalidTokenException("can't find token in cookie");
    }
    if (!ctoken.equals(rtoken)) {
        throw new InvalidTokenException("failed to check for token in request");
    }
    // cookietoken?
    Cookie c = new Cookie(FORM_RESUBMIT_TOKEN, "");
    c.setPath("/");
    response.addCookie(c);
}

From source file:webim.service.WebimVisitorManager.java

private void createCookie(HttpServletResponse response, String vid) {
    Cookie cookie = new Cookie(COOKIE_VID, vid);
    response.addCookie(cookie);
}

From source file:com.zb.app.common.cookie.manager.WebSocketCookieManager.java

private Cookie[] str2Cookie(String cookies) {
    Map<String, String> cookieMap = str2Map(cookies);
    ObjectUtils.trim(cookieMap);/*  w  w w  . ja va2  s .  c  o m*/
    List<Cookie> cookieList = new ArrayList<Cookie>();
    for (Entry<String, String> entry : cookieMap.entrySet()) {
        cookieList.add(new Cookie(entry.getKey(), entry.getValue()));
    }
    Cookie[] array = cookieList.toArray(new Cookie[cookieList.size()]);
    return array;
}

From source file:com.taobao.ad.easyschedule.exsession.request.session.SessionCookieStore.java

/**
 * @param response/*from ww  w .java2 s.  co m*/
 * @param config
 * @param value
 * 
 * @throws Exception
 */
private void saveCookie(HttpServletResponse response, SessionAttributeConfig config, Object value)
        throws Exception {
    String cookieName = config.getNickName();
    int lifeTime = config.getLifeTime();

    //COOKIE
    String attrValue = getEncodedValue(config, value);
    Cookie cookie = null;

    if (attrValue != null) {
        // if (config.isEncrypt()) {
        attrValue = URLEncoder.encode(attrValue, "UTF-8");
        // }

        cookie = new Cookie(cookieName, attrValue);
    } else {
        cookie = new Cookie(cookieName, "");
    }

    log.debug("cookie name: " + cookieName + "  cookie value: " + attrValue);

    //COOKIE
    String cookiePath = COOKIE_PATH;

    if (config.getCookiePath() != null) {
        cookiePath = config.getCookiePath();
    }

    cookie.setPath(cookiePath);

    if (lifeTime > 0) {
        cookie.setMaxAge(lifeTime);
    }

    String domain = config.getDomain();

    if ((domain != null) && (domain.length() > 0)) {
        cookie.setDomain(domain);
    }

    response.addCookie(cookie);
}

From source file:net.geoprism.data.importer.ExcelController.java

@Override
public void exportExcelFile(String type, String country, String downloadToken)
        throws IOException, ServletException {

    try {//from   ww  w. ja  v a 2s.  c o  m
        // The reason we're including a cookie here is because the browser does not give us any indication of when our
        // response from the server is successful and its downloading the file.
        // This "hack" sends a downloadToken to the client, which the client then checks for the existence of every so
        // often. When the cookie exists, it knows its downloading it.
        // http://stackoverflow.com/questions/1106377/detect-when-browser-receives-file-download
        Cookie cookie = new Cookie("downloadToken", downloadToken);
        cookie.setMaxAge(10 * 60); // 10 minute cookie expiration
        resp.addCookie(cookie);

        InputStream istream = ExcelUtilDTO.exportExcelFile(this.getClientRequest(), type, country);

        try {
            // copy it to response's OutputStream
            this.resp.setContentType("application/xlsx");
            this.resp.setHeader("Content-Disposition", "attachment; filename=\"template.xlsx\"");

            IOUtils.copy(istream, this.resp.getOutputStream());

            this.resp.flushBuffer();
        } finally {
            istream.close();
        }
    } catch (RuntimeException e) {
        if (!resp.isCommitted()) {
            resp.reset();
        }

        ErrorUtility.prepareThrowable(e, req, resp, false, true);
    }
}

From source file:com.bacic5i5j.framework.toolbox.web.WebUtils.java

/**
 * cookie?//from  w ww . jav  a2s.c o m
 *
 * @param response
 * @param name
 * @param value
 * @param domain
 * @param expiry
 */
public static void setCookie(HttpServletResponse response, String name, String value, String domain,
        int expiry) {
    Cookie cookie = new Cookie(name, value);
    cookie.setDomain(domain);
    cookie.setPath("/");
    cookie.setMaxAge(expiry);

    response.addCookie(cookie);
}

From source file:controllers.LoginController.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//  w w w .java2 s.  co m
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    //User user = (User) request.getAttribute("user");
    //if (user != null) {
    // User has been already registered
    //response.sendRedirect(request.getContextPath() + "/home");
    //} else {
    // Login in user
    String email = request.getParameter("email"), password = request.getParameter("pass");

    JSONObject object = null;
    object = (JSONObject) ISConnector.validateLogin(email, password);
    if (object.containsKey("token")) {
        Cookie cookie = new Cookie("token", (String) object.get("token"));
        cookie.setPath("/");
        long expiredDate = -1;
        if (object.containsKey("expiry_date")) {
            expiredDate = (long) object.get("expiry_date") - new Timestamp(new Date().getTime()).getTime();
            expiredDate /= 1000;
            cookie.setMaxAge((int) expiredDate);
        }
        response.addCookie(cookie);
        response.sendRedirect(request.getContextPath() + "/home");
    } else if (object.containsKey("error")) {
        request.setAttribute("error", (String) object.get("error"));
        String error = (String) object.get("error");
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(error);
            out.println("</body>");
            out.println("</html>");

        }
        //doGet(request, response);
    } else {
        try (PrintWriter out = response.getWriter()) {
            /* TODO output your page here. You may use following sample code. */
            out.println("<!DOCTYPE html>");
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet coba2</title>");
            out.println("</head>");
            out.println("<body>");
            out.println(object);
            out.println("</body>");
            out.println("</html>");

        }
    }
    //}
}

From source file:org.tonguetied.web.CookieUtilsTest.java

/**
 * Test method for {@link org.tonguetied.web.CookieUtils#getCookie(HttpServletRequest, String)}.
 *//*from w  ww . j  a  v  a2 s  .c o m*/
@Test
public final void testGetCookieWhenCookieExists() {
    Cookie[] cookies = new Cookie[] { new Cookie("name", "value"), new Cookie("other1", "value"),
            new Cookie("other2", "value"), new Cookie("other3", "value"), new Cookie("other4", "value"),
            new Cookie("other5", "value") };
    request.setCookies(cookies);
    Cookie cookie = CookieUtils.getCookie(request, "name");
    assertEquals("name", cookie.getName());
    assertEquals("value", cookie.getValue());
}

From source file:com.woonoz.proxy.servlet.CookieFormatterTest.java

@Test(expected = InvalidCookieException.class)
public void testCookieNoName() throws InvalidCookieException {
    String sessionId = "JJJ2234312421";
    Cookie cookie = new Cookie("", sessionId);
    CookieFormatter.createFromServletCookie(cookie);
}