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:de.voolk.marbles.web.app.IdentSession.java

@Override
public boolean authenticate(String loginName, String password) {
    boolean auth = getAuthentificationService().authenticate(loginName, password);
    if (auth) {//  www.j a  v a 2s.co m
        this.login = loginName;
        String identKey = getUser().getIdentKey();
        Cookie cookie = new Cookie(IDENT_COOKIE, identKey);
        cookie.setMaxAge(COOKIE_MAX_AGE);
        ((WebResponse) RequestCycle.get().getResponse()).addCookie(cookie);
    }
    signIn(auth);
    return auth;
}

From source file:com.nkapps.billing.services.SearchServiceImpl.java

@Override
public String execSearchByDate(HttpServletRequest request, HttpServletResponse response) {
    Cookie sbdCookie = null;//from w ww  .  j ava 2s  . c  o  m

    String searchByDate = request.getParameter("searchByDate");
    if (searchByDate == null) {
        Cookie[] requestCookies = request.getCookies();
        for (Cookie c : requestCookies) {
            if (c.getName().equals("searchByDate")) {
                sbdCookie = c;
            }
        }
        if (sbdCookie != null) {
            searchByDate = sbdCookie.getValue();
        } else {
            searchByDate = new SimpleDateFormat("dd.MM.yyyy").format(Calendar.getInstance().getTime());
        }
    } else {
        sbdCookie = new Cookie("searchByDate", searchByDate);
        sbdCookie.setPath("/");
        response.addCookie(sbdCookie);
    }
    return searchByDate;
}

From source file:com.liusoft.dlog4j.util.RequestUtils.java

/**
 * COOKIE//from w ww  . ja  va  2 s  .c  o m
 * 
 * @param name
 * @param value
 * @param maxAge
 */
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String name,
        String value, int maxAge) {
    Cookie cookie = new Cookie(name, value);
    cookie.setMaxAge(maxAge);
    String serverName = request.getServerName();
    String domain = getDomainOfServerName(serverName);
    if (domain != null && domain.indexOf('.') != -1) {
        cookie.setDomain('.' + domain);
    }
    cookie.setPath("/");
    response.addCookie(cookie);
}

From source file:atd.backend.Login.java

/**
 * Vangt het POST request van de login.jsp en controlleerd deze met de
 * database//from w  ww. ja va  2  s.  c  o  m
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String username = req.getParameter("username").toLowerCase();

    try {
        Class.forName("org.apache.commons.codec.digest.DigestUtils");
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    String pass = org.apache.commons.codec.digest.DigestUtils.sha256Hex(req.getParameter("password"));
    RequestDispatcher rd = null;

    if (UsersDAO.authUser(username, pass)
            || (username.equals(adminUser)) && req.getParameter("password").equals(adminPwd)) {
        // Controlleer of het filter een redirect gezet heeft
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }

        req.getSession().setAttribute("username", UsersDAO.searchUser(username));
        resp.addCookie(new Cookie("username", username));
        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);
        LogDAO.setLog(req.getRemoteAddr(), currentTime, UsersDAO.searchUser(username), null);
        rd.forward(req, resp);
    } else if (KlantenDAO.authKlant(username, pass)) {
        if (req.getAttribute("redirect") == null || req.getAttribute("redirect").equals("")) {
            rd = req.getRequestDispatcher("/index.jsp");
        } else {
            rd = req.getRequestDispatcher((String) req.getAttribute("redirect"));
            req.removeAttribute("redirect");
        }
        req.getSession().setAttribute("username", KlantenDAO.searchKlant(username));
        System.out.println("klant setten");

        resp.addCookie(new Cookie("username", username));

        java.util.Date dt = new java.util.Date();
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String currentTime = sdf.format(dt);

        LogDAO.setLog(req.getRemoteAddr(), currentTime, null, KlantenDAO.searchKlant(username));
        rd.forward(req, resp);
    } else {
        rd = req.getRequestDispatcher("/login/login.jsp");
        req.setAttribute("error",
                "<div class=\"alert alert-danger\" role=\"alert\"> <span class=\"sr-only\">Error:</span> ongeldige inlog gegevens </div>");
        rd.forward(req, resp);
    }
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

private void addLanguageCookie(AppUser appUser, HttpServletResponse response) {
    Cookie cookie = new Cookie(Constants.NG_TRANSLATE_LANG_KEY, "%22" + appUser.getPreferredLanguage() + "%22");
    addCookie(response, cookie);/*w w w  . j  ava  2  s.  c  o m*/
}

From source file:com.edgenius.wiki.integration.client.Authentication.java

private void setCookie(String[] tokens, int maxAge, String targetWebContext, HttpServletRequest request,
        HttpServletResponse response) {// ww  w  .  j  a v a2s  . c  om
    String cookieValue = encodeCookie(tokens);
    Cookie cookie = new Cookie(WsContants.REMEMBER_ME_COOKIE_NAME, cookieValue);
    cookie.setMaxAge(maxAge);
    cookie.setPath(targetWebContext);
    response.addCookie(cookie);
}

From source file:fragment.web.AbstractManageResourceControllerTest.java

public void setSSOHandler() {
    mockCloudInstance = getMockCloudInstance();
    CloudConnector connector = mockCloudInstance.getCloudConnector();
    SsoHandler ssoHandler = mockCloudInstance.getSsoHandler();
    EasyMock.expect(ssoHandler.handleLogin(EasyMock.anyObject(User.class))).andAnswer(new IAnswer<SsoObject>() {

        @Override//from  w w w. j  a  va  2  s .c o  m
        public SsoObject answer() throws Exception {
            SsoObject ssoObject = new SsoObject();
            String name = ((User) EasyMock.getCurrentArguments()[0]).getName();
            ssoObject.setSsoString(name);
            List<Cookie> cookies = new ArrayList<Cookie>();
            Cookie c = new Cookie("Test", "Test");
            cookies.add(c);
            ssoObject.setCookies(cookies);
            return ssoObject;
        }

    }).anyTimes();
    EasyMock.replay(ssoHandler);
    EasyMock.replay(connector);
}

From source file:org.apache.oltu.oauth2.client.demo.controller.RedirectController.java

@RequestMapping(method = RequestMethod.GET)
public ModelAndView handleRedirect(@ModelAttribute("oauthParams") OAuthParams oauthParams,
        HttpServletRequest request, HttpServletResponse response) {

    try {/*  w w w  .  j  ava  2 s  .com*/

        // Get OAuth Info
        String clientId = Utils.findCookieValue(request, "clientId");
        String clientSecret = Utils.findCookieValue(request, "clientSecret");
        String authzEndpoint = Utils.findCookieValue(request, "authzEndpoint");
        String tokenEndpoint = Utils.findCookieValue(request, "tokenEndpoint");
        String redirectUri = Utils.findCookieValue(request, "redirectUri");
        String scope = Utils.findCookieValue(request, "scope");
        String state = Utils.findCookieValue(request, "state");

        oauthParams.setClientId(clientId);
        oauthParams.setClientSecret(clientSecret);
        oauthParams.setAuthzEndpoint(authzEndpoint);
        oauthParams.setTokenEndpoint(tokenEndpoint);
        oauthParams.setRedirectUri(redirectUri);
        oauthParams.setScope(Utils.isIssued(scope));
        oauthParams.setState(Utils.isIssued(state));

        // Create the response wrapper
        OAuthAuthzResponse oar = null;
        oar = OAuthAuthzResponse.oauthCodeAuthzResponse(request);

        // Get Authorization Code
        String code = oar.getCode();
        oauthParams.setAuthzCode(code);

        String app = Utils.findCookieValue(request, "app");
        response.addCookie(new Cookie("app", app));

        oauthParams.setApplication(app);

    } catch (OAuthProblemException e) {
        StringBuffer sb = new StringBuffer();
        sb.append("</br>");
        sb.append("Error code: ").append(e.getError()).append("</br>");
        sb.append("Error description: ").append(e.getDescription()).append("</br>");
        sb.append("Error uri: ").append(e.getUri()).append("</br>");
        sb.append("State: ").append(e.getState()).append("</br>");
        oauthParams.setErrorMessage(sb.toString());
        return new ModelAndView("get_authz");
    }

    return new ModelAndView("request_token");

}

From source file:com.sse.abtester.VariantSelectionFilter.java

/**
 * Attach variant selection and publishing to the request processing.
 *
 * @param request the request//from   w  w w  .  j av a2s . co m
 * @param response the response
 * @param chain the chain
 * @throws IOException Signals that an I/O exception has occurred.
 * @throws ServletException the servlet exception
 * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
 */
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest hReq = (HttpServletRequest) request;
    HttpServletResponse hRes = (HttpServletResponse) response;
    IVariant<VariantBean> theVariant = null;
    IVariationStrategy variationStrategy = null;

    HttpSession session = hReq.getSession();

    if (VM != null) {
        String vsKey = getCookieValue(hReq);
        if (vsKey != "") {
            // has a key, so is enrolled, just update
            // (and get the variant control)
            theVariant = VM.updateVariant(vsKey);
        } else {
            // give opportunity to enroll, map key into a Cookie
            theVariant = VM.enrollRequest(hReq);
            if (theVariant != null)
                vsKey = "" + theVariant.getKey();
            if (vsKey != null && vsKey != "") {
                Cookie cookie = new Cookie(VSKEY, vsKey);
                hRes.addCookie(cookie);
            }
        }
        if (theVariant != null && session != null) {
            variationStrategy = theVariant.getVariationStrategy();
            session.setAttribute(VSKEY, variationStrategy);
        }
    }
    if (variationStrategy == null) {
        variationStrategy = new Default();
        // chain.doFilter(hReq, hRes);
    }
    // attach the variation properties to the HttpSession

    variationStrategy.execute(filterConfig, chain, hReq, hRes);

    // we always offer up the response for pub,
    // even if it wasn't varied
    if (VM != null)
        VM.publishVariationResponse(hRes);
}

From source file:com.baidu.rigel.biplatform.ma.auth.resource.RandomValidateCode.java

/**
 * //from   ww w. ja  va 2 s  .  c  o  m
 * @param request
 * @param response
 * @param cacheManagerForResource 
 */
public static void getRandcode(HttpServletRequest request, HttpServletResponse response,
        CacheManagerForResource cacheManagerForResource) {
    // BufferedImageImage,Image????
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
    Graphics g = image.getGraphics(); // ImageGraphics,?????
    g.fillRect(0, 0, width, height);
    g.setFont(new Font("Times New Roman", Font.ROMAN_BASELINE, 18));
    g.setColor(getRandColor(110, 133));
    // 
    for (int i = 0; i <= lineSize; i++) {
        drowLine(g);
    }
    // ?
    String randomString = "";
    for (int i = 1; i <= stringNum; i++) {
        randomString = drowString(g, randomString, i);
    }
    String key = null;
    if (request.getCookies() != null) {
        for (Cookie tmp : request.getCookies()) {
            if (tmp.getName().equals(Constants.RANDOMCODEKEY)) {
                key = tmp.getName();
                cacheManagerForResource.removeFromCache(key);
                break;
            }
        }
    }
    if (StringUtils.isEmpty(key)) {
        key = String.valueOf(System.nanoTime());
    }
    cacheManagerForResource.setToCache(key, randomString);
    final Cookie cookie = new Cookie(Constants.RANDOMCODEKEY, key);
    cookie.setPath(Constants.COOKIE_PATH);
    response.addCookie(cookie);
    g.dispose();
    try {
        ImageIO.write(image, "JPEG", response.getOutputStream()); // ??
    } catch (Exception e) {
        LOG.info(e.getMessage());
    }
}