CookieHeaderSerializer implements Serializer<Cookie> { @Override public String serialize(final Cookie cookie) { StringBuilder sb = new StringBuilder(); sb.append(cookie.getName()) .append(EQUALS) .append(StringUtilities.urlEncode(cookie.getValue())); if (cookie.getMaxAge() != -1) { sb.append(SEPARATOR) .append("Expires") .append(EQUALS) .append(getExpires(cookie.getMaxAge())); } if (cookie.getPath() != null) { sb.append(SEPARATOR) .append("Path") .append(EQUALS) .append(cookie.getPath()); } if (cookie.getDomain() != null) { sb.append(SEPARATOR) .append("Domain") .append(EQUALS) .append(cookie.getDomain()); } if (cookie.getComment() != null) { sb.append(SEPARATOR) .append("Comment") .append(EQUALS) .append(cookie.getComment()); } if (cookie.isHttpOnly()) { sb.append(SEPARATOR) .append("HttpOnly"); } if (cookie.isSecure()) { sb.append(SEPARATOR) .append("Secure"); } return sb.toString(); } CookieHeaderSerializer(final DateProvider dateProvider); @Override String serialize(final Cookie cookie);  }
@Test public void shouldSerializeCookieWithUrlEncode() { String value = "= &"; Cookie cookie = new Cookie("name", value); String serializedCookie = cookieHeaderSerializer.serialize(cookie); assertThat(serializedCookie, is("name=" + StringUtilities.urlEncode(value))); }
@Test public void shouldSerializeCookieWithNoAttributes() { Cookie cookie = new Cookie("name", "value"); String serializedCookie = cookieHeaderSerializer.serialize(cookie); assertThat(serializedCookie, is("name=value")); }
@Test public void shouldSerializeExpiresBasedOnMaxAge() { int maxAgeSeconds = 35; Cookie cookie = new Cookie("name", "value"); cookie.setMaxAge(maxAgeSeconds); String serializedCookie = cookieHeaderSerializer.serialize(cookie); Date date = new Date(System.currentTimeMillis() + Long.valueOf(maxAgeSeconds) * 1000L); String expiresValue = DateUtilities.dateFormat(date); assertThat(getExpiresValue(serializedCookie), is(expiresValue)); }
@Test public void shouldSerializeCookieWithAllAttributes() { Cookie cookie = new Cookie("name", "value"); cookie.setDomain("example.com"); cookie.setMaxAge(20); cookie.setSecure(true); cookie.setHttpOnly(true); cookie.setPath("/somepath"); cookie.setComment("Some Comment"); String serializedCookie = cookieHeaderSerializer.serialize(cookie); String[] serializedCookieParts = getCookieParts(serializedCookie); assertThat(serializedCookie, startsWith("name=value")); assertThat(serializedCookie, containsString("Expires")); assertThat(getExpiresValue(serializedCookie), endsWith("GMT")); assertThat(serializedCookieParts, hasItemInArray("Domain=example.com")); assertThat(serializedCookieParts, hasItemInArray("Path=/somepath")); assertThat(serializedCookieParts, hasItemInArray("HttpOnly")); assertThat(serializedCookieParts, hasItemInArray("Secure")); assertThat(serializedCookieParts, hasItemInArray("Comment=Some Comment")); }