incubator-awf-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From elecha...@apache.org
Subject svn commit: r1152427 - in /incubator/deft/sandbox/src: main/java/org/deftserver/example/ main/java/org/deftserver/util/ main/java/org/deftserver/web/http/ test/java/org/deftserver/util/ test/java/org/deftserver/web/http/
Date Sat, 30 Jul 2011 05:16:30 GMT
Author: elecharny
Date: Sat Jul 30 05:16:26 2011
New Revision: 1152427

URL: http://svn.apache.org/viewvc?rev=1152427&view=rev
Log:
applied patch for DEFT-52

Added:
    incubator/deft/sandbox/src/main/java/org/deftserver/example/DeftCookieExample.java
    incubator/deft/sandbox/src/main/java/org/deftserver/util/CookieUtil.java
Modified:
    incubator/deft/sandbox/src/main/java/org/deftserver/util/DateUtil.java
    incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpRequest.java
    incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpResponse.java
    incubator/deft/sandbox/src/test/java/org/deftserver/util/DateUtilTest.java
    incubator/deft/sandbox/src/test/java/org/deftserver/web/http/HttpRequestTest.java

Added: incubator/deft/sandbox/src/main/java/org/deftserver/example/DeftCookieExample.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/main/java/org/deftserver/example/DeftCookieExample.java?rev=1152427&view=auto
==============================================================================
--- incubator/deft/sandbox/src/main/java/org/deftserver/example/DeftCookieExample.java (added)
+++ incubator/deft/sandbox/src/main/java/org/deftserver/example/DeftCookieExample.java Sat
Jul 30 05:16:26 2011
@@ -0,0 +1,72 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+package org.deftserver.example;
+
+import java.util.Map;
+import java.util.UUID;
+
+import org.deftserver.io.IOLoop;
+import org.deftserver.web.Application;
+import org.deftserver.web.HttpServer;
+import org.deftserver.web.handler.RequestHandler;
+import org.deftserver.web.http.HttpRequest;
+import org.deftserver.web.http.HttpResponse;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.google.common.collect.Maps;
+
+/**
+ * Demonstration of cookie-related functionality.
+ */
+public class DeftCookieExample {
+
+    private final static Logger logger = LoggerFactory.getLogger(DeftServerExample.class);
+    private final static int PORT = 8080;
+
+    private static class ExampleCookieRequestHandler extends RequestHandler {
+
+        @Override
+        public void get(HttpRequest request, HttpResponse response) {
+            String sessCookie = request.getCookie("deftssid");
+            if (sessCookie != null) {
+                response.write("Cookie deftssid: " + sessCookie);
+                response.clearCookie("deftssid");
+            } else {
+                String ssid = UUID.randomUUID().toString();
+                response.setCookie("deftssid", ssid, 1800);
+                response.write("Set cookie deftssid: " + ssid);
+            }
+        }
+    }
+
+    public static void main(String[] args) {
+        Map<String, RequestHandler> handlers = Maps.newHashMap();
+        handlers.put("/", new ExampleCookieRequestHandler());
+
+        Application application = new Application(handlers);
+
+        logger.debug("Starting up server on port: " + PORT);
+        HttpServer server = new HttpServer(application);
+        server.listen(PORT);
+        IOLoop.INSTANCE.start();
+    }
+
+}

Added: incubator/deft/sandbox/src/main/java/org/deftserver/util/CookieUtil.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/main/java/org/deftserver/util/CookieUtil.java?rev=1152427&view=auto
==============================================================================
--- incubator/deft/sandbox/src/main/java/org/deftserver/util/CookieUtil.java (added)
+++ incubator/deft/sandbox/src/main/java/org/deftserver/util/CookieUtil.java Sat Jul 30 05:16:26
2011
@@ -0,0 +1,38 @@
+/*
+ *  Licensed to the Apache Software Foundation (ASF) under one
+ *  or more contributor license agreements.  See the NOTICE file
+ *  distributed with this work for additional information
+ *  regarding copyright ownership.  The ASF licenses this file
+ *  to you under the Apache License, Version 2.0 (the
+ *  "License"); you may not use this file except in compliance
+ *  with the License.  You may obtain a copy of the License at
+ *  
+ *    http://www.apache.org/licenses/LICENSE-2.0
+ *  
+ *  Unless required by applicable law or agreed to in writing,
+ *  software distributed under the License is distributed on an
+ *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ *  KIND, either express or implied.  See the License for the
+ *  specific language governing permissions and limitations
+ *  under the License. 
+ *  
+ */
+package org.deftserver.util;
+
+
+/**
+ * Utility type providing cookie-related functionality.
+ */
+public class CookieUtil {
+
+	/**
+	 * Utility method to calculate the expiration date of a cookie, starting with a time of
validity in seconds.
+	 * 
+	 * @param seconds time of validity 
+	 * @return expiry date 
+	 */
+	public static String maxAgeToExpires(Long seconds) {
+		return DateUtil.parseToRFC1123(System.currentTimeMillis() + (seconds * 1000));
+	}
+	
+}

Modified: incubator/deft/sandbox/src/main/java/org/deftserver/util/DateUtil.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/main/java/org/deftserver/util/DateUtil.java?rev=1152427&r1=1152426&r2=1152427&view=diff
==============================================================================
--- incubator/deft/sandbox/src/main/java/org/deftserver/util/DateUtil.java (original)
+++ incubator/deft/sandbox/src/main/java/org/deftserver/util/DateUtil.java Sat Jul 30 05:16:26
2011
@@ -95,9 +95,20 @@ public class DateUtil {
 	 */
 	public static String parseToRFC1123(final long dateValue) {
 
-		final Calendar calendar = Calendar.getInstance();
+		final Calendar calendar = Calendar.getInstance();		
 		calendar.setTimeInMillis(dateValue);
 
 		return DateUtil.RFC_1123_FORMAT.format(calendar.getTime());
 	}
+	
+	/**
+	 * Convert a given <code>Date</code> object to a <code>RFC 1123</code>
formatted <code>String</code>.
+	 * 
+	 * @param date the <code>Date</code> object to convert
+	 * @return a <code>String</code> representation of the date.
+	 */
+	public static String getDateAsString(Date date) {
+		return RFC_1123_FORMAT.format(date);
+	}
+	
 }
\ No newline at end of file

Modified: incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpRequest.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpRequest.java?rev=1152427&r1=1152426&r2=1152427&view=diff
==============================================================================
--- incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpRequest.java (original)
+++ incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpRequest.java Sat Jul
30 05:16:26 2011
@@ -32,7 +32,9 @@ import org.deftserver.util.ArrayUtil;
 import org.deftserver.web.HttpVerb;
 
 import com.google.common.base.Charsets;
+import com.google.common.base.Strings;
 import com.google.common.collect.ImmutableMultimap;
+import com.google.common.collect.Maps;
 
 public class HttpRequest {
 	
@@ -50,6 +52,7 @@ public class HttpRequest {
 	private InetAddress serverHost;
 	private int remotePort;
 	private int serverPort;
+	private Map<String, String> cookies = null;
 
 	/** Regex to parse HttpRequest Request Line */
 	public static final Pattern REQUEST_LINE_PATTERN = Pattern.compile(" ") ;
@@ -65,8 +68,8 @@ public class HttpRequest {
 	public static final Pattern HEADERS_BODY_PATTERN = Pattern.compile("\\r\\n");
 	/** Regex to parse header name and value */
 	public static final Pattern HEADER_VALUE_PATTERN = Pattern.compile(": ");
-	
-	
+	/** Regex to split cookie header following RFC6265 Section 5.4 */
+	public static final Pattern COOKIE_SEPARATOR_PATTERN = Pattern.compile(";");	
 	
 	/**
 	 * Creates a new HttpRequest 
@@ -224,6 +227,33 @@ public class HttpRequest {
 	protected void setServerPort(int port) {
 		serverPort = port;
 	}
+	
+	/**
+	 * Returns a map with all cookies contained in the request. Cookies are represented as strings,

+	 * and are parsed at the first invocation of this method
+	 * 
+	 * @return a map containing all cookies of request
+	 */
+	public Map<String, String> getCookies() {
+		if (cookies == null) {
+			parseCookies();
+		}
+		return Collections.unmodifiableMap(cookies);
+	}
+	
+	/**
+	 * Returns a given cookie. Cookies are represented as strings, 
+	 * and are parsed at the first invocation of this method
+	 * 
+	 * @param name the name of cookie
+	 * @return the corresponding cookie, or null if the cookie does not exist
+	 */
+	public String getCookie(String name) {
+		if (cookies == null) {
+			parseCookies();
+		}
+		return cookies.get(name);
+	}
 
 	/**
 	 * Returns a collection of all values associated with the provided parameter.
@@ -279,6 +309,20 @@ public class HttpRequest {
 		return builder.build();
 	}
 	
+	/**
+	* Parse the cookie's http header (RFC6265 Section 5.4)
+	*/
+	private void parseCookies() {
+		String cookiesHeader = Strings.nullToEmpty(getHeader("Cookie")).trim();
+		cookies = Maps.newHashMap();
+		if (!cookiesHeader.equals("")) {
+			String[] cookiesStrings = COOKIE_SEPARATOR_PATTERN.split(cookiesHeader);
+			for (String cookieString : cookiesStrings) {
+				String[] cookie = KEY_VALUE_PATTERN.split(cookieString, 2);
+				cookies.put(cookie[0].trim(), cookie[1].trim());
+			}
+		}
+	}	
 	
 	private void initKeepAlive() {
 		String connection = getHeader("Connection");

Modified: incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpResponse.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpResponse.java?rev=1152427&r1=1152426&r2=1152427&view=diff
==============================================================================
--- incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpResponse.java (original)
+++ incubator/deft/sandbox/src/main/java/org/deftserver/web/http/HttpResponse.java Sat Jul
30 05:16:26 2011
@@ -30,17 +30,22 @@ import java.nio.channels.FileChannel;
 import java.nio.channels.FileChannel.MapMode;
 import java.nio.channels.SelectionKey;
 import java.nio.channels.SocketChannel;
+import java.util.Date;
 import java.util.HashMap;
 import java.util.Map;
 
 import org.deftserver.io.buffer.DynamicByteBuffer;
 import org.deftserver.util.Closeables;
+import org.deftserver.util.CookieUtil;
 import org.deftserver.util.DateUtil;
 import org.deftserver.util.HttpUtil;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import com.google.common.base.CharMatcher;
 import com.google.common.base.Charsets;
+import com.google.common.base.Strings;
+import com.google.common.collect.Maps;
 
 public class HttpResponse {
 	
@@ -52,6 +57,7 @@ public class HttpResponse {
 	private int statusCode = 200;	// default response status code
 	
 	private final Map<String, String> headers = new HashMap<String, String>();
+	private final Map<String, String> cookies = Maps.newHashMap();
 	private boolean headersCreated = false;
 	private DynamicByteBuffer responseData = DynamicByteBuffer.allocate(WRITE_BUFFER_SIZE);
 	
@@ -70,6 +76,143 @@ public class HttpResponse {
 	public void setHeader(String header, String value) {
 		headers.put(header, value);
 	}
+	
+	/**
+	 * Add a cookie to response.
+	 * 
+	 * @see #setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value) {
+		setCookie(name, value, -1, null, null, false, false);
+	}
+	
+	/**
+	 * Add a cookie to response.
+	 * 
+	 * @see #setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param expiration expiration of cookie in seconds
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, long expiration) {
+		setCookie(name, value, expiration, null, null, false, false);
+	}
+	
+	/**
+	 * Add a cookie to response.
+	 * 
+	 * @see #setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param domain cookie domain
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, String domain) {
+		setCookie(name, value, -1, domain, null, false, false);
+	}
+	
+	/**
+	 * Add a cookie to response.
+	 * 
+	 * @see #setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param domain cookie domain
+	 * @param path cookie path
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, String domain, String path) {
+		setCookie(name, value, -1, domain, path, false, false);
+	}
+		
+	/**
+	 * Add a cookie to response.
+	 * 
+	 * @see #setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param expiration expiration of cookie in seconds
+	 * @param domain cookie domain
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, long expiration, String domain) {
+		setCookie(name, value, expiration, domain, null, false, false);
+	}
+	
+	/**
+	 * Add a cookie to response. 
+	 * 
+	 * @see HttpResponse#setCookie(String, String, Integer, String, String, boolean, boolean)
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param expiration expiration of cookie in seconds 
+	 * @param domain cookie domain
+	 * @param path cookie path
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, long expiration, String domain, String
path) {
+		setCookie(name, value, expiration, domain, path, false, false);
+	}	
+	
+	/**
+	 * Add a cookie to response. 
+	 * The addition of a cookie with a name that was already inserted, causes the substitution
of the previous cookie
+	 *  
+	 * @param name name of cookie
+	 * @param value value of cookie
+	 * @param expiration expiration of cookie in seconds 
+	 * @param domain cookie domain
+	 * @param path cookie path
+	 * @param secure set <code>Secure</code> property of cookie
+	 * @param httpOnly set <code>HttpOnly</code> property of cookie
+	 * @throws IllegalArgumentException if cookie name, or value, is not valid
+	 */
+	public void setCookie(String name, String value, long expiration, String domain, String
path, boolean secure, boolean httpOnly) {
+		if (Strings.isNullOrEmpty(name)) {
+			throw new IllegalArgumentException("Cookie name is empty");
+		}
+		if (name.trim().startsWith("$")) {
+			throw new IllegalArgumentException("Cookie name is not valid");
+		}
+		StringBuffer sb = new StringBuffer(name.trim() + "=" + Strings.nullToEmpty(value).trim()
+ "; ");
+		if (CharMatcher.JAVA_ISO_CONTROL.countIn(sb) > 0) {
+			throw new IllegalArgumentException("Invalid cookie " + name + ": " + value);
+		}
+		if (expiration >= 0) {
+			if (expiration == 0)
+				sb.append("Expires=" + DateUtil.getDateAsString(new Date(0)) + "; ");
+			else 
+				sb.append("Expires=" + CookieUtil.maxAgeToExpires(expiration) + "; ");
+		} 
+		if (!Strings.isNullOrEmpty(domain)) {
+			sb.append("Domain=" + domain.trim() + "; ");
+		}
+		if (!Strings.isNullOrEmpty(path)) {
+			sb.append("Path=" + path.trim() + "; ");
+		}
+		if (secure) {
+			sb.append("Secure; ");
+		}
+		if (httpOnly) {
+			sb.append("HttpOnly; ");
+		}
+		cookies.put(name, sb.toString());
+	}
+	
+	/**
+	 * Removes a cookie. This method forces the removal of a cookie, by setting its expiration
in the past.
+	 * 
+	 * @param name name of cookie to delete
+	 */
+	public void clearCookie(String name) {
+		if (Strings.emptyToNull(name) != null) {	
+			setCookie(name, null, 0);
+		}
+	}
 
 	/**
 	 * The given data data will be sent as the HTTP response upon next flush or when the response
is finished.
@@ -182,6 +325,9 @@ public class HttpResponse {
 			sb.append(header.getValue());
 			sb.append("\r\n");
 		}
+		for (String cookie : cookies.values()) {
+			sb.append("Set-Cookie: " + cookie + "\r\n");
+		}
 		
 		sb.append("\r\n");
 		return sb.toString();

Modified: incubator/deft/sandbox/src/test/java/org/deftserver/util/DateUtilTest.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/test/java/org/deftserver/util/DateUtilTest.java?rev=1152427&r1=1152426&r2=1152427&view=diff
==============================================================================
--- incubator/deft/sandbox/src/test/java/org/deftserver/util/DateUtilTest.java (original)
+++ incubator/deft/sandbox/src/test/java/org/deftserver/util/DateUtilTest.java Sat Jul 30
05:16:26 2011
@@ -21,13 +21,12 @@ package org.deftserver.util;
 
 import static org.junit.Assert.assertEquals;
 
+import java.util.Date;
+
 import org.junit.Test;
 
 /**
  * Test cases for {@link DateUtil}.
- * 
- * @author <a href="johnathan.meehan@phasevariance.com">Johnathan Meehan</a>
- * @since 0.3.0
  */
 public class DateUtilTest {
 
@@ -58,4 +57,12 @@ public class DateUtilTest {
 		final String actual = DateUtil.parseToRFC1123(1266689558000L);
 		assertEquals("Sat, 20 Feb 2010 18:12:38 GMT", actual);
 	}
+	
+    @Test
+    public void testGetDateAsString() {
+    
+        Date date = new Date(1266689558000L);
+        String actual = DateUtil.getDateAsString(date);
+        assertEquals("Sat, 20 Feb 2010 18:12:38 GMT", actual);
+    }	
 }
\ No newline at end of file

Modified: incubator/deft/sandbox/src/test/java/org/deftserver/web/http/HttpRequestTest.java
URL: http://svn.apache.org/viewvc/incubator/deft/sandbox/src/test/java/org/deftserver/web/http/HttpRequestTest.java?rev=1152427&r1=1152426&r2=1152427&view=diff
==============================================================================
--- incubator/deft/sandbox/src/test/java/org/deftserver/web/http/HttpRequestTest.java (original)
+++ incubator/deft/sandbox/src/test/java/org/deftserver/web/http/HttpRequestTest.java Sat
Jul 30 05:16:26 2011
@@ -373,5 +373,36 @@ public class HttpRequestTest {
 		Assert.assertEquals("/foobar/", request.getRequestedPath());
 	}
 	
+	@Test
+	public void testNoCookies() {
+		HttpRequestHelper hrh = new HttpRequestHelper();
+		HttpRequest hr = HttpRequest.of(hrh.getRequestAsByteBuffer());
+		Assert.assertEquals(0, hr.getCookies().size());
+	}	  
+
+	@Test
+	public void testOneCookie() {
+	   	HttpRequestHelper hrh = new HttpRequestHelper();
+	   	hrh.addHeader("Cookie", "one=value");    
+	   	HttpRequest hr = HttpRequest.of(hrh.getRequestAsByteBuffer());
+	   	Assert.assertEquals("value",hr.getCookie("one"));
+	}    
+
+	@Test
+	public void testOneCookieWithoutValue() {
+		HttpRequestHelper hrh = new HttpRequestHelper();
+		hrh.addHeader("Cookie", "one=");	    
+		HttpRequest hr = HttpRequest.of(hrh.getRequestAsByteBuffer());
+		Assert.assertEquals("",hr.getCookie("one"));
+	}  	  
+
+	@Test
+	public void testMultipleCookies() {
+		HttpRequestHelper hrh = new HttpRequestHelper();
+		hrh.addHeader("Cookie", "one=value;two=value2");
+		HttpRequest hr = HttpRequest.of(hrh.getRequestAsByteBuffer());
+		Assert.assertEquals("value",hr.getCookie("one"));
+		Assert.assertEquals("value2",hr.getCookie("two"));
+	}	
 
 }



Mime
View raw message