Example usage for javax.servlet.http Cookie getName

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

Introduction

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

Prototype

public String getName() 

Source Link

Document

Returns the name of the cookie.

Usage

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

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
 *//*w ww  .j  ava  2s  .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.glaf.core.util.RequestUtils.java

public static String getTheme(HttpServletRequest request) {
    String theme = "default";
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), Constants.THEME_COOKIE)) {
                if (cookie.getValue() != null) {
                    theme = cookie.getValue();
                }//from w ww. jav  a2 s . c  o m
            }
        }
    }
    if (StringUtils.isNotEmpty(request.getParameter("theme"))) {
        theme = request.getParameter("theme");
    }
    return theme;
}

From source file:hudson.plugins.codeviation.JavaFileIterableView.java

public ChartConf getChartConf(StaplerRequest req) {
    String chartTypePar = req.getParameter(CHART_TYPE_PARAM);

    if (chartTypePar == null) {
        Cookie cookies[] = req.getCookies();
        // cookies are null
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(CHART_TYPE_PARAM)) {
                    chartTypePar = cookie.getValue();
                    break;
                }//from  ww w  .  ja v a 2s  . co  m
            }
        }
    }
    for (ChartConf conf : getChartConfs()) {
        if (conf.getName().equals(chartTypePar)) {
            selectedChartConf = conf;
            return conf;
        }
    }
    selectedChartConf = null;
    return null;
}

From source file:com.googlesource.gerrit.plugins.github.oauth.GitHubLogin.java

private String getScopesKeyFromCookie(HttpServletRequest request) {
    Cookie[] cookies = request.getCookies();
    if (cookies == null) {
        return null;
    }//from w  ww . j  a v a 2  s.co  m

    for (Cookie cookie : cookies) {
        if (cookie.getName().equalsIgnoreCase("scope")) {
            return cookie.getValue();
        }
    }
    return null;
}

From source file:spring.travel.site.controllers.OffersControllerTest.java

@Test
public void shouldGetOffersAndAdverts() throws Exception {
    stubGet("/user?id=123", new User("123", "Fred", "Flintstone", "freddyf", Optional.<Address>empty()));

    stubGet("/profile/user/123", new Profile(LifeCycle.Family, Spending.Economy, Gender.Male));

    stubGet("/loyalty/user/123", new Loyalty(Group.Bronze, 100));

    List<Offer> offers = Arrays.asList(new Offer("Offer 1", "Blah blah", "offer1.jpg"),
            new Offer("Offer 2", "Blah blah", "offer2.jpg"), new Offer("Offer 3", "Blah blah", "offer3.jpg"),
            new Offer("Offer 4", "Blah blah", "offer4.jpg"));

    stubGet("/offers?lifecycle=family&spending=economy&gender=male&loyalty=bronze", offers);

    List<Advert> adverts = Arrays.asList(new Advert("Advert 1", "advert1.jpg", "Blah blah"),
            new Advert("Advert 2", "advert2.jpg", "Blah blah"),
            new Advert("Advert 3", "advert3.jpg", "Blah blah"),
            new Advert("Advert 4", "advert4.jpg", "Blah blah"),
            new Advert("Advert 5", "advert5.jpg", "Blah blah"));

    stubGet("/adverts?count=4&target=low", adverts);

    String signature = "0923023985092384";
    String cookieName = "GETAWAY_SESSION";
    String encoded = "id=123";
    String cookieValue = signature + "-" + encoded;

    Cookie cookie = Mockito.mock(Cookie.class);
    when(cookie.getName()).thenReturn(cookieName);
    when(cookie.getValue()).thenReturn(cookieValue);

    when(mockVerifier.verify(encoded, signature)).thenReturn(true);

    MvcResult mvcResult = this.mockMvc
            .perform(get("/offers").accept(MediaType.parseMediaType("application/json;charset=UTF-8"))
                    .header("Cookie", cookieName + "=" + cookieValue))
            .andExpect(status().isOk()).andExpect(request().asyncStarted())
            .andExpect(request().asyncResult(isA(ModelAndView.class))).andReturn();

    this.mockMvc.perform(asyncDispatch(mvcResult)).andExpect(status().isOk());

    ModelAndView modelAndView = (ModelAndView) mvcResult.getAsyncResult(1000);

    Map<String, Object> model = modelAndView.getModel();

    User user = (User) model.get("user");
    assertEquals("Fred", user.getFirstName());

    OffersView modelOffers = (OffersView) model.get("offers");
    assertNotNull(modelOffers);/*from w  w w .  ja  v  a2  s.  co m*/
    assertEquals("Offer 1", modelOffers.getOffers().get(0).getTitle());

    AdvertsView modelAdverts = (AdvertsView) model.get("adverts");
    assertNotNull(modelAdverts);
    assertEquals("Advert 1", modelAdverts.getAdverts().get(0).getTitle());
}

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

public static void removeLoginUser(HttpServletRequest request, HttpServletResponse response) {
    Cookie[] cookies = request.getCookies();
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            if (StringUtils.equals(cookie.getName(), Constants.COOKIE_NAME)) {
                cookie.setMaxAge(0);//from  w w w  .  j ava2s  .c o  m
                cookie.setPath("/");
                cookie.setValue(UUID32.getUUID());
                response.addCookie(cookie);
                logger.debug("remove user from cookie");
            }
        }
    }

    HttpSession session = request.getSession(false);
    if (session != null) {
        session.removeAttribute(Constants.LOGIN_INFO);
        session.invalidate();
    }
}

From source file:eu.semlibproject.annotationserver.managers.CookiesManager.java

/**
 * Remove an annotation server cookie/*  www . jav a  2s .c  o  m*/
 * 
 * @param request
 * @param response
 * @param token 
 */
public void removeASCookie(HttpServletRequest request, HttpServletResponse response, String token) {

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cCookie = cookies[i];
            if (SemlibConstants.COOCKIE_NAME.equalsIgnoreCase(cCookie.getName())) {
                String value = cCookie.getValue();
                if (value.equals(token)) {
                    removeASCookie(response, cCookie);
                }
                break;
            }
        }
    }
}

From source file:com.pureinfo.tgirls.sns.servlet.TestSNSEntryServlet.java

@Override
protected void doPost(HttpServletRequest _req, HttpServletResponse _resp) throws ServletException, IOException {
    System.out.println("==================test entry=====POST==============");

    try {/*from w w  w  .  ja  v a2s  .c  o m*/
        String userId = _req.getParameter("id");
        if (StringUtils.isEmpty(userId)) {
            userId = "1";
        }

        System.out.println("----user id----" + userId);

        IUserMgr mgr = (IUserMgr) ArkContentHelper.getContentMgrOf(User.class);
        User u = mgr.getUserByTaobaoId(userId);

        System.out.println("user:::;" + u);

        addCookie(u, _req, _resp);

        Cookie[] cookies = _req.getCookies();

        if (cookies == null) {
            System.out.println("=====cookie is null=======");
        } else {
            for (int i = 0; i < cookies.length; i++) {
                Cookie cookie = cookies[i];
                System.out.println("cookie[" + i + "]:[" + cookie.getName() + ":" + cookie.getValue() + "("
                        + cookie.getMaxAge() + ")]");
            }

        }

        int i = new Random().nextInt();
        Cookie c = new Cookie("topsessionid", "abc" + i);

        _resp.addCookie(c);

        System.out.println("========================");

        //            Cookie[] cs = _req.getCookies();
        //             for (int ii = 0; ii < cs.length; ii++) {
        //                 Cookie cc = cs[ii];
        //                 System.out.println("cookie[" + cc.getName() + "]:" + cc.getValue());
        //             }

        //_resp.sendRedirect(_req.getContextPath() + "/index.html");

        RequestDispatcher rd = _req.getRequestDispatcher("/index.html");
        rd.forward(_req, _resp);

        //_req.getSession().setAttribute(ArkHelper.ATTR_LOGIN_USER, u);
        // _resp.sendRedirect(_req.getContextPath());
        //            _req.getCookies()[0].
    } catch (PureException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

}

From source file:com.gradecak.alfresco.mvc.aop.AuthenticationAdvice.java

private String getTicket() {

    String ticket = "";
    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
            .getRequest();/*from   w  w  w.j  a  v a  2 s .c o m*/

    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cookie = cookies[i];
            if (cookie != null && "TICKET".equals(cookie.getName().toUpperCase())) {
                ticket = cookie.getValue();
            }
        }
    }

    @SuppressWarnings("unchecked")
    Map<String, Object> parameterMap = request.getParameterMap();

    if (parameterMap != null) {
        for (Object parameter : parameterMap.keySet()) {
            if (parameter != null && "TICKET".equals(((String) parameter).toUpperCase())) {
                ticket = (String) parameterMap.get(parameter);
            }
        }
    }

    // HttpSession session = request.getSession();
    // if (session != null) {
    // // TODO dgradecak: FIX THIS
    // User user = (User)session.getAttribute("_alfAuthTicket");
    // ticket = user.getTicket();
    // }

    return ticket;
}

From source file:eu.semlibproject.annotationserver.managers.CookiesManager.java

/**
 * Check if the current user is authenticated/authorized verifying
 * the annotation server cookie//from  w w w  . ja v  a2  s.  c om
 * 
 * @param httpRequest   the HTTP servlet request
 * @return              if the user is authorized/authenticaed, return the accessToken
 *                      otherwise return <code>null</code>
 */
public String isUserAuthorizedFromCookie(HttpServletRequest httpRequest, HttpServletResponse response) {

    boolean authorized = false;
    Cookie[] cookies = httpRequest.getCookies();
    if (cookies != null) {
        for (int i = 0; i < cookies.length; i++) {
            Cookie cCookie = cookies[i];
            if (SemlibConstants.COOCKIE_NAME.equalsIgnoreCase(cCookie.getName())) {
                String cookieValue = cCookie.getValue();
                authorized = TokenManager.getInstance().isTokenValid(cookieValue);
                if (authorized) {
                    return cookieValue;
                } else {
                    removeASCookie(response, cCookie);
                }
            }
        }
    }

    return null;
}