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:ch.unifr.pai.twice.widgets.mpproxy.server.SimpleHttpUrlConnectionServletFilter.java

/**
 * Apply the filter logic/* w  w  w  .j  a  va  2  s .com*/
 * 
 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
 */
@Override
public void doFilter(ServletRequest genericRequest, ServletResponse genericResponse, FilterChain chain)
        throws IOException, ServletException {
    if (genericRequest instanceof HttpServletRequest && genericResponse instanceof HttpServletResponse) {
        HttpServletRequest request = (HttpServletRequest) genericRequest;
        HttpServletResponse response = (HttpServletResponse) genericResponse;

        if (request.getSession().getAttribute(Constants.uuidCookie) == null) {
            request.getSession().setAttribute(Constants.uuidCookie, UUID.randomUUID().toString());
        }
        response.addCookie(new Cookie(Constants.uuidCookie,
                request.getSession().getAttribute(Constants.uuidCookie).toString()));
        String fullUrl = getFullRequestString(request);

        fullUrl.replace("gwt.codesvr=127.0.0.1:9997&", "");
        String servletPath = getServletPath(request);
        if (!servletPath.endsWith("/"))
            servletPath += "/";

        URLParser parser = new URLParser(fullUrl, servletPath);
        String url = parser.getFullProxyPath();

        // Prevent the managing resources to be filtered.
        if (request.getRequestURL().toString().startsWith(servletPath + Constants.nonFilterPrefix)
                || (url != null && url.equals(fullUrl))) {
            chain.doFilter(genericRequest, genericResponse);
            return;
        }

        // The read only screen
        if (request.getRequestURL().toString().contains("miceScreenShot")) {

            String result = ReadOnlyPresentation.getScreenshotForUUID(request.getParameter("uuid"));
            PrintWriter w = response.getWriter();
            if (result == null) {
                w.println("No screenshot available");
            } else {
                w.print(result);
            }
            w.flush();
            w.close();
            return;
        }
        // ProxyURLParser parser = new ProxyURLParser(fullUrl);
        // String url = parser.writeRequestUrl();
        if (url == null || url.isEmpty() || !url.startsWith("http")) {
            // We've lost context - lets try to re-establish it from
            // other
            // sources...
            String newProxyBase = null;

            // ... a referer is the best hint
            String referer = request.getHeader("Referer");
            if (referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    newProxyBase = refererParser.getProxyBasePath();
                }
            }
            // ... otherwise use the last used proxy (since it probably
            // is a
            // redirection we might have success with this)
            if (newProxyBase == null) {
                newProxyBase = (String) request.getSession().getAttribute("lastProxy");
            }

            // Now redirect the client to the new url
            if (newProxyBase != null) {
                url = newProxyBase + (url != null && !url.isEmpty() ? '/' + url : "/");
                response.sendRedirect(servletPath + url);

            } else {
                response.sendError(404);
            }
            return;

        }
        url = url.replace("\\|", "|");

        ProcessResult result = null;
        try {
            result = servlet.loadFromProxy(request, response, url, servletPath, parser.getProxyBasePath());

        } catch (UnknownHostException e) {
            // If we get a unknown host exception, we try it with the
            // referer
            String referer = request.getHeader("Referer");
            if (parser.getRefererRelative() != null && referer != null && !referer.isEmpty()) {
                URLParser refererParser = new URLParser(referer, Rewriter.getServletPath(referer));
                if (refererParser.getProxyBasePath() != null && !refererParser.getProxyBasePath().isEmpty()) {
                    String newUrl = refererParser.getProxyBasePath() + parser.getRefererRelative();
                    try {
                        result = servlet.loadFromProxy(request, response, newUrl, servletPath,
                                refererParser.getProxyBasePath());
                    } catch (UnknownHostException e1) {
                        result = null;
                        response.sendError(404);
                    }
                } else {
                    result = null;
                    response.sendError(404);
                }
            } else {
                result = null;
                response.sendError(404);
            }

        }

        if (result != null) {
            // If an error is returned, we don't need to process the
            // inputstream
            InputStream input;
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            OutputStream output = outputStream;
            if (result.isGzipped()) {
                output = new GZIPOutputStream(outputStream, 100000);
            }
            String s = URLRewriterServer.process(result.getContent(), fullUrl);
            s = URLRewriterServer.removeTopHref(s);
            if (request.getSession().getAttribute(Constants.miceManaged) == null
                    || !request.getSession().getAttribute(Constants.miceManaged).equals("true")) {
                s = s.replace("<head>",
                        "<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1, maximum-scale=1\">");
                // Pattern p = Pattern.compile("<body.*?>");
                // Matcher m = p.matcher(s);
                // StringBuffer sb = new StringBuffer();
                // while (m.find()) {
                // m.appendReplacement(
                // sb,
                // m.group()
                // + "<link href=\""
                // + servletPath
                // +
                // "miceproxy/navigation.css\" rel=\"stylesheet\" type=\"text/css\"/><div id=\"miceNavigation\"><input id=\"miceUrlBox\" type=\"text\" value=\""
                // + parser.getFullProxyPath()
                // +
                // "\"/></div><div id=\"contentWrapper\">");
                // }
                // s = m.appendTail(sb).toString();
                // s = s.replace("</body>",
                // "</div></body>");
            }

            // The page shall only be injected if it is a
            // html page and if it really has html content
            // (prevent e.g. blank.html to be injected)
            if (result.getContentType() != null && result.getContentType().contains("text/html")
                    && (s.contains("body") || s.contains("BODY")))
                s += "<script type=\"text/javascript\" language=\"javascript\" src=\"" + servletPath
                        + "miceproxy/miceproxy.nocache.js\"></script>";
            IOUtils.write(s, output, result.getCharset());
            output.flush();
            if (output instanceof GZIPOutputStream)
                ((GZIPOutputStream) output).finish();
            outputStream.writeTo(response.getOutputStream());
        }

    }
}

From source file:com.ibm.jaggr.core.impl.transport.AbstractHttpTransportTest.java

@Test
public void testGetFeaturesFromRequest() throws Exception {
    Map<String, Object> requestAttributes = new HashMap<String, Object>();
    Map<String, String[]> requestParameters = new HashMap<String, String[]>();
    AbstractHttpTransport transport = new TestHttpTransport();
    Cookie[] cookies = new Cookie[1];
    HttpServletRequest request = TestUtils.createMockRequest(null, requestAttributes, requestParameters,
            cookies, null);/*from   w  w w .  j  a  v  a 2  s . c  o m*/
    EasyMock.replay(request);
    assertNull(transport.getHasConditionsFromRequest(request));

    String hasConditions = "foo;!bar";
    requestParameters.put("has", new String[] { hasConditions });
    Features features = transport.getFeaturesFromRequest(request);
    assertEquals(2, features.featureNames().size());
    Assert.assertTrue(features.featureNames().contains("foo") && features.featureNames().contains("bar"));
    Assert.assertTrue(features.isFeature("foo"));
    Assert.assertFalse(features.isFeature("bar"));

    // Now try specifying the has conditions in the cookie
    requestParameters.clear();
    requestParameters.put("hashash", new String[] { "xxxx" }); // value not checked by server
    cookies[0] = new Cookie("has", hasConditions);
    features = transport.getFeaturesFromRequest(request);
    assertEquals(2, features.featureNames().size());
    Assert.assertTrue(features.featureNames().contains("foo") && features.featureNames().contains("bar"));
    Assert.assertTrue(features.isFeature("foo"));
    Assert.assertFalse(features.isFeature("bar"));

    // Make sure we handle null cookie values without throwing
    requestParameters.put("hashash", new String[] { "xxxx" }); // value not checked by server
    cookies[0] = new Cookie("has", null);
    features = transport.getFeaturesFromRequest(request);
    assertEquals(0, features.featureNames().size());

    // Try missing cookie
    cookies[0] = new Cookie("foo", "bar");
    features = transport.getFeaturesFromRequest(request);
    assertEquals(0, features.featureNames().size());
}

From source file:com.adito.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }/*from  w  w  w  . jav a2s .co m*/
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("adito.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:fr.mby.portal.coreimpl.session.MemorySessionManager.java

@Override
public void initPortalSession(final HttpServletRequest request, final HttpServletResponse response) {
    String portalSessionId = this.getPortalSessionId(request);

    if (portalSessionId == null) {
        // Can't find session Id => session wasn't initialized
        portalSessionId = this.genSessionId(request);

        this.initSessionBucket(portalSessionId);

        // Put sessionId in Cookie
        final Cookie portalSessionCookie = new Cookie(IPortal.PORTAL_SESSION_ID_COOKIE_NAME, portalSessionId);
        portalSessionCookie.setPath("/");
        response.addCookie(portalSessionCookie);

        // Put sessionId in current Http request
        request.setAttribute(IPortal.PORTAL_SESSION_ID_PARAM_NAME, portalSessionId);
    }// w  w w.  j  a  va2s  .  c  o  m

}

From source file:com.thoughtworks.go.http.mocks.MockHttpServletResponseAssert.java

public SELF hasCookie(String path, String name, String value, int maxAge, boolean secured, boolean httpOnly) {
    Cookie actualCookie = actual.getCookie(name);

    Cookie expectedCookie = new Cookie(name, value);
    expectedCookie.setDomain("");
    expectedCookie.setPath(path);/*w  ww. j ava  2s  .c  o m*/
    expectedCookie.setMaxAge(maxAge);
    expectedCookie.setSecure(secured);
    expectedCookie.setHttpOnly(httpOnly);

    if (!EqualsBuilder.reflectionEquals(expectedCookie, actualCookie)) {
        this.as("cookie");

        throw Failures.instance().failure(info,
                shouldBeEqual(ReflectionToStringBuilder.toString(actualCookie, ToStringStyle.MULTI_LINE_STYLE),
                        ReflectionToStringBuilder.toString(expectedCookie, ToStringStyle.MULTI_LINE_STYLE),
                        info.representation()));
    }
    return myself;
}

From source file:com.baifendian.swordfish.webserver.controller.LoginController.java

/**
 * @param name ??/*from   w ww  .  ja v  a2 s  .co m*/
 * @param email  email
 * @param password ?
 * @param request ?
 * @param response ?
 */
@RequestMapping(value = "", method = { RequestMethod.POST, RequestMethod.GET })
public UserSessionDto login(@RequestParam(value = "name", required = false) String name,
        @RequestParam(value = "email", required = false) String email,
        @RequestParam(value = "password") String password, HttpServletRequest request,
        HttpServletResponse response) {
    logger.info("Login, user name: {}, email: {}, password: {}", name, email, "******");

    // 
    if (StringUtils.isEmpty(name) && StringUtils.isEmpty(email)) {
        throw new ParameterException("name or email");
    }

    // 
    if (StringUtils.isNotEmpty(name) && StringUtils.isNotEmpty(email)) {
        throw new ParameterException("name or email");
    }

    //  ip ?
    String ip = HttpUtil.getClientIpAddress(request);
    if (StringUtils.isEmpty(ip)) {
        throw new ParameterException("ip");
    }

    // ?????
    User user = userService.queryUser(name, email, password);

    if (user == null) {
        throw new UnAuthorizedException("User password error");
    }

    //  session
    UserSessionDto data = sessionService.createSession(user, ip);

    if (data == null) {
        throw new UnAuthorizedException("Create session error");
    }

    response.setStatus(HttpStatus.SC_OK);
    response.addCookie(new Cookie("sessionId", data.getSessionId()));

    return data;
}

From source file:com.sslexplorer.language.actions.SelectLanguageAction.java

public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    String referer = DAVUtilities.encodePath(CoreUtil.getRequestReferer(request), false);
    if (referer == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "referer");
    }//from  w  w  w.j  a  v a 2  s  . c o m
    String localeCode = request.getParameter("locale");
    if (localeCode == null) {
        throw new CoreException(ErrorConstants.ERR_MISSING_REQUEST_PARAMETER, ErrorConstants.CATEGORY_NAME,
                "locale");
    }

    /* Tokenize the locale parameter so we only get the first line. This prevents
     * a header injection exploit as the (not validated) locale gets added as 
     * a cookie.
     */
    StringTokenizer t = new StringTokenizer(localeCode);
    String locale = t.nextToken();

    // Parse the locale code
    String country = "";
    String variant = "";
    String lang = locale;
    int idx = locale.indexOf("_");
    if (idx != -1) {
        country = lang.substring(idx + 1);
        lang = lang.substring(0, idx);
    }
    idx = country.indexOf('_');
    if (idx != -1) {
        variant = country.substring(idx + 1);
        country = country.substring(0, idx);
    }

    // Store the new locale in the session and set a persistant cookie
    Locale l = new Locale(lang, country, variant);
    request.getSession().setAttribute(Globals.LOCALE_KEY, l);
    Cookie cookie = new Cookie(SystemProperties.get("sslexplorer.cookie", "SSLX_SSESHID") + "_LANG",
            locale.toString());
    cookie.setMaxAge(60 * 60 * 24 * 7); // a week
    cookie.setPath("/");
    cookie.setSecure(true);
    response.addCookie(cookie);
    return referer == null ? mapping.findForward("home") : new ActionForward(referer, true);
}

From source file:org.jasig.cas.web.LogoutControllerTests.java

@Test
public void testLogoutCookie() throws Exception {
    MockHttpServletRequest request = new MockHttpServletRequest();
    Cookie cookie = new Cookie(COOKIE_TGC_ID, "test");
    request.setCookies(new Cookie[] { cookie });
    assertNotNull(this.logoutController.handleRequestInternal(request, new MockHttpServletResponse()));
}

From source file:com.mobileman.projecth.web.util.PersistentCookieHelper.java

public void removeUser(HttpServletRequest request, HttpServletResponse response) {
    //remove from request
    Cookie[] cookies = request.getCookies();
    if (cookies != null) {
        for (Cookie c : cookies) {
            if (COOKIE_NAME.equals(c.getName())) {
                c.setValue("deleted");
                break;
            }//w  w  w.  ja  va 2s . c  o  m
        }
    }

    //remove from browser
    Cookie cookie = new Cookie(COOKIE_NAME, "1");
    cookie.setPath(PATH);
    cookie.setMaxAge(0); //0 = remove cookie
    response.setContentType("text/html"); //else delete cookie not works
    response.addCookie(cookie);
}