|
From: <ian...@us...> - 2007-07-03 02:33:30
|
Revision: 209
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=209&view=rev
Author: iansmith
Date: 2007-07-02 19:33:29 -0700 (Mon, 02 Jul 2007)
Log Message:
-----------
Started down the road to building a tool that will sync a set of directories full of content with service that hosts those spaces. It's nowhere near complete yet.
Add support for RMock tests, since I like them. Examples in com.ogoglio.spacesync.SyncToolSpec.
Updated the .jars for cglib and junit to include proper version numbers. It appears that we were already at these versions but I wanted to be sure when I was including RMock that it was clear which version we were expecting. I did not delete old ones in case of catastrophic failure.
Java does not allow one to override (and thus mock) statics so I had to move WebAPIClient.authenticate to a separate class for later hackery. I created WebAPIUtil with a few things in it (including authenticate) and patched all the callers to use the new version. Other than the class name, no visible effects to callers.
So far, all my space sync tool does is parse the command line and look for directories that may be your collection of spaces that it should synchronize. This was enough to teach me how to use RMock (vince I was used to the ruby version, RSpec).
I split my "tests" into spec and unit parts. Eventually, I'd like to use the documentation generator (TDDocRender) to render documentation from my specs, but I couldn't get that to work right off the bat.
Modified Paths:
--------------
spaces/trunk/.classpath
spaces/trunk/src/com/ogoglio/client/ClientTests.java
spaces/trunk/src/com/ogoglio/client/SpaceDuplicatorTests.java
spaces/trunk/src/com/ogoglio/client/WebAPIClient.java
spaces/trunk/src/com/ogoglio/media/WebStore.java
spaces/trunk/src/com/ogoglio/persist/ServiceInitializationPersistTasks.java
spaces/trunk/src/com/ogoglio/site/AccountServlet.java
spaces/trunk/src/com/ogoglio/site/AuthServlet.java
spaces/trunk/src/com/ogoglio/site/MessageProxy.java
Added Paths:
-----------
spaces/trunk/src/com/ogoglio/client/WebAPIAuthenticator.java
spaces/trunk/src/com/ogoglio/client/WebAPIUtil.java
spaces/trunk/src/com/ogoglio/spacesync/
spaces/trunk/src/com/ogoglio/spacesync/SpaceSyncTestSuite.java
spaces/trunk/src/com/ogoglio/spacesync/SyncTool.java
spaces/trunk/src/com/ogoglio/spacesync/SyncToolSpec.java
spaces/trunk/src/com/ogoglio/spacesync/SyncToolTest.java
spaces/trunk/war/WEB-INF/lib/cglib-nodep-2.1_2.jar
spaces/trunk/war/WEB-INF/lib/junit-3.8.1.jar
spaces/trunk/war/WEB-INF/lib/rmock-2.0.0.jar
Modified: spaces/trunk/.classpath
===================================================================
--- spaces/trunk/.classpath 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/.classpath 2007-07-03 02:33:29 UTC (rev 209)
@@ -4,9 +4,8 @@
<classpathentry kind="var" path="TOMCAT_HOME/common/lib/servlet-api.jar"/>
<classpathentry kind="var" path="TOMCAT_HOME/common/lib/jasper-runtime.jar"/>
<classpathentry kind="var" path="TOMCAT_HOME/common/lib/jsp-api.jar"/>
- <classpathentry output="work" kind="src" path="work"/>
+ <classpathentry kind="src" output="work" path="work"/>
<classpathentry kind="src" path="src"/>
- <classpathentry kind="lib" path="war/WEB-INF/lib/junit.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/mysql-connector-java-3.1.11-bin.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/log4j-1.2.9.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/jta.jar"/>
@@ -16,7 +15,6 @@
<classpathentry kind="lib" path="war/WEB-INF/lib/dom4j-1.6.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/commons-logging-1.0.4.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/commons-collections-2.1.1.jar"/>
- <classpathentry kind="lib" path="war/WEB-INF/lib/cglib-2.1.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/asm-attrs.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/asm.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/antlr-2.7.5H3.jar"/>
@@ -27,5 +25,8 @@
<classpathentry kind="lib" path="war/WEB-INF/lib/commons-httpclient-3.0.1.jar"/>
<classpathentry kind="lib" path="war/WEB-INF/lib/commons-codec-1.3.jar"/>
<classpathentry kind="var" path="BROWSER_PLUGIN"/>
+ <classpathentry kind="lib" path="war/WEB-INF/lib/cglib-nodep-2.1_2.jar"/>
+ <classpathentry kind="lib" path="war/WEB-INF/lib/junit-3.8.1.jar"/>
+ <classpathentry kind="lib" path="war/WEB-INF/lib/rmock-2.0.0.jar"/>
<classpathentry kind="output" path="war/WEB-INF/classes"/>
</classpath>
Modified: spaces/trunk/src/com/ogoglio/client/ClientTests.java
===================================================================
--- spaces/trunk/src/com/ogoglio/client/ClientTests.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/client/ClientTests.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -81,7 +81,7 @@
public void testWebAdmin() {
try {
- String adminAuthCookie = WebAPIClient.authenticate(serviceURI1, ServiceInitializationPersistTasks.LIBRARY_USERNAME, ServiceInitializationPersistTasks.DEFAULT_LIBRARY_PASSWORD);
+ String adminAuthCookie = WebAPIUtil.authenticate(serviceURI1, ServiceInitializationPersistTasks.LIBRARY_USERNAME, ServiceInitializationPersistTasks.DEFAULT_LIBRARY_PASSWORD);
assertNotNull("got null auth cookie", adminAuthCookie);
try {
@@ -91,7 +91,7 @@
//may already exist
}
- String basicAuthCookie = WebAPIClient.authenticate(serviceURI1, USERNAME1, PASSWORD1);
+ String basicAuthCookie = WebAPIUtil.authenticate(serviceURI1, USERNAME1, PASSWORD1);
assertNotNull("got null auth cookie", basicAuthCookie);
try {
String failedUsername = "Bogosity" + System.currentTimeMillis();
@@ -136,11 +136,11 @@
SpaceClient guestSpaceClient1 = null;
try {
- String authCookie1 = WebAPIClient.authenticate(serviceURI1, USERNAME1, PASSWORD1);
+ String authCookie1 = WebAPIUtil.authenticate(serviceURI1, USERNAME1, PASSWORD1);
assertNotNull("got null auth cookie", authCookie1);
SpaceDocument spaceDoc1 = WebAPIClient.createSpace(serviceURI1, authCookie1);
- URI spaceURI1 = WebAPIClient.appendToURI(serviceURI1, "space/" + spaceDoc1.getSpaceID());
+ URI spaceURI1 = WebAPIUtil.appendToURI(serviceURI1, "space/" + spaceDoc1.getSpaceID());
try {
new WebAPIClient(spaceURI1, serviceURI1, "BadBadCookie").getSpaceDocument(false);
@@ -220,7 +220,7 @@
assertEquals(USERNAME2, membershipDocs[0].getMemberUsername());
assertEquals(SpaceMemberDocument.MEMBER, membershipDocs[0].getRole());
- String authCookie2 = WebAPIClient.authenticate(serviceURI1, USERNAME2, PASSWORD1);
+ String authCookie2 = WebAPIUtil.authenticate(serviceURI1, USERNAME2, PASSWORD1);
assertNotNull("got null auth cookie", authCookie1);
WebAPIClient webClient2 = new WebAPIClient(spaceURI1, serviceURI1, authCookie2);
membershipDocs = webClient2.getUsersSpaceMemberships();
@@ -354,7 +354,7 @@
assertNotNull(stream);
consume(stream);
- authCookie1 = WebAPIClient.authenticate(serviceURI1, USERNAME1, PASSWORD1);
+ authCookie1 = WebAPIUtil.authenticate(serviceURI1, USERNAME1, PASSWORD1);
assertNotNull("got null auth cookie", authCookie1);
TestSpaceClientListener listener = new TestSpaceClientListener();
Modified: spaces/trunk/src/com/ogoglio/client/SpaceDuplicatorTests.java
===================================================================
--- spaces/trunk/src/com/ogoglio/client/SpaceDuplicatorTests.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/client/SpaceDuplicatorTests.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -37,7 +37,7 @@
spaceURI2 = new URI("http://127.0.0.1:8080/og/space/2/");
serviceURI1 = new URI("http://127.0.0.1:8080/og/");
- authCookie = WebAPIClient.authenticate(serviceURI1, ClientTests.USERNAME1, ClientTests.PASSWORD1);
+ authCookie = WebAPIUtil.authenticate(serviceURI1, ClientTests.USERNAME1, ClientTests.PASSWORD1);
assertNotNull(authCookie);
client1 = new WebAPIClient(spaceURI1, serviceURI1, authCookie);
client1.putSetting(testSettingKey, testSettingValue);
Added: spaces/trunk/src/com/ogoglio/client/WebAPIAuthenticator.java
===================================================================
--- spaces/trunk/src/com/ogoglio/client/WebAPIAuthenticator.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/client/WebAPIAuthenticator.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -0,0 +1,50 @@
+package com.ogoglio.client;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintWriter;
+import java.net.HttpURLConnection;
+import java.net.URI;
+
+import nanoxml.XMLElement;
+
+import com.ogoglio.site.AuthServlet;
+
+public class WebAPIAuthenticator {
+
+ // it makes it a LOT easier to simulate if we use this style of a little object
+ // rather than the statics which don't allow mocking (and that's kinda important
+ // for authentication!)
+ public WebAPIAuthenticator() {
+
+ }
+
+ /**
+ * @return the authCookie or null if authentication failed
+ */
+ public String authenticate(URI serviceURI, String username, String password) throws IOException {
+
+ String body = AuthServlet.USERNAME_PARAM + "=" + username + "&" + AuthServlet.PASS_PARAM + "=" + password;
+
+ HttpURLConnection connection = (HttpURLConnection) WebAPIUtil.appendToURI(serviceURI, "auth/").toURL().openConnection();
+ connection.setRequestMethod("POST");
+ connection.setAllowUserInteraction(false);
+ connection.setDoOutput(true);
+ connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
+ connection.setRequestProperty("Content-length", Integer.toString(body.length()));
+
+ OutputStream rawOutStream = connection.getOutputStream();
+ PrintWriter pw = new PrintWriter(rawOutStream);
+ pw.print(body);
+ pw.flush();
+ pw.close();
+
+ String cookie = WebAPIUtil.parseSetCookieHeader(connection.getHeaderField("Set-Cookie"));
+
+ XMLElement data = new XMLElement();
+ data.parseFromReader(new InputStreamReader(connection.getInputStream()));
+ return cookie;
+ }
+
+}
Modified: spaces/trunk/src/com/ogoglio/client/WebAPIClient.java
===================================================================
--- spaces/trunk/src/com/ogoglio/client/WebAPIClient.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/client/WebAPIClient.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -87,19 +87,19 @@
public static AccountDocument createAccount(URI serviceURI, String adminAuthCookie, String username, String accountLevel, String firstName, String lastName, String homepage, String email, String password) throws IOException {
AccountDocument newAccountDoc = new AccountDocument(username, accountLevel, firstName, lastName, homepage, password, email, null, null, null, null, -1);
- XMLElement result = sendAuthenticatedXML(appendToURI(serviceURI, "account/"), newAccountDoc.toString(), "POST", adminAuthCookie);
+ XMLElement result = sendAuthenticatedXML(WebAPIUtil.appendToURI(serviceURI, "account/"), newAccountDoc.toString(), "POST", adminAuthCookie);
return new AccountDocument(result);
}
public static SpaceDocument createSpace(URI serviceURI, String authCookie) throws IOException {
AuthDocument authDocument = new AuthDocument(fetchAuthenticatedXML(getAuthURI(serviceURI), authCookie));
SpaceDocument spaceDoc = new SpaceDocument(-1, "New Space", authDocument.getUsername(), false, 0, false, 0, -1);
- XMLElement result = sendAuthenticatedXML(appendToURI(serviceURI, "account/" + authDocument.getUsername() + "/space/"), spaceDoc.toString(), "POST", authCookie);
+ XMLElement result = sendAuthenticatedXML(WebAPIUtil.appendToURI(serviceURI, "account/" + authDocument.getUsername() + "/space/"), spaceDoc.toString(), "POST", authCookie);
return new SpaceDocument(result);
}
public static AccountDocument updateAccount(URI serviceURI, String authCookie, AccountDocument accountDoc) throws IOException {
- XMLElement result = sendAuthenticatedXML(appendToURI(serviceURI, "account/" + accountDoc.getUsername()), accountDoc.toElement().toString(), "POST", authCookie);
+ XMLElement result = sendAuthenticatedXML(WebAPIUtil.appendToURI(serviceURI, "account/" + accountDoc.getUsername()), accountDoc.toElement().toString(), "POST", authCookie);
if (result == null) {
return null;
}
@@ -107,7 +107,7 @@
}
public static AccountDocument getAccountDocument(URI serviceURI, String authCookie, String username) throws IOException {
- XMLElement response = fetchAuthenticatedXML(appendToURI(serviceURI, "account/" + username), authCookie);
+ XMLElement response = fetchAuthenticatedXML(WebAPIUtil.appendToURI(serviceURI, "account/" + username), authCookie);
if (response == null) {
return null;
}
@@ -296,44 +296,7 @@
return StreamUtils.readInput(input);
}
- /**
- * @return the authCookie or null if authentication failed
- */
- public static String authenticate(URI serviceURI, String username, String password) throws IOException {
- String body = AuthServlet.USERNAME_PARAM + "=" + username + "&" + AuthServlet.PASS_PARAM + "=" + password;
-
- HttpURLConnection connection = (HttpURLConnection) appendToURI(serviceURI, "auth/").toURL().openConnection();
- connection.setRequestMethod("POST");
- connection.setAllowUserInteraction(false);
- connection.setDoOutput(true);
- connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
- connection.setRequestProperty("Content-length", Integer.toString(body.length()));
-
- OutputStream rawOutStream = connection.getOutputStream();
- PrintWriter pw = new PrintWriter(rawOutStream);
- pw.print(body);
- pw.flush();
- pw.close();
-
- String cookie = parseSetCookieHeader(connection.getHeaderField("Set-Cookie"));
-
- XMLElement data = new XMLElement();
- data.parseFromReader(new InputStreamReader(connection.getInputStream()));
- return cookie;
- }
-
- private static String parseSetCookieHeader(String setCookieHeader) {
- if (setCookieHeader == null || setCookieHeader.indexOf('=') == -1 || setCookieHeader.indexOf(';') == -1) {
- return null;
- }
- if (!setCookieHeader.startsWith(AuthServlet.AUTH_COOKIE + "=")) {
- System.err.println("Unknown set cookie: " + setCookieHeader);
- return null;
- }
- return setCookieHeader.substring(setCookieHeader.indexOf("=") + 1, setCookieHeader.indexOf(";"));
- }
-
public SpaceDocument getSpaceDocument(boolean includeChildren) throws IOException {
return new SpaceDocument(fetchAuthenticatedXML(getSpaceURI(includeChildren)));
}
@@ -521,19 +484,19 @@
}
public InputStream getGeometryStream(URI renderableRootURI, String name) throws IOException {
- return fetchAuthenticatedStream(appendToURI(renderableRootURI, "geometry/" + name), authCookie);
+ return fetchAuthenticatedStream(WebAPIUtil.appendToURI(renderableRootURI, "geometry/" + name), authCookie);
}
public void putGeometryStream(URI rootURI, InputStream input, String name) throws IOException {
- performPOST(appendToURI(rootURI, "geometry/" + name), StreamUtils.readInput(input), "application/octet-stream", authCookie);
+ performPOST(WebAPIUtil.appendToURI(rootURI, "geometry/" + name), StreamUtils.readInput(input), "application/octet-stream", authCookie);
}
public void putGeometryStream(URI rootURI, InputStream input, int lodIndex) throws IOException {
- performPOST(appendToURI(rootURI, "geometry/data/" + lodIndex), StreamUtils.readInput(input), "application/octet-stream", authCookie);
+ performPOST(WebAPIUtil.appendToURI(rootURI, "geometry/data/" + lodIndex), StreamUtils.readInput(input), "application/octet-stream", authCookie);
}
public InputStream getGeometryStream(URI renderableRootURI, int lodIndex) throws IOException {
- return fetchAuthenticatedStream(appendToURI(renderableRootURI, "geometry/data/" + lodIndex), authCookie);
+ return fetchAuthenticatedStream(WebAPIUtil.appendToURI(renderableRootURI, "geometry/data/" + lodIndex), authCookie);
}
public static InputStream performGET(URI uri, String authCookie) throws IOException {
@@ -660,7 +623,7 @@
pw.close();
}
- String cookie = parseSetCookieHeader(connection.getHeaderField("Set-Cookie"));
+ String cookie = WebAPIUtil.parseSetCookieHeader(connection.getHeaderField("Set-Cookie"));
if (connection.getResponseCode() != 200) {
throw new IOException("Get status " + connection.getResponseCode() + " from " + uri);
@@ -696,57 +659,48 @@
return fetchAuthenticatedXML(uri, authCookie);
}
- public static URI appendToURI(URI uri, String suffix) {
- try {
- String uriString = uri.toString();
- return new URI(uriString + (uriString.endsWith("/") ? "" : "/") + suffix);
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("Bad uri: " + uri.toString() + suffix);
- }
- }
-
public URI getSpaceURI() {
return spaceURI;
}
public URI getSpaceURI(boolean includeChildren) {
if (includeChildren) {
- return appendToURI(spaceURI, "?" + SpaceServlet.INCLUDE_CHILDREN_PARAM + "=true");
+ return WebAPIUtil.appendToURI(spaceURI, "?" + SpaceServlet.INCLUDE_CHILDREN_PARAM + "=true");
} else {
return spaceURI;
}
}
public URI getSpaceMemberURI() {
- return appendToURI(spaceURI, "member/");
+ return WebAPIUtil.appendToURI(spaceURI, "member/");
}
private URI getSpaceMemberURI(String memberUsername) {
- return appendToURI(getSpaceMemberURI(), memberUsername + "/");
+ return WebAPIUtil.appendToURI(getSpaceMemberURI(), memberUsername + "/");
}
private URI getUsersSpaceMembershipsURI(String username) {
- return appendToURI(getAccountURI(username), "membership/");
+ return WebAPIUtil.appendToURI(getAccountURI(username), "membership/");
}
public URI getAccountURI() {
- return appendToURI(serviceURI, "account/");
+ return WebAPIUtil.appendToURI(serviceURI, "account/");
}
public URI getAccountURI(String username) {
- return appendToURI(getAccountURI(), username + "/");
+ return WebAPIUtil.appendToURI(getAccountURI(), username + "/");
}
private URI getPossessionsURI(String username) {
- return appendToURI(getAccountURI(username), "possession/");
+ return WebAPIUtil.appendToURI(getAccountURI(username), "possession/");
}
private URI getPossessionURI(String username, long possessionID) {
- return appendToURI(getPossessionsURI(username), possessionID + "/");
+ return WebAPIUtil.appendToURI(getPossessionsURI(username), possessionID + "/");
}
public static URI getAuthURI(URI serviceURI) {
- return appendToURI(serviceURI, "auth/");
+ return WebAPIUtil.appendToURI(serviceURI, "auth/");
}
public URI getAuthURI() {
@@ -754,75 +708,75 @@
}
private static URI getAuthGuestURI(URI serviceURI) {
- return appendToURI(getAuthURI(serviceURI), "guest/");
+ return WebAPIUtil.appendToURI(getAuthURI(serviceURI), "guest/");
}
private URI getAccountSpacesURI(String username) {
- return appendToURI(getAccountURI(username), "space/");
+ return WebAPIUtil.appendToURI(getAccountURI(username), "space/");
}
public URI getTemplatesURI(String username) {
- return appendToURI(getAccountURI(username), "template/");
+ return WebAPIUtil.appendToURI(getAccountURI(username), "template/");
}
public URI getTemplateURI(String username, long templateID) {
- return appendToURI(getTemplatesURI(username), templateID + "/");
+ return WebAPIUtil.appendToURI(getTemplatesURI(username), templateID + "/");
}
public URI getDoorsURI() {
- return appendToURI(spaceURI, "door/");
+ return WebAPIUtil.appendToURI(spaceURI, "door/");
}
public URI getDoorURI(long doorID) {
- return appendToURI(getDoorsURI(), doorID + "/");
+ return WebAPIUtil.appendToURI(getDoorsURI(), doorID + "/");
}
public URI getThingsURI() {
- return appendToURI(spaceURI, "thing/");
+ return WebAPIUtil.appendToURI(spaceURI, "thing/");
}
public URI getThingURI(long thingID) {
- return appendToURI(getThingsURI(), thingID + "/");
+ return WebAPIUtil.appendToURI(getThingsURI(), thingID + "/");
}
private URI getTemplateScriptURI(String username, long templateID) {
- return appendToURI(getTemplateURI(username, templateID), "script/");
+ return WebAPIUtil.appendToURI(getTemplateURI(username, templateID), "script/");
}
public URI getUserURI(String username) {
- return appendToURI(getUsersURI(), username + "/");
+ return WebAPIUtil.appendToURI(getUsersURI(), username + "/");
}
public URI getUsersURI() {
- return appendToURI(spaceURI, "user/");
+ return WebAPIUtil.appendToURI(spaceURI, "user/");
}
private URI getBodiesURI(String username) {
- return appendToURI(getAccountURI(username), "body/");
+ return WebAPIUtil.appendToURI(getAccountURI(username), "body/");
}
public URI getBodyURI(String username, long bodyID) {
- return appendToURI(getBodiesURI(username), bodyID + "/");
+ return WebAPIUtil.appendToURI(getBodiesURI(username), bodyID + "/");
}
public URI getPagesURI(long thingID) {
- return appendToURI(getThingURI(thingID), "page/");
+ return WebAPIUtil.appendToURI(getThingURI(thingID), "page/");
}
public URI getPageURI(long thingID, long pageID) {
- return appendToURI(getPagesURI(thingID), pageID + "/");
+ return WebAPIUtil.appendToURI(getPagesURI(thingID), pageID + "/");
}
private URI getPageContentsURI(long thingID, long pageID) {
- return appendToURI(getPageURI(thingID, pageID), "content");
+ return WebAPIUtil.appendToURI(getPageURI(thingID, pageID), "content");
}
public URI getSettingsURI() {
- return appendToURI(getSpaceURI(), "setting/");
+ return WebAPIUtil.appendToURI(getSpaceURI(), "setting/");
}
public URI getSettingURI(String key) {
- return appendToURI(getSettingsURI(), key + "/");
+ return WebAPIUtil.appendToURI(getSettingsURI(), key + "/");
}
}
Added: spaces/trunk/src/com/ogoglio/client/WebAPIUtil.java
===================================================================
--- spaces/trunk/src/com/ogoglio/client/WebAPIUtil.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/client/WebAPIUtil.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -0,0 +1,34 @@
+package com.ogoglio.client;
+
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import com.ogoglio.site.AuthServlet;
+
+public class WebAPIUtil {
+ public static URI appendToURI(URI uri, String suffix) {
+ try {
+ String uriString = uri.toString();
+ return new URI(uriString + (uriString.endsWith("/") ? "" : "/") + suffix);
+ } catch (URISyntaxException e) {
+ throw new IllegalArgumentException("Bad uri: " + uri.toString() + suffix);
+ }
+ }
+
+ //for clients that don't want to bother creating the authenticator object
+ public static String authenticate(URI serviceURI, String username, String password)
+ throws IOException {
+ return (new WebAPIAuthenticator()).authenticate(serviceURI, username, password);
+ }
+ public static String parseSetCookieHeader(String setCookieHeader) {
+ if (setCookieHeader == null || setCookieHeader.indexOf('=') == -1 || setCookieHeader.indexOf(';') == -1) {
+ return null;
+ }
+ if (!setCookieHeader.startsWith(AuthServlet.AUTH_COOKIE + "=")) {
+ System.err.println("Unknown set cookie: " + setCookieHeader);
+ return null;
+ }
+ return setCookieHeader.substring(setCookieHeader.indexOf("=") + 1, setCookieHeader.indexOf(";"));
+ }
+}
Modified: spaces/trunk/src/com/ogoglio/media/WebStore.java
===================================================================
--- spaces/trunk/src/com/ogoglio/media/WebStore.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/media/WebStore.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -19,6 +19,7 @@
import java.net.URI;
import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.client.WebAPIUtil;
import com.ogoglio.util.ArgumentUtils;
public class WebStore implements MediaStore {
@@ -35,7 +36,7 @@
}
public boolean write(String name, InputStream input, long maxSize) throws IOException {
- InputStream responseInput = WebAPIClient.performPUT(WebAPIClient.appendToURI(mediaURI, name), input, "application/data", -1, null);
+ InputStream responseInput = WebAPIClient.performPUT(WebAPIUtil.appendToURI(mediaURI, name), input, "application/data", -1, null);
if(responseInput == null) {
return false;
}
@@ -46,19 +47,19 @@
public InputStream getData(String name) {
try {
- return WebAPIClient.performGET(WebAPIClient.appendToURI(mediaURI, name), null);
+ return WebAPIClient.performGET(WebAPIUtil.appendToURI(mediaURI, name), null);
} catch (IOException e) {
return null;
}
}
public long getSize(String name) {
- return WebAPIClient.requestContentLength(WebAPIClient.appendToURI(mediaURI, name), null);
+ return WebAPIClient.requestContentLength(WebAPIUtil.appendToURI(mediaURI, name), null);
}
public boolean delete(String name) {
try {
- return WebAPIClient.sendDelete(WebAPIClient.appendToURI(mediaURI, name), null);
+ return WebAPIClient.sendDelete(WebAPIUtil.appendToURI(mediaURI, name), null);
} catch (IOException e) {
e.printStackTrace();
return false;
Modified: spaces/trunk/src/com/ogoglio/persist/ServiceInitializationPersistTasks.java
===================================================================
--- spaces/trunk/src/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -18,7 +18,7 @@
import org.hibernate.SessionFactory;
-import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.client.WebAPIUtil;
public class ServiceInitializationPersistTasks {
@@ -37,7 +37,7 @@
if (simRecords.length != 0) {
return;
}
- SimPersistTasks.createSim(LOCAL_SIM_DISPLAY_NAME, WebAPIClient.appendToURI(serviceURI, "sim/"), SimRecord.DEFAULT_EVENT_PORT, true, sessionFactory);
+ SimPersistTasks.createSim(LOCAL_SIM_DISPLAY_NAME, WebAPIUtil.appendToURI(serviceURI, "sim/"), SimRecord.DEFAULT_EVENT_PORT, true, sessionFactory);
}
public static void initializeLibraryAccount(SessionFactory sessionFactory,String host) throws PersistException, IOException {
Modified: spaces/trunk/src/com/ogoglio/site/AccountServlet.java
===================================================================
--- spaces/trunk/src/com/ogoglio/site/AccountServlet.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/site/AccountServlet.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -29,6 +29,7 @@
import nanoxml.XMLElement;
import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.client.WebAPIUtil;
import com.ogoglio.media.MediaService;
import com.ogoglio.persist.AccountPersistTasks;
import com.ogoglio.persist.AccountRecord;
@@ -725,7 +726,7 @@
if (spaceRecord != null) {
SimRecord simRecord = SpacePersistTasks.findOrAssignSim(spaceRecord, getSessionFactory());
if (simRecord != null) {
- URI thingURI = WebAPIClient.appendToURI(simRecord.getSimURI(), "space/" + record.getSpaceID() + "/thing/" + record.getThingID());
+ URI thingURI = WebAPIUtil.appendToURI(simRecord.getSimURI(), "space/" + record.getSpaceID() + "/thing/" + record.getThingID());
if (!WebAPIClient.sendDelete(thingURI, null)) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
@@ -775,7 +776,7 @@
if (oldSpaceRecord != null) {
SimRecord simRecord = SpacePersistTasks.findOrAssignSim(oldSpaceRecord, getSessionFactory());
if (simRecord != null) {
- URI thingURI = WebAPIClient.appendToURI(simRecord.getSimURI(), "space/" + oldSpaceID + "/thing/" + oldThingID);
+ URI thingURI = WebAPIUtil.appendToURI(simRecord.getSimURI(), "space/" + oldSpaceID + "/thing/" + oldThingID);
if (!WebAPIClient.sendDelete(thingURI, null)) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
@@ -810,7 +811,7 @@
return;
}
- URI thingsURI = WebAPIClient.appendToURI(simRecord.getSimURI(), "space/" + record.getSpaceID() + "/thing/");
+ URI thingsURI = WebAPIUtil.appendToURI(simRecord.getSimURI(), "space/" + record.getSpaceID() + "/thing/");
ThingDocument thingDoc = new ThingDocument(-1, templateRecord.getDisplayName(), templateRecord.getTemplateID(), templateRecord.getOwnerUsername(), record.getOwnerUsername(), record.getPossessionID(), new Transform3D(), null);
try {
XMLElement element = WebAPIClient.sendAuthenticatedXML(thingsURI, thingDoc.toString(), "POST", null);
@@ -836,14 +837,6 @@
}
}
- private MessageProxy getMessageProxy() {
- MessageProxy proxy = (MessageProxy) getServletContext().getAttribute(SpaceServlet.MESSAGE_PROXY_KEY);
- if (proxy == null) {
- throw new IllegalStateException("No Message Proxy!");
- }
- return proxy;
- }
-
private class PossessionsResource extends AuthenticatedSiteResource {
public PossessionsResource() {
super("possession", true, getSessionFactory());
Modified: spaces/trunk/src/com/ogoglio/site/AuthServlet.java
===================================================================
--- spaces/trunk/src/com/ogoglio/site/AuthServlet.java 2007-07-01 20:25:27 UTC (rev 208)
+++ spaces/trunk/src/com/ogoglio/site/AuthServlet.java 2007-07-03 02:33:29 UTC (rev 209)
@@ -1,258 +1,256 @@
-/* Copyright 2007 Transmutable (http://transmutable.com/)
-
- Licensed 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 com.ogoglio.site;
-
-import java.io.IOException;
-import java.util.Random;
-
-import javax.servlet.ServletConfig;
-import javax.servlet.ServletException;
-import javax.servlet.http.Cookie;
-import javax.servlet.http.HttpServletRequest;
-import javax.servlet.http.HttpServletResponse;
-
-import org.hibernate.SessionFactory;
-
-import com.ogoglio.persist.AccountPersistTasks;
-import com.ogoglio.persist.AccountRecord;
-import com.ogoglio.persist.PersistException;
-import com.ogoglio.xml.AuthDocument;
-
-public class AuthServlet extends AbstractResourceServlet {
-
- public static final String AUTH_DATA_KEY = "authData";
-
- public static final String AUTH_COOKIE = "loginCookie";
-
- public static final String USERNAME_PARAM = "username";
-
- public static final String PASS_PARAM = "password";
-
- public static final String LOGOUT_PARAM = "logout";
-
- private Random random = new Random();
-
- //TODO add a way to remove a login cookie from the db when people change their password
-
- public SiteResource createBaseResource(ServletConfig servletConfig) {
- return new AuthResource();
- }
-
- public static boolean isGuest(HttpServletRequest request) {
- String cookie = getRequestAuthCookie(request);
- if (cookie == null) {
- return false;
- }
- return cookie.startsWith(GUEST_COOKIE_PREFIX);
- }
-
- public static AccountRecord getAuthedAccountRecord(HttpServletRequest request, SessionFactory hibernateSessionFactory) throws PersistException {
- String cookie = getRequestAuthCookie(request);
- if (cookie == null) {
- return null;
- }
- return AccountPersistTasks.findAccountByCookie(cookie, hibernateSessionFactory);
- }
-
- private AccountRecord authenticate(String username, String password) throws PersistException {
- if (username == null || password == null) {
- return null;
- }
-
- AccountRecord accountRecord = AccountPersistTasks.findAccountByUsername(username, getSessionFactory());
- if (accountRecord == null) {
- return null;
- }
- if (accountRecord.getFrozenUntil() != null && accountRecord.getFrozenUntil().getTime() > System.currentTimeMillis()) {
- return null;
- }
- if (password != null && !password.equals(accountRecord.getPassword())) {
- return null;
- }
-
- if (accountRecord.getCookie() == null) {
- accountRecord.setCookie(generateAuthCookie(false));
- }
-
- AccountPersistTasks.update(accountRecord, getSessionFactory());
-
- return accountRecord;
- }
-
- private class AuthResource extends SiteResource {
- public AuthResource() {
- super("auth");
- addSubResource(new GuestResource());
- }
-
- public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
- try {
-
- String logoutParam = request.getParameter(LOGOUT_PARAM);
-
- AccountRecord cookieAccountRecord = getAuthedAccountRecord(request, getSessionFactory());
-
- if (request.getParameter("debug") != null) {
- String result = "";
- if (cookieAccountRecord != null) {
- result += "person element: " + cookieAccountRecord.getUsername() + "\n";
- result += "authCookie: " + cookieAccountRecord.getCookie() + "\n";
- }
- result += "requestCookie: " + getRequestAuthCookie(request) + "\n";
- result += "logoutParam: " + logoutParam + "\n";
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/plain");
- response.getOutputStream().write(result.getBytes());
- return;
- } else if ("true".equals(logoutParam)) {
- request.getSession().removeAttribute(AUTH_DATA_KEY);
- Cookie logoutCookie = new Cookie(AUTH_COOKIE, "logMeOut");
- logoutCookie.setPath("/");
- logoutCookie.setMaxAge(0);
- logoutCookie.setDomain(getSiteInfo().getHost());
- response.addCookie(logoutCookie);
-
- AuthDocument authDoc = new AuthDocument();
-
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/xml");
- response.getOutputStream().write(authDoc.toString().getBytes());
- return;
- } else {
- AuthDocument authDoc = null;
- if (cookieAccountRecord != null) {
- authDoc = new AuthDocument(cookieAccountRecord.getUsername(), true);
- } else {
- authDoc = new AuthDocument();
- }
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/xml");
- response.getOutputStream().write(authDoc.toString().getBytes());
- return;
- }
- } catch (PersistException e) {
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- }
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
- try {
-
- String usernameParam = request.getParameter(USERNAME_PARAM);
- String passParam = request.getParameter(PASS_PARAM);
-
- if (usernameParam != null || passParam != null) {
- AccountRecord authedAccountRecord = authenticate(usernameParam, passParam);
- if (authedAccountRecord != null) {
- Cookie newCookie = new Cookie(AUTH_COOKIE, authedAccountRecord.getCookie());
- newCookie.setPath("/");
- newCookie.setMaxAge(Integer.MAX_VALUE - 1);
- newCookie.setDomain(getSiteInfo().getHost());
- response.addCookie(newCookie);
-
- AuthDocument authDoc = new AuthDocument(authedAccountRecord.getUsername(), true);
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/xml");
- response.getOutputStream().write(authDoc.toString().getBytes());
- return;
- } else {
- AuthDocument authDoc = new AuthDocument();
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/xml");
- response.getOutputStream().write(authDoc.toString().getBytes());
- return;
- }
- }
-
- AccountRecord cookieAccountRecord = getAuthedAccountRecord(request, getSessionFactory());
- AuthDocument authDoc = null;
- if (cookieAccountRecord != null) {
- authDoc = new AuthDocument(cookieAccountRecord.getUsername(), true);
- } else {
- authDoc = new AuthDocument();
- }
-
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/xml");
- response.getOutputStream().write(authDoc.toString().getBytes());
- return;
- } catch (PersistException e) {
- response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
- return;
- }
-
- }
- }
-
- private class GuestResource extends SiteResource {
- public GuestResource() {
- super("guest");
- }
-
- public void doPost(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
- String cookie = generateGuestCookie();
- Cookie newCookie = new Cookie(AUTH_COOKIE, cookie);
- newCookie.setPath("/");
- newCookie.setMaxAge(-1);
- newCookie.setDomain(getSiteInfo().getHost());
-
- response.addCookie(newCookie);
-
- response.setStatus(HttpServletResponse.SC_OK);
- response.setContentType("text/plain");
- response.getOutputStream().write(cookie.getBytes());
- return;
- }
- }
-
- public static String getRequestAuthCookie(HttpServletRequest request) {
- Cookie[] cookies = request.getCookies();
- for (int i = 0; cookies != null && i < cookies.length; i++) {
- if (AUTH_COOKIE.equals(cookies[i].getName())) {
- return cookies[i].getValue();
- }
- }
- return null;
- }
-
- public static final String COOKIE_CHARS = "abcdefghijklmnopqrstuvwxyz1234567890";
-
- public static final String GUEST_COOKIE_PREFIX = "guest";
-
- public static final String[] GUEST_NAMES = { "Moon", "Spoon", "Plume", "Bloom", "Thyme", "Rhyme", "Steel", "Boat", "Vase", "Book", "Screen", "Fenestra", "Farmer", "Door", "Squid", "Rocket", "Picker", "Page", "Lawn", "Food", "Plate", "Bean", "Horse", "Cat", "Fireplace", "Frame", "Chair", "Table", "Sofa", "Stair", "Counter", "Shelf", "Phone", "Robot", "Tree", "Key" };
-
- private String generateGuestCookie() {
- StringBuffer result = new StringBuffer();
- result.append(GUEST_COOKIE_PREFIX);
- for (int i = 0; i < 3; i++) {
- result.append("_" + GUEST_NAMES[Math.abs(random.nextInt()) % GUEST_NAMES.length]);
- }
- return result.toString();
- }
-
- private String generateAuthCookie(boolean guest) {
- StringBuffer result = new StringBuffer(14);
- if (guest) {
- result.append(GUEST_COOKIE_PREFIX);
- } else {
- result.append("tr");
- }
- for (int i = 0; i < 12; i++) {
- result.append(COOKIE_CHARS.charAt(Math.abs(random.nextInt()) % COOKIE_CHARS.length()));
- }
- return result.toString();
- }
-
-}
+\xFE\xFF |