public void testParseSimple() throws Exception { Header header = new Header("Set-Cookie","cookie-name=cookie-value"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, "127.0.0.1", 80, "/path/path", false, header); assertEquals("Found 1 cookie.",1,parsed.length); assertEquals("Name","cookie-name",parsed[0].getName()); assertEquals("Value","cookie-value",parsed[0].getValue()); assertTrue("Comment",null == parsed[0].getComment()); assertTrue("ExpiryDate",null == parsed[0].getExpiryDate()); //assertTrue("isToBeDiscarded",parsed[0].isToBeDiscarded()); assertTrue("isPersistent",!parsed[0].isPersistent()); assertEquals("Domain","127.0.0.1",parsed[0].getDomain()); assertEquals("Path","/path",parsed[0].getPath()); assertTrue("Secure",!parsed[0].getSecure()); assertEquals("Version",0,parsed[0].getVersion()); }
public void testKeepCloverHappy() throws Exception { CookieSpec cookiespec = new IgnoreCookiesSpec(); cookiespec.parseAttribute(null, null); cookiespec.parse("host", 80, "/", false, (String)null); cookiespec.parse("host", 80, "/", false, (Header)null); cookiespec.validate("host", 80, "/", false, (Cookie)null); cookiespec.match("host", 80, "/", false, (Cookie)null); cookiespec.match("host", 80, "/", false, (Cookie [])null); cookiespec.domainMatch(null, null); cookiespec.pathMatch(null, null); cookiespec.match("host", 80, "/", false, (Cookie [])null); cookiespec.formatCookie(null); cookiespec.formatCookies(null); cookiespec.formatCookieHeader((Cookie)null); cookiespec.formatCookieHeader((Cookie [])null); }
public void testSetCookieVersionMix() throws IOException { this.server.setHttpService(new SetCookieVersionMixService()); this.client.setState(new TestHttpState()); this.client.getParams().setCookiePolicy(CookiePolicy.RFC_2965); GetMethod httpget1 = new GetMethod("/test/"); try { this.client.executeMethod(httpget1); } finally { httpget1.releaseConnection(); } Cookie[] cookies = this.client.getState().getCookies(); assertNotNull(cookies); assertEquals(1, cookies.length); assertEquals("right", cookies[0].getValue()); assertTrue(cookies[0] instanceof Cookie2); }
/** * Parse RFC 2965 specific cookie attribute and update the corresponsing * {@link org.apache.commons.httpclient.Cookie} properties. * * @param attribute {@link org.apache.commons.httpclient.NameValuePair} cookie attribute from the * <tt>Set-Cookie2</tt> header. * @param cookie {@link org.apache.commons.httpclient.Cookie} to be updated * @throws MalformedCookieException if an exception occurs during parsing */ public void parseAttribute( final NameValuePair attribute, final Cookie cookie) throws MalformedCookieException { if (attribute == null) { throw new IllegalArgumentException("Attribute may not be null."); } if (attribute.getName() == null) { throw new IllegalArgumentException("Attribute Name may not be null."); } if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null."); } final String paramName = attribute.getName().toLowerCase(); final String paramValue = attribute.getValue(); CookieAttributeHandler handler = findAttribHandler(paramName); if (handler == null) { // ignore unknown attribute-value pairs if (LOG.isDebugEnabled()) LOG.debug("Unrecognized cookie attribute: " + attribute.toString()); } else { handler.parse(cookie, paramValue); } }
/** * Parse cookie path attribute. */ public void parse(final Cookie cookie, final String path) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (path == null) { throw new MalformedCookieException( "Missing value for path attribute"); } if (path.trim().equals("")) { throw new MalformedCookieException( "Blank value for path attribute"); } cookie.setPath(path); cookie.setPathAttributeSpecified(true); }
/** * Match cookie path attribute. The value for the Path attribute must be a * prefix of the request-URI (case-sensitive matching). */ public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } String path = origin.getPath(); if (cookie.getPath() == null) { LOG.warn("Invalid cookie state: path attribute is null."); return false; } if (path.trim().equals("")) { path = PATH_DELIM; } if (!pathMatch(path, cookie.getPath())) { return false; } return true; }
/** * Parse cookie domain attribute. */ public void parse(final Cookie cookie, String domain) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (domain == null) { throw new MalformedCookieException( "Missing value for domain attribute"); } if (domain.trim().equals("")) { throw new MalformedCookieException( "Blank value for domain attribute"); } domain = domain.toLowerCase(); if (!domain.startsWith(".")) { // Per RFC 2965 section 3.2.2 // "... If an explicitly specified value does not start with // a dot, the user agent supplies a leading dot ..." // That effectively implies that the domain attribute // MAY NOT be an IP address of a host name domain = "." + domain; } cookie.setDomain(domain); cookie.setDomainAttributeSpecified(true); }
/** * Parse cookie port attribute. */ public void parse(final Cookie cookie, final String portValue) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; if ((portValue == null) || (portValue.trim().equals(""))) { // If the Port attribute is present but has no value, the // cookie can only be sent to the request-port. // Since the default port list contains only request-port, we don't // need to do anything here. cookie2.setPortAttributeBlank(true); } else { int[] ports = parsePortAttribute(portValue); cookie2.setPorts(ports); } cookie2.setPortAttributeSpecified(true); } }
/** * Validate cookie port attribute. If the Port attribute was specified * in header, the request port must be in cookie's port list. */ public void validate(final Cookie cookie, final CookieOrigin origin) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int port = origin.getPort(); if (cookie2.isPortAttributeSpecified()) { if (!portMatch(port, cookie2.getPorts())) { throw new MalformedCookieException( "Port attribute violates RFC 2965: " + "Request port not found in cookie's port list."); } } } }
/** * Match cookie port attribute. If the Port attribute is not specified * in header, the cookie can be sent to any port. Otherwise, the request port * must be in the cookie's port list. */ public boolean match(final Cookie cookie, final CookieOrigin origin) { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (origin == null) { throw new IllegalArgumentException("Cookie origin may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; int port = origin.getPort(); if (cookie2.isPortAttributeSpecified()) { if (cookie2.getPorts() == null) { LOG.warn("Invalid cookie state: port not specified"); return false; } if (!portMatch(port, cookie2.getPorts())) { return false; } } return true; } else { return false; } }
/** * Parse cookie version attribute. */ public void parse(final Cookie cookie, final String value) throws MalformedCookieException { if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { Cookie2 cookie2 = (Cookie2) cookie; if (value == null) { throw new MalformedCookieException( "Missing value for version attribute"); } int version = -1; try { version = Integer.parseInt(value); } catch (NumberFormatException e) { version = -1; } if (version < 0) { throw new MalformedCookieException("Invalid cookie version."); } cookie2.setVersion(version); cookie2.setVersionAttributeSpecified(true); } }
/** * Return an array of {@link Cookie}s that should be submitted with a * request with given attributes, <tt>false</tt> otherwise. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (currently * ignored) * @param path the path to which the request is being submitted * @param secure <tt>true</tt> if the request is using a secure protocol * @param cookies an array of <tt>Cookie</tt>s to be matched * @return an array of <tt>Cookie</tt>s matching the criterium */ public Cookie[] match(String host, int port, String path, boolean secure, final Cookie cookies[]) { LOG.trace("enter CookieSpecBase.match(" + "String, int, String, boolean, Cookie[])"); if (cookies == null) { return null; } List matching = new LinkedList(); for (int i = 0; i < cookies.length; i++) { if (match(host, port, path, secure, cookies[i])) { addInPathOrder(matching, cookies[i]); } } return (Cookie[]) matching.toArray(new Cookie[matching.size()]); }
/** * Create a <tt>"Cookie"</tt> header value containing all {@link Cookie}s in * <i>cookies</i> suitable for sending in a <tt>"Cookie"</tt> header * @param cookies an array of {@link Cookie}s to be formatted * @return a string suitable for sending in a Cookie header. * @throws IllegalArgumentException if an input parameter is illegal */ public String formatCookies(Cookie[] cookies) throws IllegalArgumentException { LOG.trace("enter CookieSpecBase.formatCookies(Cookie[])"); if (cookies == null) { throw new IllegalArgumentException("Cookie array may not be null"); } if (cookies.length == 0) { throw new IllegalArgumentException("Cookie array may not be empty"); } StringBuffer buffer = new StringBuffer(); for (int i = 0; i < cookies.length; i++) { if (i > 0) { buffer.append("; "); } buffer.append(formatCookie(cookies[i])); } return buffer.toString(); }
/** * Return a string suitable for sending in a <tt>"Cookie"</tt> header * as defined in RFC 2109 for backward compatibility with cookie version 0 * @param buffer The string buffer to use for output * @param cookie The {@link Cookie} to be formatted as string * @param version The version to use. */ private void formatCookieAsVer(final StringBuffer buffer, final Cookie cookie, int version) { String value = cookie.getValue(); if (value == null) { value = ""; } formatParam(buffer, new NameValuePair(cookie.getName(), value), version); if ((cookie.getPath() != null) && cookie.isPathAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Path", cookie.getPath()), version); } if ((cookie.getDomain() != null) && cookie.isDomainAttributeSpecified()) { buffer.append("; "); formatParam(buffer, new NameValuePair("$Domain", cookie.getDomain()), version); } }
/** * Tests RFC 2965 compliant cookies formatting. */ public void testRFC2965CookiesFormatting() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Cookie2 cookie1 = new Cookie2(".domain.com", "name1", "value1", "/", null, false, new int[] {80,8080}); cookie1.setVersion(1); // domain, path, port specified cookie1.setDomainAttributeSpecified(true); cookie1.setPathAttributeSpecified(true); cookie1.setPortAttributeSpecified(true); Cookie2 cookie2 = new Cookie2(".domain.com", "name2", null, "/", null, false, null); cookie2.setVersion(1); // value null, domain, path, port specified cookie2.setDomainAttributeSpecified(true); cookie2.setPathAttributeSpecified(true); cookie2.setPortAttributeSpecified(false); Cookie[] cookies = new Cookie[] {cookie1, cookie2}; assertEquals("$Version=\"1\"; name1=\"value1\"; $Domain=\".domain.com\"; $Path=\"/\"; $Port=\"80,8080\"; " + "name2=\"\"; $Domain=\".domain.com\"; $Path=\"/\"", cookiespec.formatCookies(cookies)); }
public void testParseMultipleSamePaths() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Version=1;Path=/commons,name1=value2;Version=1;Path=/commons"); CookieSpec cookiespec = new CookieSpecBase(); Cookie[] parsed = cookieParse(cookiespec, ".apache.org", 80, "/commons/httpclient", true, header); HttpState state = new HttpState(); state.addCookies(parsed); Cookie[] cookies = state.getCookies(); assertEquals("Found 1 cookies.",1,cookies.length); assertEquals("Name","name1",cookies[0].getName()); assertEquals("Value","value2",cookies[0].getValue()); }
private Cookie[] sort(Cookie[] cookies) { Cookie[] result = new Cookie[cookies.length]; System.arraycopy(cookies, 0, result, 0, cookies.length); Arrays.sort(result, COOKIE_NAME_COMPARATOR); return result; }
public void testValidateNullHost() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.validate(null, 80, "/", false, cookie); fail("IllegalArgumentException must have been thrown"); } catch (IllegalArgumentException expected) { } }
public void testMatchedCookiesOrder() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie[] cookies = { new Cookie("host", "nomatch", "value", "/noway", null, false), new Cookie("host", "name2", "value", "/foobar/yada", null, false), new Cookie("host", "name3", "value", "/foobar", null, false), new Cookie("host", "name1", "value", "/foobar/yada/yada", null, false)}; Cookie[] matched = cookiespec.match("host", 80, "/foobar/yada/yada", false, cookies); assertNotNull(matched); assertEquals(3, matched.length); assertEquals("name1", matched[0].getName()); assertEquals("name2", matched[1].getName()); assertEquals("name3", matched[2].getName()); }
public void testParseAbsPath() throws Exception { Header header = new Header("Set-Cookie", "name1=value1;Path=/path/"); CookieSpec cookiespec = new NetscapeDraftSpec(); Cookie[] parsed = cookieParse(cookiespec, "host", 80, "/path/", true, header); assertEquals("Found 1 cookies.",1,parsed.length); assertEquals("Name","name1",parsed[0].getName()); assertEquals("Value","value1",parsed[0].getValue()); assertEquals("Domain","host",parsed[0].getDomain()); assertEquals("Path","/path/",parsed[0].getPath()); }
/** * test parsing cookie name/value. */ public void testParseNameValue() throws Exception { CookieSpec cookiespec = new RFC2965Spec(); Header header = new Header("Set-Cookie2", "name=value;Version=1;"); Cookie[] parsed = cookiespec.parse("www.domain.com", 80, "/", false, header); assertNotNull(parsed); assertEquals(1, parsed.length); Cookie2 cookie = (Cookie2) parsed[0]; assertEquals("name", cookie.getName()); assertEquals("value", cookie.getValue()); }
private Cookie createCookieFromToken(String token, String path, String domain) { Cookie cookie = new Cookie(); cookie.setPath(path); cookie.setDomain(domain); cookie.setName(token.substring(0, token.indexOf('='))); cookie.setValue(token.substring(token.indexOf('=') + 1)); return cookie; }
public void testCookieNullDomainNullPathFormatting() { Cookie cookie = new Cookie(null, "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new RFC2109Spec(); String s = cookiespec.formatCookie(cookie); assertEquals("$Version=0; name=; $Path=/", s); cookie.setDomainAttributeSpecified(false); cookie.setPathAttributeSpecified(false); s = cookiespec.formatCookie(cookie); assertEquals("$Version=0; name=", s); }
/** * Domain does not start with a dot */ public void testParseWithIllegalDomain1() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=a.b.com; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "www.a.b.com", 80, "/", false, header); fail("MalformedCookieException should have been thrown"); } catch (MalformedCookieException e) { // expected } }
public void testEquality3() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", null, null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); }
public Vector<String> getCookieStrings() { // Use the HandleCookie Property of the transaction to return or not the cookies. // // We noticed a Bug in tomcat when too much cookies where set in the response to the client. This causes a // IndexOutOfBoundException: 4096 in coyote. // To overcome this situation, now you can configure HandleCookies to false in the transaction to prevent cookies to be reflected // to the client. if (requestedObject instanceof AbstractHttpTransaction ) { if (!((AbstractHttpTransaction)requestedObject).isHandleCookie()) return new Vector<String>(); } Vector<String> cookies = new Vector<String>(); if (httpState != null) { Cookie[] httpCookies = httpState.getCookies(); int len = httpCookies.length; Cookie cookie = null; String sCookie; DateFormat df = new SimpleDateFormat("EEE, dd-MMM-yyyy HH:mm:ss z", Locale.US); df.setTimeZone(TimeZone.getTimeZone("GMT")); for (int i=0; i<len; i++) { cookie = httpCookies[i]; sCookie = cookie.getName() + "=" + cookie.getValue() + ";"; sCookie += (cookie.getExpiryDate() != null) ? "expires=" + df.format(cookie.getExpiryDate())+ ";":""; sCookie += "path=" + cookie.getPath() + ";"; sCookie += "domain=" + cookie.getDomain() + ";"; sCookie += cookie.getSecure() ? "secure": ""; cookies.add(sCookie); } } return cookies; }
public void testEquality1() { Cookie cookie1 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Cookie cookie2 = new Cookie(".whatever.com", "name1", "value", "/a", null, false); Comparator comparator = new CookiePathComparator(); assertTrue(comparator.compare(cookie1, cookie2) == 0); assertTrue(comparator.compare(cookie2, cookie1) == 0); }
private void removeTransactionContext() { if (Engine.isEngineMode()) { if (parent instanceof ParallelStep) { if (sequence.useSameJSessionForSteps()) { // TODO?? } else { if (httpState != null) { Cookie[] httpCookies = httpState.getCookies(); int len = httpCookies.length; Cookie cookie = null; for (int i = 0; i < len; i++) { cookie = httpCookies[i]; if (cookie.getName().equalsIgnoreCase("JSESSIONID")) { Engine.logBeans .debug("Executing deletion of transaction's context of TranscationStep \"" + getName() + "\""); Engine.theApp.contextManager.removeAll(cookie.getValue()); Engine.logBeans .debug("Deletion of transaction's context of TranscationStep \"" + getName() + "\" done"); break; } } } } } } }
@Override public boolean execute(Context javascriptContext, Scriptable scope) throws EngineException { if (isEnabled()) { if (super.execute(javascriptContext, scope)) { if (this.getConnector().handleCookie) { HttpState httpState = this.getParentTransaction().context.httpState; if (httpState != null) { Cookie[] cookies = httpState.getCookies(); String code = variable + "="; boolean array = separator.length() == 0; if (cookies.length == 0) { code += array ? "[]" : "''"; } else { String sep = array ? "\",\"" : separator; code += (array ? "[\"" : "\"") + CookiesUtils.formatCookie(cookies[0]).replace("\"", "\\\""); for (int i = 1; i < cookies.length; i++) { code += sep + CookiesUtils.formatCookie(cookies[i]).replace("\"", "\\\""); } code += (array ? "\"]" : "\""); } evaluate(javascriptContext, scope, code, "CookiesGet", true); } else { Engine.logBeans.debug("(CookiesGetStatement) No httpState for cookies"); } } return true; } } return false; }
public void testInvalidSecondDomainLevelCookieMatch1() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); assertFalse(cookiespec.match("antisourceforge.net", 80, "/", false, cookie)); }
public Cookie[] getCookies() { Cookie[] cookies = new Cookie[]{}; if ((httpState != null) && handleCookie) { cookies = httpState.getCookies(); } return cookies; }
public String get(String url, Cookie[] cookies) throws IOException { // clearCookies(); GetMethod g = new GetMethod(url); g.setFollowRedirects(false); hc.getState().addCookies(cookies); hc.executeMethod(g); return g.getResponseBodyAsString(); }
public synchronized void addCookie(Cookie cookie) { if (cookie != null) { if ("localhost.local".equals(cookie.getDomain())) { cookie.setDomain("localhost"); } super.addCookie(cookie); } }
/** * Tests if invalid second domain level cookie gets accepted in the * browser compatibility mode. */ public void testSecondDomainLevelCookie() throws Exception { Cookie cookie = new Cookie(".sourceforge.net", "name", null, "/", null, false); cookie.setDomainAttributeSpecified(true); cookie.setPathAttributeSpecified(true); CookieSpec cookiespec = new CookieSpecBase(); cookiespec.validate("sourceforge.net", 80, "/", false, cookie); }
public void testParseWithBlankHost() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=127.0.0.1; path=/; secure"); CookieSpec cookiespec = new CookieSpecBase(); try { Cookie[] parsed = cookieParse(cookiespec, " ", 80, "/", false, header); fail("IllegalArgumentException should have been thrown"); } catch (IllegalArgumentException e) { // expected } }
public void testParseAttributeBlankDomain() throws Exception { CookieSpec cookiespec = new CookieSpecBase(); Cookie cookie = new Cookie(); try { cookiespec.parseAttribute(new NameValuePair("domain", " "), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } }
/** * Return <tt>true</tt> if the cookie should be submitted with a request * with given attributes, <tt>false</tt> otherwise. * @param host the host to which the request is being submitted * @param port the port to which the request is being submitted (ignored) * @param path the path to which the request is being submitted * @param secure <tt>true</tt> if the request is using a secure connection * @return true if the cookie matches the criterium */ public boolean match(String host, int port, String path, boolean secure, final Cookie cookie) { LOG.trace("enter RFC2965.match(" + "String, int, String, boolean, Cookie"); if (cookie == null) { throw new IllegalArgumentException("Cookie may not be null"); } if (cookie instanceof Cookie2) { // check if cookie has expired if (cookie.isPersistent() && cookie.isExpired()) { return false; } CookieOrigin origin = new CookieOrigin(getEffectiveHost(host), port, path, secure); for (Iterator i = getAttribHandlerIterator(); i.hasNext(); ) { CookieAttributeHandler handler = (CookieAttributeHandler) i.next(); if (!handler.match(cookie, origin)) { return false; } } return true; } else { // old-style cookies are matched according to the old rules return this.rfc2109.match(host, port, path, secure, cookie); } }
public void testParseWithInvalidHeader1() throws Exception { CookieSpec cookiespec = new NetscapeDraftSpec(); try { Cookie[] parsed = cookiespec.parse("127.0.0.1", 80, "/foo", false, (String)null); fail("IllegalArgumentException should have been thrown."); } catch (IllegalArgumentException e) { // expected } }
/** * Domain must have alt least one embedded dot */ public void testParseWithIllegalDomain3() throws Exception { Header header = new Header("Set-Cookie", "cookie-name=cookie-value; domain=.com.; version=1"); CookieSpec cookiespec = new RFC2109Spec(); try { Cookie[] parsed = cookieParse(cookiespec, "b.com", 80, "/", false, header); fail("HttpException exception should have been thrown"); } catch (MalformedCookieException e) { // expected } }
public void testParseAttributeNullPath() throws Exception { CookieSpec cookiespec = new RFC2109Spec(); try { Cookie cookie = new Cookie(); cookiespec.parseAttribute(new NameValuePair("path", null), cookie); fail("MalformedCookieException must have been thrown"); } catch (MalformedCookieException expected) { } }