|
From: <ian...@us...> - 2007-08-29 20:55:22
|
Revision: 290
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=290&view=rev
Author: iansmith
Date: 2007-08-29 13:55:24 -0700 (Wed, 29 Aug 2007)
Log Message:
-----------
New support for migrations and better support for test resources.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
maven/trunk/ogoglio-common/.classpath
maven/trunk/ogoglio-common/pom.xml
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/WebConstants.java
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-server/.classpath
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/AuthServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
Added Paths:
-----------
maven/trunk/ogoglio-appdev/src/test/resources/basic.properties
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/PropStorage.java
maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties
maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties
maven/trunk/ogoglio-server/src/test/resources/basic-config.properties
maven/trunk/ogoglio-server/src/test/resources/bootstrap.properties
maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/
maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -9,6 +9,21 @@
public interface Migration {
- public boolean migrate(SessionFactory sessionFactory, ServletConfig servletConfig, Context ctx, Properties testConfig, int from, int to);
+ /*
+ * Called to move a running database from one version to another. The receiver should
+ * take actions that are required to make the new schema work properly, such as fixing
+ * pointers that may have been put out-of-date.
+ *
+ * Return false if things went wrong.
+ */
+ public boolean patch(SessionFactory sessionFactory, ServletConfig servletConfig, Context ctx, int from, int to);
+ /*O
+ * The receiver should use this call to populate the database with data that would be useful
+ * to sample programs or a user such as example user accounts, etc.
+ *
+ * Return false if things went wrong.
+ */
+ public boolean populate(SessionFactory sessionFactory, int from, int to);
+
}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -1,9 +1,5 @@
package com.ogoglio.appdev.migrate;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
-
import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
@@ -12,13 +8,19 @@
import org.hibernate.cfg.Configuration;
import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.util.PropStorage;
import com.ogoglio.viewer.render.UIConstants;
+
+
public abstract class MigrationSupport {
//check on migration okayness
public static final String MIGRATION_KEY = "ogoglio/okToMigrateDB";
+ public static final boolean DDL_MODE_UPDATE=true;
+ public static final boolean DDL_MODE_CREATE=false;
+
public MigrationSupport() {
}
@@ -32,7 +34,8 @@
if (version != versionNumber()) {
System.err.println("DB Version Mismatch! Expected (" + versionNumber() + ") but got " + version + "!");
sessionFactory.close();
- return tryUpgrade(servletConf, ctx, version, versionNumber(), "update", true);
+ return tryUpgrade(servletConf, ctx, version, versionNumber(),
+ DDL_MODE_UPDATE, true, null);
}
sessionFactory.close();
return true; // we are at the expected version
@@ -42,12 +45,12 @@
return false;
}
System.err.println("Unable to figure out DB version number. Likely this is a fresh database....(" + e.innerThrowable.getClass().getName() + ")");
- return initialize_version(servletConf, ctx, true);
+ return initVersionAndUpgrade(servletConf, ctx);
}
}
- public boolean initialize_version(ServletConfig conf, Context ctx, boolean useJNDI) {
- Configuration configuration = createConfigurationForHibernate(0, "create", useJNDI);
+ public boolean initVersionOnly(boolean useJNDI, PropStorage propStore) {
+ Configuration configuration = createConfigurationForHibernate(0, "create", useJNDI, propStore);
try {
SessionFactory factory = configuration.buildSessionFactory();
if (setVersionNumberOfDbViaQuery(factory, 0, 0) == false) {
@@ -55,19 +58,25 @@
return false;
}
factory.close();
- return tryUpgrade(conf, ctx, 0, versionNumber(), "create", useJNDI);
- } catch (Throwable e) {
- System.err.println("Error trying initialized DB:" + e.getMessage());
+ return true;
+ } catch (Throwable t) {
+ System.err.println("Error trying initialized DB:" + t.getMessage());
return false;
}
-
}
+
+ public boolean initVersionAndUpgrade(ServletConfig conf, Context ctx) {
+ if (!initVersionOnly(true,null)) {
+ return false;
+ }
+ return tryUpgrade(conf, ctx, 0, versionNumber(), DDL_MODE_UPDATE, true,null);
+ }
public Configuration getCurrentConfiguration() {
- return createConfigurationForHibernate(versionNumber(), null, true);
+ return createConfigurationForHibernate(versionNumber(), null, true, null);
}
- public Configuration createConfigurationForHibernate(int num, String autoSetting, boolean useJNDI) {
+ public Configuration createConfigurationForHibernate(int num, String autoSetting, boolean useJNDI, PropStorage ps) {
Configuration configuration = new Configuration();
if (autoSetting != null) {
configuration.setProperty("hibernate.hbm2ddl.auto", autoSetting);
@@ -75,14 +84,7 @@
if (useJNDI) {
configuration.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/space");
} else {
- Properties p = new Properties();
- try {
- p.load(getClass().getResourceAsStream("/test-config.properties"));
- configuration.addProperties(p);
- } catch (IOException e) {
- System.err.println("Unable to find the test configuration file!" + e.getMessage());
- return configuration.configure();
- }
+ configuration.addProperties(ps.getAllProps(PropStorage.TEST_CONFIG_PROPS));
}
configuration.addInputStream(UIConstants.getResource("com/ogoglio/migrate/migration-" + num + ".xml"));
return configuration.configure();
@@ -97,35 +99,39 @@
}
}
- public boolean tryUpgrade(ServletConfig servletConfig, Context ctx, int db_is, int db_wants_to_be, String ddlMode, boolean useJNDI) {
+ public boolean tryUpgrade(ServletConfig servletConfig, Context ctx, int db_is,
+ int db_wants_to_be, boolean isUpdate, boolean useJNDI, PropStorage propStore) {
if (migrationList().length != versionNumber()) {
System.out.println("Internal error! Migration list length should be " + versionNumber() + " but is " + migrationList().length + "!");
return false;
}
- Properties testConfig = new Properties();
boolean canMigrate = false;
- if (ctx == null) {
- //in test mode
- testConfig = getTestConfig();
- if ("true".equals(testConfig.getProperty("ogoglio.okToMigrateDB"))) {
- canMigrate = true;
- }
- } else {
- //not testing, but might be integration testing
- try {
- String migrate = (String) ctx.lookup(MIGRATION_KEY);
- if ("true".equals(migrate)) {
- canMigrate = true;
- }
- } catch (NamingException e) {
- System.err.println("Naming exception trying to access " + MIGRATION_KEY + " from naming context!");
- }
+
+ //check the flags
+ try {
+ String migrate;
+ if (useJNDI) {
+ migrate = (String) ctx.lookup(MIGRATION_KEY);
+ } else {
+ migrate= propStore.getKeyFromSet(PropStorage.TEST_CONFIG_PROPS, "ogoglio.okToMigrateDB");
+ }
+ if ("true".equals(migrate)) {
+ canMigrate = true;
+ }
+ } catch (NamingException e) {
+ System.err.println("Naming exception trying to access " + MIGRATION_KEY + " from naming context!");
+ canMigrate=false;
}
if (!canMigrate) {
System.err.println("Cannot migrate data! Property ogoglio.okToMigrateDB is false or non-existent!");
return false;
}
+ String hbm_auto_flag="update";
+ if (!isUpdate) {
+ hbm_auto_flag="create";
+ }
+
for (int i = db_is; i < db_wants_to_be; ++i) {
Migration current = migrationList()[i];
@@ -133,38 +139,47 @@
System.out.println("DB: Attempting migration from " + i + " to " + (i + 1) + "...");
//try to get hibernate to do the work
- Configuration config = createConfigurationForHibernate(i + 1, ddlMode, useJNDI);
+ Configuration config = createConfigurationForHibernate(i + 1, hbm_auto_flag, useJNDI, propStore);
SessionFactory factory = config.buildSessionFactory();
//subtle: if the ddlMode is create, hibernate blows away all the data (including our version number record)
int expectedRecords = 1;
- if ("create".equals(ddlMode)) {
+ if (!isUpdate) {
expectedRecords = 0;
}
setVersionNumberOfDbViaQuery(factory, i + 1, expectedRecords);
- if (!current.migrate(factory, servletConfig, ctx, testConfig, i, i + 1)) {
+ if (!current.patch(factory, servletConfig, ctx, i, i + 1)) {
factory.close();
return false;
}
+
+ if (!isUpdate) {
+ //we need to go ahead and create the data
+ if (!current.populate(factory, i, i+1)) {
+ System.out.println("FART: Whoa! Populate failed!"+i);
+ factory.close();
+ return false;
+ }
+ System.out.println("FART: Populate ok!"+i);
+ }
+
factory.close();
System.out.println("------------------------------------------------\n");
}
return true;
}
- public Properties getTestConfig() {
- Properties testConfig = new Properties();
- InputStream is = getClass().getResourceAsStream("/test-config.properties");
- if (is == null) {
- System.err.println("Warning! Unable to find test-config.properties! Probably something is broken!");
- } else {
- try {
- testConfig.load(is);
- } catch (IOException e) {
- System.err.println("Warning! Error reading test-config.properties! " + e.getMessage());
- }
- }
- return testConfig;
- }
+ public boolean destroyAllData() {
+ PropStorage ps =new PropStorage();
+ if (ps.loadPropertySet(PropStorage.TEST_CONFIG_PROPS)==false) {
+ return false;
+ }
+
+ if (initVersionOnly(false, ps)==false) {
+ return false;
+ }
+
+ return tryUpgrade(null, null, 0, versionNumber(), DDL_MODE_CREATE, false, ps);
+ }
}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -5,6 +5,7 @@
import org.hibernate.SessionFactory;
import com.ogoglio.appdev.migrate.MigrationSupport;
+import com.ogoglio.util.PropStorage;
public abstract class DBZapTest extends TestCase {
@@ -15,15 +16,19 @@
public void setUp() {
try {
MigrationSupport support = getMigrationSupport();
- if (!("true".equals(support.getTestConfig().getProperty("ogoglio.okToZapDB")))) {
+ PropStorage ps=new PropStorage();
+ if (ps.loadPropertySet(PropStorage.TEST_CONFIG_PROPS)==false) {
+ fail("Can't load test configuration for hibernate properties!");
+ }
+ if (!("true".equals(ps.getKeyFromSet(PropStorage.TEST_CONFIG_PROPS,"ogoglio.okToZapDB")))) {
fail("Whoa! Shouldn't be running tests without setting the ogoglio.okToZapDB property!");
}
- if (support.initialize_version(null, null, false) == false) {
+ if (support.destroyAllData() == false) {
fail("can't get DB set up: trying to initialize it in the test code");
}
//if we are here, db stuff worked, but we still need to avoid all the jndi stuff
- sessionFactory = support.createConfigurationForHibernate(getMigrationSupport().versionNumber(), null, false).buildSessionFactory();
+ sessionFactory = support.createConfigurationForHibernate(getMigrationSupport().versionNumber(), null, false, ps).buildSessionFactory();
} catch (Exception e) {
System.out.println("-------");
e.printStackTrace(System.out);
Added: maven/trunk/ogoglio-appdev/src/test/resources/basic.properties
===================================================================
--- maven/trunk/ogoglio-appdev/src/test/resources/basic.properties (rev 0)
+++ maven/trunk/ogoglio-appdev/src/test/resources/basic.properties 2007-08-29 20:55:24 UTC (rev 290)
@@ -0,0 +1,4 @@
+# basic info needed for some tests
+ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
+ogoglio.baseUrl = ${ogoglio.baseURL}
+
Modified: maven/trunk/ogoglio-common/.classpath
===================================================================
--- maven/trunk/ogoglio-common/.classpath 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-common/.classpath 2007-08-29 20:55:24 UTC (rev 290)
@@ -2,9 +2,7 @@
<classpath>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
- <classpathentry excluding="**" output="src/main/resources/avatar" kind="src" path="src/main/resources/avatar"/>
- <classpathentry excluding="**" output="src/main/resources/templates" kind="src" path="src/main/resources/templates"/>
- <classpathentry excluding="**" output="src/test/resources" kind="src" path="src/test/resources"/>
+ <classpathentry excluding="**" kind="src" output="src/main/resources/templates" path="src/main/resources/templates"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
Modified: maven/trunk/ogoglio-common/pom.xml
===================================================================
--- maven/trunk/ogoglio-common/pom.xml 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-common/pom.xml 2007-08-29 20:55:24 UTC (rev 290)
@@ -13,14 +13,7 @@
<build>
<resources>
<!-- FILTER RESOURCES FOR SOME CONSTANTS-->
- <!--
<resource>
- <directory>src/main/resources/testing_constants</directory>
- <filtering>true</filtering>
- </resource>
- -->
-
- <resource>
<targetPath>avatar</targetPath>
<directory>src/main/resources/avatar</directory>
</resource>
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/PropStorage.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/PropStorage.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/PropStorage.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -0,0 +1,55 @@
+package com.ogoglio.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Properties;
+
+/*
+ * This is used by test and utility code to manipulate the DB and avoid having production
+ * jars that contain property files that have private information.
+ */
+public class PropStorage {
+
+ public static final String TEST_CONFIG_PROPS="test-config.properties";
+ public static final String BOOTSTRAP_PROPS="bootstrap.properties";
+ public static final String BASIC_PROPS = "basic-config.properties";
+
+
+
+ private Map propMap = new HashMap();
+
+ public PropStorage() {}
+
+ public boolean loadPropertySet(String propsetNameAndPath) {
+ if (!propMap.containsKey(propsetNameAndPath)) {
+ InputStream is;
+ is = UIConstants.class.getClassLoader().getResourceAsStream(propsetNameAndPath);
+ if (is== null) {
+ is= UIConstants.class.getResourceAsStream(propsetNameAndPath);
+ }
+ if (is==null) {
+ return false;
+ }
+ Properties props=new Properties();
+ try {
+ props.load(is);
+ propMap.put(propsetNameAndPath,props);
+ } catch (IOException e) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ public String getKeyFromSet(String propSetName, String key) {
+ Properties props=(Properties)propMap.get(propSetName);
+ return props.getProperty(key);
+ }
+
+ public Properties getAllProps(String propsetNameAndPath) {
+ return (Properties)propMap.get(propsetNameAndPath);
+ }
+
+}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/WebConstants.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/WebConstants.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/WebConstants.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -1,8 +1,5 @@
package com.ogoglio.util;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.Properties;
public class WebConstants {
public static final String AUTH_USERNAME_PARAM = "username";
Modified: maven/trunk/ogoglio-integration-test/pom.xml
===================================================================
--- maven/trunk/ogoglio-integration-test/pom.xml 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-integration-test/pom.xml 2007-08-29 20:55:24 UTC (rev 290)
@@ -9,13 +9,23 @@
<packaging>pom</packaging>
<build>
+ <!-- -->
+ <!-- TEST RESOURCES -->
+ <!-- -->
<testResources>
<testResource>
- <targetPath></targetPath>
- <directory>src/test/resources/</directory>
+ <directory>src/test/resources</directory>
<filtering>true</filtering>
+ <includes>
+ <include>test-config.properties</include>
+ <include>basic-config.properties</include>
+ <include>bootstrap.properties</include>
+ <include>mail/*</include>
+ <include>sample-art3d/*</include>
+ </includes>
</testResource>
</testResources>
+
<plugins>
<!-- COMPILER needed b/c POM packaging by default doesn't build the tests -->
<plugin>
@@ -99,8 +109,10 @@
<goals>
<goal>stop</goal>
</goals>
+
<configuration>
<wait>true</wait>
+ <type>runtime</type>
</configuration>
</execution>
<execution>
@@ -110,7 +122,8 @@
<goals>
<goal>stop</goal>
</goals>
- <configuration>
+ <configuration>
+ <type>runtime</type>
<wait>false</wait>
</configuration>
</execution>
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -41,8 +41,10 @@
import com.ogoglio.client.model.SplinePath;
import com.ogoglio.client.model.Thing;
import com.ogoglio.client.model.User;
+import com.ogoglio.util.PropStorage;
import com.ogoglio.util.StreamUtils;
import com.ogoglio.util.WebConstants;
+import com.ogoglio.viewer.render.UIConstants;
import com.ogoglio.xml.AccountDocument;
import com.ogoglio.xml.AuthDocument;
import com.ogoglio.xml.BodyDocument;
@@ -97,7 +99,15 @@
public void testWebAdmin() {
try {
- WebAPIAuthenticator adminAuthenticator = new WebAPIAuthenticatorFactory().authenticate(wire1, descriptor1, BootstrapInfo.getBootstrapUsername(), BootstrapInfo.getBootstrapUserPW());
+ PropStorage ps=new PropStorage();
+ if (ps.loadPropertySet(PropStorage.BOOTSTRAP_PROPS)==false) {
+ fail("unable to load properties bootstrap.properties!");
+ }
+
+ WebAPIAuthenticator adminAuthenticator = new WebAPIAuthenticatorFactory().authenticate(wire1, descriptor1,
+ ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUser"),
+ ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUserPW"));
+
assertNotNull("got null auth cookie", adminAuthenticator.getAuthCookie());
WebAPIClient adminWebClient = new WebAPIClient(descriptor1, adminAuthenticator, wire1);
@@ -240,7 +250,7 @@
private UserDocument[] verifyUserDocsBySize(WebAPIClient webClient1, long spaceID, int expectedLen, String expectedUsername) throws IOException {
UserDocument[] userDocs = webClient1.getUserDocuments(spaceID);
- assertTrue(userDocs.length == expectedLen);
+ assertEquals(expectedLen,userDocs.length);
if (expectedUsername != null) {
assertEquals(expectedUsername, userDocs[0].getUsername());
}
@@ -422,6 +432,7 @@
SpaceClient guestSpaceClient1 = new SpaceClient(spaceID, serviceURI1, guestCookie1, new TestSpaceClientListener());
try {
Thread.sleep(1000);
+ Thread.yield();
} catch (InterruptedException e) {
e.printStackTrace();
}
@@ -533,11 +544,10 @@
String CUBE_GIF = "TestCube.gif";
String CUBE_MATERIAL = "TestCube.mtl";
- Class clazz = getClass();
- webClient1.uploadTemplateGeometryStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), 0, clazz.getResourceAsStream("/sample-art3d/TestCube.obj"));
- webClient1.uploadTemplateResourceStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), CUBE_MATERIAL, clazz.getResourceAsStream("/sample-art3d/TestCube.mtl"));
- webClient1.uploadTemplateResourceStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), CUBE_GIF, clazz.getResourceAsStream("/sample-art3d/TestCube.gif"));
- webClient1.updateTemplateScript(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), StreamUtils.readInput(clazz.getResourceAsStream("/sample-art3d/TestCube.js")));
+ webClient1.uploadTemplateGeometryStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), 0, UIConstants.getResource("sample-art3d/TestCube.obj"));
+ webClient1.uploadTemplateResourceStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), CUBE_MATERIAL, UIConstants.getResource("sample-art3d/TestCube.mtl"));
+ webClient1.uploadTemplateResourceStream(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), CUBE_GIF, UIConstants.getResource("sample-art3d/TestCube.gif"));
+ webClient1.updateTemplateScript(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID(), StreamUtils.readInput(UIConstants.getResource("sample-art3d/TestCube.js")));
baseDoc = webClient1.getTemplateDocument(newTemplateDoc.getOwnerUsername(), newTemplateDoc.getTemplateID());
//make sure the sequence right above didn't take more than 1 sec
Added: maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties (rev 0)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-08-29 20:55:24 UTC (rev 290)
@@ -0,0 +1,4 @@
+# basic info needed for some tests
+ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
+ogoglio.baseUrl = ${ogoglio.baseURL}
+
Added: maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties (rev 0)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties 2007-08-29 20:55:24 UTC (rev 290)
@@ -0,0 +1,2 @@
+bootstrapUser=${ogoglio.bootstrapUser}
+bootstrapUserPW=${ogoglio.bootstrapUserPW}
Added: maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties (rev 0)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties 2007-08-29 20:55:24 UTC (rev 290)
@@ -0,0 +1,28 @@
+# this is needed for running tests because tomcat isn't
+# actually around when these tests get run so we need
+# to use the DB via the simple c3po connection manager
+# (supplied with hibernate)
+
+hibernate.connection.driver_class = com.mysql.jdbc.Driver
+hibernate.connection.url = ${ogoglio.mysql.url}
+hibernate.connection.username = ${ogoglio.mysql.user}
+hibernate.connection.password = ${ogoglio.mysql.password}
+hibernate.show_sql=false
+hibernate.dialect=org.hibernate.dialect.MySQLDialect
+
+#copied from the web
+#hibernate.c3p0.min_size=5
+#hibernate.c3p0.max_size=20
+#hibernate.c3p0.timeout=1800
+#hibernate.c3p0.max_statements=50
+
+#for doing tests that need bootstrap
+ogoglio.baseURL=${ogoglio.baseURL}
+ogoglio.bootstrapUser=${ogoglio.bootstrapUser}
+ogoglio.bootstrapUserPW=${ogoglio.bootstrapUserPW}
+
+#can destroy the db?
+ogoglio.okToZapDB=${ogoglio.okToZapDB}
+#can migrate data?
+ogoglio.okToMigrateDB=${ogoglio.okToMigrateDB}
+
Modified: maven/trunk/ogoglio-server/.classpath
===================================================================
--- maven/trunk/ogoglio-server/.classpath 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-server/.classpath 2007-08-29 20:55:24 UTC (rev 290)
@@ -1,9 +1,14 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
+ <classpathentry kind="src" path="src/main/java"/>
+ <classpathentry kind="src" path="src/test/java"/>
+ <classpathentry excluding="**" kind="src" output="src/main/resources/hibernate" path="src/main/resources/hibernate"/>
+ <classpathentry excluding="**" kind="src" output="src/main/resources/log4j" path="src/main/resources/log4j"/>
+ <classpathentry excluding="**" kind="src" output="src/test/resources" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
- <attribute value="/usr/local/jdk1.5.0_12/jre/lib/i386" name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY"/>
+ <attribute name="org.eclipse.jdt.launching.CLASSPATH_ATTR_LIBRARY_PATH_ENTRY" value="/usr/local/jdk1.5.0_12/jre/lib/i386"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-server/pom.xml 2007-08-29 20:55:24 UTC (rev 290)
@@ -65,6 +65,8 @@
<filtering>true</filtering>
<includes>
<include>test-config.properties</include>
+ <include>basic-config.properties</include>
+ <include>bootstrap.properties</include>
<include>mail/*</include>
<include>templates/*</include>
</includes>
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-08-29 00:48:02 UTC (rev 289)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-08-29 20:55:24 UTC (rev 290)
@@ -1,7 +1,6 @@
package com.ogoglio.migrate;
impo...
[truncated message content] |
|
From: <ian...@us...> - 2007-08-29 21:44:04
|
Revision: 291
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=291&view=rev
Author: iansmith
Date: 2007-08-29 14:43:58 -0700 (Wed, 29 Aug 2007)
Log Message:
-----------
Removed file leftover from merge.
Reorganized servlet heirarchy in appdev to accomodate transmutable.
Whitespace changes in context.xml. sheesh.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
Removed Paths:
-------------
maven/trunk/ogoglio-integration-test/src/test/resources/bootstrapUser.properties
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-08-29 20:55:24 UTC (rev 290)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-08-29 21:43:58 UTC (rev 291)
@@ -20,7 +20,7 @@
import com.ogoglio.util.ArgumentUtils;
import com.ogoglio.xml.AuthDocument;
-public abstract class AbstractRemoteServlet extends AbstractResourceServlet {
+public abstract class AbstractRemoteServlet extends MigratedResourceServlet {
private WebAPIClient ogoglioClient = null;
Deleted: maven/trunk/ogoglio-integration-test/src/test/resources/bootstrapUser.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/bootstrapUser.properties 2007-08-29 20:55:24 UTC (rev 290)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/bootstrapUser.properties 2007-08-29 21:43:58 UTC (rev 291)
@@ -1,2 +0,0 @@
-bootstrapUser=${ogoglio.bootstrapUser}
-bootstrapUserPW=${ogoglio.bootstrapUserPW}
Modified: maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-08-29 20:55:24 UTC (rev 290)
+++ maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-08-29 21:43:58 UTC (rev 291)
@@ -14,6 +14,7 @@
show_sql="false"
maxIdle="5"
maxActive="50" />
+
<Environment name="ogoglio/oktoZapDB" value="false" type="java.lang.String"/> <!-- not running tests! -->
<Environment name="ogoglio/okToMigrateDB" value="${ogoglio.okToMigrateDB}" type="java.lang.String"/>
<Environment name="ogoglio/mediaURL" value="${ogoglio.mediaURL}" type="java.lang.String"/>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-08-30 19:00:25
|
Revision: 296
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=296&view=rev
Author: iansmith
Date: 2007-08-30 12:00:17 -0700 (Thu, 30 Aug 2007)
Log Message:
-----------
Added support for multiple, different versioning of the database code. Needed to support multiple apps.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/.classpath
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties
maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/OgoglioServerMigration.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
maven/trunk/ogoglio-server/src/main/resources/hibernate/hibernate.cfg.xml
maven/trunk/ogoglio-server/src/test/resources/bootstrap.properties
maven/trunk/ogoglio-server/src/test/resources/test-config.properties
Removed Paths:
-------------
maven/trunk/ogoglio-appdev/src/test/resources/
Modified: maven/trunk/ogoglio-appdev/.classpath
===================================================================
--- maven/trunk/ogoglio-appdev/.classpath 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-appdev/.classpath 2007-08-30 19:00:17 UTC (rev 296)
@@ -3,7 +3,6 @@
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
<classpathentry excluding="**" kind="src" output="src/main/resources" path="src/main/resources"/>
- <classpathentry excluding="**" kind="src" output="src/test/resources" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/Migration.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -1,12 +1,12 @@
package com.ogoglio.appdev.migrate;
-import java.util.Properties;
-
import javax.naming.Context;
import javax.servlet.ServletConfig;
import org.hibernate.SessionFactory;
+import com.ogoglio.appdev.persist.PersistException;
+
public interface Migration {
/*
@@ -16,7 +16,8 @@
*
* Return false if things went wrong.
*/
- public boolean patch(SessionFactory sessionFactory, ServletConfig servletConfig, Context ctx, int from, int to);
+ public boolean patch(SessionFactory sessionFactory, ServletConfig servletConfig, Context ctx,
+ int from, int to) throws PersistException;
/*O
* The receiver should use this call to populate the database with data that would be useful
@@ -24,6 +25,6 @@
*
* Return false if things went wrong.
*/
- public boolean populate(SessionFactory sessionFactory, int from, int to);
+ public boolean populate(SessionFactory sessionFactory, int from, int to) throws PersistException;
}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -24,17 +24,18 @@
public MigrationSupport() {
}
- public abstract int versionNumber();
- public abstract Migration[] migrationList();
+ public abstract int getVersionNumber();
+ public abstract Migration[] getMigrationList();
+ public abstract String getResourcePath();
public boolean verifyVersion(ServletConfig servletConf, Context ctx) {
try {
SessionFactory sessionFactory = getCurrentConfiguration().buildSessionFactory();
int version = DBVersionPersistTasks.findVersion(sessionFactory);
- if (version != versionNumber()) {
- System.err.println("DB Version Mismatch! Expected (" + versionNumber() + ") but got " + version + "!");
+ if (version != getVersionNumber()) {
+ System.err.println("DB Version Mismatch! Expected (" + getVersionNumber() + ") but got " + version + "!");
sessionFactory.close();
- return tryUpgrade(servletConf, ctx, version, versionNumber(),
+ return tryUpgrade(servletConf, ctx, version, getVersionNumber(),
DDL_MODE_UPDATE, true, null);
}
sessionFactory.close();
@@ -69,11 +70,11 @@
if (!initVersionOnly(true,null)) {
return false;
}
- return tryUpgrade(conf, ctx, 0, versionNumber(), DDL_MODE_UPDATE, true,null);
+ return tryUpgrade(conf, ctx, 0, getVersionNumber(), DDL_MODE_UPDATE, true,null);
}
public Configuration getCurrentConfiguration() {
- return createConfigurationForHibernate(versionNumber(), null, true, null);
+ return createConfigurationForHibernate(getVersionNumber(), null, true, null);
}
public Configuration createConfigurationForHibernate(int num, String autoSetting, boolean useJNDI, PropStorage ps) {
@@ -86,7 +87,7 @@
} else {
configuration.addProperties(ps.getAllProps(PropStorage.TEST_CONFIG_PROPS));
}
- configuration.addInputStream(UIConstants.getResource("com/ogoglio/migrate/migration-" + num + ".xml"));
+ configuration.addInputStream(UIConstants.getResource(getResourcePath()+"/migration-" + num + ".xml"));
return configuration.configure();
}
@@ -101,8 +102,8 @@
public boolean tryUpgrade(ServletConfig servletConfig, Context ctx, int db_is,
int db_wants_to_be, boolean isUpdate, boolean useJNDI, PropStorage propStore) {
- if (migrationList().length != versionNumber()) {
- System.out.println("Internal error! Migration list length should be " + versionNumber() + " but is " + migrationList().length + "!");
+ if (getMigrationList().length != getVersionNumber()) {
+ System.out.println("Internal error! Migration list length should be " + getVersionNumber() + " but is " + getMigrationList().length + "!");
return false;
}
boolean canMigrate = false;
@@ -134,9 +135,9 @@
for (int i = db_is; i < db_wants_to_be; ++i) {
- Migration current = migrationList()[i];
+ Migration current = getMigrationList()[i];
System.out.println("------------------------------------------------\n");
- System.out.println("DB: Attempting migration from " + i + " to " + (i + 1) + "...");
+ System.out.println("DB: Attempting migration from " + i + " to " + (i + 1) + " with auto HBM:"+hbm_auto_flag);
//try to get hibernate to do the work
Configuration config = createConfigurationForHibernate(i + 1, hbm_auto_flag, useJNDI, propStore);
@@ -149,21 +150,30 @@
}
setVersionNumberOfDbViaQuery(factory, i + 1, expectedRecords);
- if (!current.patch(factory, servletConfig, ctx, i, i + 1)) {
- factory.close();
- return false;
- }
-
- if (!isUpdate) {
- //we need to go ahead and create the data
- if (!current.populate(factory, i, i+1)) {
- System.out.println("FART: Whoa! Populate failed!"+i);
+ try {
+ if (!current.patch(factory, servletConfig, ctx, i, i + 1)) {
factory.close();
return false;
}
- System.out.println("FART: Populate ok!"+i);
+ } catch (PersistException e) {
+ System.err.println("Whoa! Patch failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ System.err.println("Whoa! Persistance layer problem was:"+e.getMessage());
}
+ try {
+ if (!isUpdate) {
+ //we need to go ahead and create the data
+ if (!current.populate(factory, i, i+1)) {
+ System.err.println("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ factory.close();
+ return false;
+ }
+ }
+ } catch (PersistException e) {
+ System.err.println("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ System.err.println("Whoa! Persistance layer problem was:"+e.getMessage());
+ }
+
factory.close();
System.out.println("------------------------------------------------\n");
}
@@ -180,6 +190,6 @@
return false;
}
- return tryUpgrade(null, null, 0, versionNumber(), DDL_MODE_CREATE, false, ps);
+ return tryUpgrade(null, null, 0, getVersionNumber(), DDL_MODE_CREATE, false, ps);
}
}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -28,7 +28,7 @@
}
//if we are here, db stuff worked, but we still need to avoid all the jndi stuff
- sessionFactory = support.createConfigurationForHibernate(getMigrationSupport().versionNumber(), null, false, ps).buildSessionFactory();
+ sessionFactory = support.createConfigurationForHibernate(getMigrationSupport().getVersionNumber(), null, false, ps).buildSessionFactory();
} catch (Exception e) {
System.out.println("-------");
e.printStackTrace(System.out);
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -62,7 +62,6 @@
throw new ServletException("Failed because of Ogoglio service auth failure: " + e);
}
}
-
super.service(request, response);
}
Modified: maven/trunk/ogoglio-integration-test/pom.xml
===================================================================
--- maven/trunk/ogoglio-integration-test/pom.xml 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-integration-test/pom.xml 2007-08-30 19:00:17 UTC (rev 296)
@@ -3,7 +3,7 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <groupId>ogoglio-integration-test</groupId>
+ <groupId>com.ogoglio</groupId>
<artifactId>ogoglio-integration-test</artifactId>
<version>0.0.1</version>
<packaging>pom</packaging>
Modified: maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/bootstrap.properties 2007-08-30 19:00:17 UTC (rev 296)
@@ -1,2 +1,4 @@
+allBootstrapUsers=${ogoglio.allBootstrapUsers}
+allBootstrapUsersPW=${ogoglio.allBootstrapUsersPW}
bootstrapUser=${ogoglio.bootstrapUser}
bootstrapUserPW=${ogoglio.bootstrapUserPW}
Modified: maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/test-config.properties 2007-08-30 19:00:17 UTC (rev 296)
@@ -18,6 +18,8 @@
#for doing tests that need bootstrap
ogoglio.baseURL=${ogoglio.baseURL}
+ogoglio.allBootstrapUsers=${ogoglio.allBootstrapUsers}
+ogoglio.allBootstrapUsersPW=${ogoglio.allBootstrapUsersPW}
ogoglio.bootstrapUser=${ogoglio.bootstrapUser}
ogoglio.bootstrapUserPW=${ogoglio.bootstrapUserPW}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -1,6 +1,7 @@
package com.ogoglio.migrate;
import java.net.URI;
+import java.util.regex.Pattern;
import javax.naming.Context;
import javax.servlet.ServletConfig;
@@ -8,6 +9,7 @@
import org.hibernate.SessionFactory;
import com.ogoglio.appdev.migrate.Migration;
+import com.ogoglio.appdev.persist.PersistException;
import com.ogoglio.persist.ServiceInitializationPersistTasks;
import com.ogoglio.util.PropStorage;
@@ -17,7 +19,7 @@
public boolean patch(SessionFactory sessionFactory, ServletConfig config, Context ctx, int from, int to) {
return true;
}
- public boolean populate(SessionFactory sessionFactory, int from, int to) {
+ public boolean populate(SessionFactory sessionFactory, int from, int to) throws PersistException{
if ((from != 0) || (to != 1)) {
System.out.println("Migration called in the wrong place! Expected 0->1 but was:" + from + "->" + to + "!");
@@ -26,35 +28,40 @@
}
try {
- String uriString, user, pw;
+ String uriString, users, pws;
PropStorage zap=new PropStorage();
- System.out.println("FART1--->populate:"+(zap.loadPropertySet(PropStorage.BOOTSTRAP_PROPS))+","+
- zap.loadPropertySet(PropStorage.BASIC_PROPS));
-
if (zap.loadPropertySet(PropStorage.BOOTSTRAP_PROPS)==false) {
return false;
}
if (zap.loadPropertySet(PropStorage.BASIC_PROPS)==false) {
return false;
}
- System.out.println("FART2--->populate:");
uriString = zap.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseUrl");
- user=zap.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUser");
- pw=zap.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUserPW");
+ users=zap.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "allBootstrapUsers");
+ pws=zap.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "allBootstrapUsersPW");
- if ((uriString==null) || (user==null) || (pw==null)) {
- System.out.println("URI FART:"+(uriString==null));
- System.out.println("USER FART:"+(user==null));
- System.out.println("PW FART:"+(pw==null));
+ if ((uriString==null) || (users==null) || (pws==null)) {
+ System.err.println("URI Offender in settings.xml:"+(uriString==null));
+ System.err.println("USERS Offender in settings.xml:"+(users==null));
+ System.err.println("PWS Offender in settings.xml:"+(pws==null));
return false;
}
+
+ String[] userList = users.split(Pattern.quote(","));
+ String[] pwList = pws.split(Pattern.quote(","));
- System.out.println("FART3--->uriString:"+uriString);
+ if (userList.length!=pwList.length) {
+ System.err.println("Whoa! Settings.xml gave us a bootstrap user list and pw list of different lengths!");
+ return false;
+ }
URI uri = new URI(uriString);
- //actual work
+
+ for (int i=0; i<userList.length;++i) {
+ ServiceInitializationPersistTasks.initializeBootstrapAccount(sessionFactory, uri.getHost(), userList[i], pwList[i]);
+ }
+
ServiceInitializationPersistTasks.initializeLocalSim(uri, sessionFactory);
- ServiceInitializationPersistTasks.initializeBootstrapAccount(sessionFactory, uri.getHost(), user, pw);
ServiceInitializationPersistTasks.initializeServiceState(sessionFactory);
return true;
} catch (Exception e) {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/OgoglioServerMigration.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/OgoglioServerMigration.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/OgoglioServerMigration.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -13,14 +13,16 @@
// this is the set of semantic migrations, in order
private static final Migration[] migration = { new AccountsForTesting() };
- public Migration[] migrationList() {
+ public Migration[] getMigrationList() {
return migration;
}
- public int versionNumber() {
+ public int getVersionNumber() {
return DB_VERSION_NUMBER;
}
+ public String getResourcePath() { return "com/ogoglio/migrate"; }
+
private OgoglioServerMigration() {
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -42,7 +42,7 @@
if (accountRec != null) {
return;
}
- accountRec = AccountPersistTasks.createAccount(user, "admin", "library@"+host, sessionFactory);
+ accountRec = AccountPersistTasks.createAccount(user, "admin", user+"@"+host, sessionFactory);
accountRec.setPassword(pw);
AccountPersistTasks.update(accountRec, sessionFactory);
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-08-30 19:00:17 UTC (rev 296)
@@ -321,21 +321,17 @@
public void doPost(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
long spaceID = Long.parseLong(pathElements[2]);
try {
- System.out.println("do POST fart: SIM:"+spaceID);
SpaceRecord spaceRecord = SpacePersistTasks.findSpaceBySpaceID(spaceID, getSessionFactory());
if (spaceRecord == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
- System.out.println("do POST2 fart: SIM:"+spaceID);
-
AccountRecord authedAccount = AuthServlet.getAuthedAccountRecord(request, getSessionFactory());
if (authedAccount != null && !authedAccount.getUsername().equals(spaceRecord.getOwnerUsername())) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
- System.out.println("do POST3 fart: authed acct:"+authedAccount.getUsername());
String value = getFirstStringValue(request);
if (value == null || value.trim().length() == 0) {
System.err.println("Posted null value: " + request.getContentType());
@@ -343,11 +339,9 @@
return;
}
- System.out.println("do POST4 fart: value:"+value);
SpaceSimulator simulator = sim.getOrCreateSpaceSimulator(spaceRecord);
simulator.putSetting(pathElements[pathElements.length - 1], value);
sendStringResponse(value, "text/plain", response);
- System.out.println("do POST5 fart: value:"+value);
} catch (PersistException e) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
Modified: maven/trunk/ogoglio-server/src/main/resources/hibernate/hibernate.cfg.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/resources/hibernate/hibernate.cfg.xml 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/main/resources/hibernate/hibernate.cfg.xml 2007-08-30 19:00:17 UTC (rev 296)
@@ -9,13 +9,10 @@
<hibernate-configuration>
<session-factory>
- <!-- to use JNDI to find the data source -->
- <!-- we expect this context (java:comp/env) to have been created by the abstract resource servlet AND we expect the
- particular value (jdbc/space) to have been created in the context.xml of the server -->
- <!--
- <property name="connection.datasource">java:comp/env/jdbc/space</property>
- <property name="show_sql">false</property>
+ <!-- only mysql supported now
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
+ <property name="show_sql">true</property>
-->
+
</session-factory>
</hibernate-configuration>
Modified: maven/trunk/ogoglio-server/src/test/resources/bootstrap.properties
===================================================================
--- maven/trunk/ogoglio-server/src/test/resources/bootstrap.properties 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/test/resources/bootstrap.properties 2007-08-30 19:00:17 UTC (rev 296)
@@ -1,2 +1,4 @@
+allBootstrapUsers=${ogoglio.allBootstrapUsers}
+allBootstrapUsersPW=${ogoglio.allBootstrapUsersPW}
bootstrapUser=${ogoglio.bootstrapUser}
bootstrapUserPW=${ogoglio.bootstrapUserPW}
Modified: maven/trunk/ogoglio-server/src/test/resources/test-config.properties
===================================================================
--- maven/trunk/ogoglio-server/src/test/resources/test-config.properties 2007-08-30 00:59:14 UTC (rev 295)
+++ maven/trunk/ogoglio-server/src/test/resources/test-config.properties 2007-08-30 19:00:17 UTC (rev 296)
@@ -18,6 +18,8 @@
#for doing tests that need bootstrap
ogoglio.baseURL=${ogoglio.baseURL}
+ogoglio.allBootstrapUsers=${ogoglio.allBootstrapUsers}
+ogoglio.allBootstrapUsersPW=${ogoglio.allBootstrapUsersPW}
ogoglio.bootstrapUser=${ogoglio.bootstrapUser}
ogoglio.bootstrapUserPW=${ogoglio.bootstrapUserPW}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-02 20:29:37
|
Revision: 339
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=339&view=rev
Author: iansmith
Date: 2007-09-02 13:29:33 -0700 (Sun, 02 Sep 2007)
Log Message:
-----------
Converted ogoglio to use a master pom arrangement.
Modified Paths:
--------------
maven/trunk/dev-plugins/pom.xml
maven/trunk/dev-plugins/src/main/java/com/transmutable/plugin/StaticVelocitySitePlugin.java
maven/trunk/ogoglio/pom.xml
maven/trunk/ogoglio-appdev/pom.xml
maven/trunk/ogoglio-body-editor-applet/pom.xml
maven/trunk/ogoglio-common/.classpath
maven/trunk/ogoglio-common/pom.xml
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-test-applet/pom.xml
maven/trunk/ogoglio-viewer-applet/pom.xml
Property Changed:
----------------
maven/trunk/ogoglio/
Modified: maven/trunk/dev-plugins/pom.xml
===================================================================
--- maven/trunk/dev-plugins/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/dev-plugins/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -1,36 +1,44 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
- <artifactId>dev-plugins</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>maven-plugin</packaging>
-
- <build>
- <plugins>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-surefire-plugin</artifactId>
- <configuration>
- <skip>true</skip><!-- this is critical to avoid running unit tests -->
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>org.apache.maven</groupId>
- <artifactId>maven-plugin-api</artifactId>
- <version>2.0</version>
- </dependency>
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
- <dependency>
- <groupId>org.apache.velocity</groupId>
- <artifactId>velocity</artifactId>
- <version>1.5</version>
- </dependency>
- </dependencies>
-
-</project>
-
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
+ <artifactId>dev-plugins</artifactId>
+ <packaging>maven-plugin</packaging>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip><!-- this is critical to avoid running unit tests -->
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.maven</groupId>
+ <artifactId>maven-plugin-api</artifactId>
+ <version>2.0</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.velocity</groupId>
+ <artifactId>velocity</artifactId>
+ <version>1.5</version>
+ </dependency>
+ </dependencies>
+
+</project>
+
Modified: maven/trunk/dev-plugins/src/main/java/com/transmutable/plugin/StaticVelocitySitePlugin.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/transmutable/plugin/StaticVelocitySitePlugin.java 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/dev-plugins/src/main/java/com/transmutable/plugin/StaticVelocitySitePlugin.java 2007-09-02 20:29:33 UTC (rev 339)
@@ -30,7 +30,14 @@
private File targetDirectory;
public void execute() throws MojoExecutionException {
-
+ if (templateDirectory==null) {
+ getLog().warn("No velocity templates configured!");
+ return;
+ } else if ((!templateDirectory.exists()) || (!templateDirectory.canRead())) {
+ getLog().warn("Can't find any velocity templates to compile!");
+ return;
+ }
+
if (targetDirectory.exists()==false) {
if (targetDirectory.mkdir()==false) {
getLog().error("Unable to create target directory:"+targetDirectory.getName());
Property changes on: maven/trunk/ogoglio
___________________________________________________________________
Name: svn:ignore
- target
+ target
tomcat5x.out
Modified: maven/trunk/ogoglio/pom.xml
===================================================================
--- maven/trunk/ogoglio/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -8,46 +8,135 @@
<version>0.0.1-SNAPSHOT</version>
<packaging>pom</packaging>
+ <profiles>
+ <profile>
+ <id>boot-server</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.cargo</groupId>
+ <artifactId>cargo-maven2-plugin</artifactId>
+ <version>0.3-SNAPSHOT</version>
+ <!-- CARGO INTERACTIONS WITH TOMCAT FOR BOOTING SERVER ONLY -->
+ <configuration>
+ <!-- tomcat 5.5 running on the same machine...-->
+ <container>
+ <containerId>tomcat5x</containerId>
+ <home>${cargo.tomcat5x.home}</home>
+ <log>${basedir}/tomcat5x.log</log>
+ <output>${basedir}/tomcat5x.out</output>
+ </container>
+ <!-- tomcat configuration -->
+ <configuration>
+ <type>standalone</type>
+ <home>${ogoglio.tmp.tomcat5x}</home>
+ <properties>
+ <cargo.servlet.port>
+ 8080
+ </cargo.servlet.port>
+ </properties>
+ </configuration>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>all</id>
+ <modules>
+ <module>../ogoglio-appdev</module>
+ <module>../ogoglio-body-editor-applet</module>
+ <module>../ogoglio-common</module>
+ <module>../ogoglio-test-applet</module>
+ <module>../ogoglio-viewer-applet</module>
+ <module>../ogoglio-server</module>
+ <module>../ogoglio-integration-test</module>
+ <module>../dev-plugins</module>
+ </modules>
+ </profile>
+ <profile>
+ <id>client-side</id>
+ <modules>
+ <module>../ogoglio-appdev</module>
+ <module>../ogoglio-body-editor-applet</module>
+ <module>../ogoglio-common</module>
+ <module>../ogoglio-test-applet</module>
+ <module>../ogoglio-viewer-applet</module>
+ <module>../dev-plugins</module>
+ </modules>
+ </profile>
+ <profile>
+ <id>server-side</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.codehaus.cargo</groupId>
+ <artifactId>cargo-maven2-plugin</artifactId>
+ <version>0.3-SNAPSHOT</version>
+ <executions>
+ <execution>
+ <id>server-side</id>
+ <inherited>true</inherited>
+ <phase>install</phase>
+ <goals>
+ <goal>deploy</goal>
+ </goals>
+ <configuration>
+ <container>
+ <containerId>
+ tomcat5x
+ </containerId>
+ </container>
+ <!-- Configuration to use with the container -->
+ <configuration>
+ <type>existing</type>
+ <home>
+ ${ogoglio.tmp.tomcat5x}
+ </home>
+ </configuration>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <skip>true</skip>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <modules>
+ <module>../ogoglio-server</module>
+ </modules>
+ </profile>
+ <profile>
+ <id>integration-test</id>
+ <modules>
+ <module>../ogoglio-integration-test</module>
+ </modules>
+ </profile>
+ </profiles>
+
+ <distributionManagement>
+ <snapshotRepository>
+ <id>local-disk</id>
+ <uniqueVersion>false</uniqueVersion>
+ <name>local disk</name>
+ <url>${my.local.repo}</url>
+ </snapshotRepository>
+ </distributionManagement>
+
<build>
<plugins>
- <!-- CARGO INTERACTIONS WITH TOMCAT -->
+ <!-- solves the problem with java3d not being able to link due to isolated classloader -->
<plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>0.3-SNAPSHOT</version>
- <!-- CARGO CONFIG -->
+ <artifactId>maven-surefire-plugin</artifactId>
<configuration>
- <!-- tomcat 5.5 running on the same machine...-->
- <container>
- <containerId>tomcat5x</containerId>
- <home>${cargo.tomcat5x.home}</home>
- <log>${project.build.directory}/tomcat5x.log</log>
- <output>${project.build.directory}/tomcat5x.out</output>
- </container>
-
- <!-- tomcat configuration -->
- <configuration>
- <type>standalone</type>
- <home>${ogoglio.tmp.tomcat5x}</home>
- <properties>
- <cargo.servlet.port>
- 8080
- </cargo.servlet.port>
- </properties>
- </configuration>
+ <childDelegation>true</childDelegation>
</configuration>
</plugin>
</plugins>
</build>
- <modules>
- <module>../ogoglio-appdev</module>
- <module>../ogoglio-body-editor-applet</module>
- <module>../ogoglio-common</module>
- <module>../ogoglio-integration-test</module>
- <module>../ogoglio-server</module>
- <module>../ogoglio-test-applet</module>
- <module>../ogoglio-viewer-applet</module>
- </modules>
-
</project>
Modified: maven/trunk/ogoglio-appdev/pom.xml
===================================================================
--- maven/trunk/ogoglio-appdev/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-appdev/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -2,12 +2,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
- <modelVersion>4.0.0</modelVersion>
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-appdev</artifactId>
- <packaging>jar</packaging>
- <version>0.0.1</version>
<dependencies>
<dependency>
Modified: maven/trunk/ogoglio-body-editor-applet/pom.xml
===================================================================
--- maven/trunk/ogoglio-body-editor-applet/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-body-editor-applet/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -2,58 +2,17 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
-
<modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
+
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-body-editor-applet</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <build>
- <plugins>
- </plugins>
- </build>
- <profiles>
- <!-- LINUX -->
- <profile>
- <id>linux</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- </profile>
- <!-- OSX -->
- <profile>
- <id>osx</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-
<dependencies>
<!-- ogoglio -->
<dependency>
Modified: maven/trunk/ogoglio-common/.classpath
===================================================================
--- maven/trunk/ogoglio-common/.classpath 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-common/.classpath 2007-09-02 20:29:33 UTC (rev 339)
@@ -2,7 +2,9 @@
<classpath>
<classpathentry kind="src" path="src/main/java"/>
<classpathentry kind="src" path="src/test/java"/>
+ <classpathentry excluding="**" kind="src" output="src/main/resources/avatar" path="src/main/resources/avatar"/>
<classpathentry excluding="**" kind="src" output="src/main/resources/templates" path="src/main/resources/templates"/>
+ <classpathentry excluding="**" kind="src" output="src/test/resources" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER"/>
<classpathentry kind="output" path="target/classes"/>
Modified: maven/trunk/ogoglio-common/pom.xml
===================================================================
--- maven/trunk/ogoglio-common/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-common/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -5,65 +5,15 @@
<modelVersion>4.0.0</modelVersion>
<!-- About this project -->
- <groupId>com.ogoglio</groupId>
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-common</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <profiles>
- <!-- LINUX -->
- <profile>
- <id>linux</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.5.1</version>
- <scope>supplied</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core-utils</artifactId>
- <version>1.5.1</version>
- <scope>supplied</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.5.1</version>
- <scope>supplied</scope>
- </dependency>
- </dependencies>
- </profile>
- <!-- OSX -->
- <profile>
- <id>osx</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.3</version>
- <scope>supplied</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core-utils</artifactId>
- <version>1.3</version>
- <scope>supplied</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.3</version>
- <scope>supplied</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-
<build>
-
<resources>
<!-- FILTER RESOURCES FOR SOME CONSTANTS-->
<resource>
@@ -71,6 +21,7 @@
<directory>src/main/resources/avatar</directory>
</resource>
+ <!-- for loading indicator -->
<resource>
<targetPath>templates</targetPath>
<directory>src/main/resources/templates</directory>
Modified: maven/trunk/ogoglio-integration-test/pom.xml
===================================================================
--- maven/trunk/ogoglio-integration-test/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-integration-test/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -4,10 +4,26 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
+
+ <profiles>
+ <profile>
+ <id>integration-test</id>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ </activation>
+ </profile>
+ </profiles>
+
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-integration-test</artifactId>
<packaging>pom</packaging>
- <version>0.0.1-SNAPSHOT</version>
+
<build>
<testResources>
<testResource>
@@ -17,6 +33,12 @@
<include>test-config.properties</include>
<include>basic-config.properties</include>
<include>bootstrap.properties</include>
+ </includes>
+ </testResource>
+ <testResource>
+ <filtering>false</filtering>
+ <directory>src/test/resources</directory>
+ <includes>
<include>mail/*</include>
<include>sample-art3d/*</include>
</includes>
@@ -74,6 +96,7 @@
</plugin>
</plugins>
</build>
+
<dependencies>
<dependency>
<groupId>junit</groupId>
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -4,74 +4,41 @@
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-server</artifactId>
<packaging>war</packaging>
- <version>0.0.1-SNAPSHOT</version>
- <distributionManagement>
- <snapshotRepository>
- <id>local-disk</id>
- <uniqueVersion>false</uniqueVersion>
- <name>local disk</name>
- <url>${my.local.repo}</url>
- </snapshotRepository>
- </distributionManagement>
-
- <!-- -->
- <!-- profiles -->
- <!-- -->
+ <!-- mildly questionable: with this profile active by default, you don't get tests run -->
+ <!-- when you do 'install' in this directory... this is b/c often you don't want to destroy -->
+ <!-- the db (which the tests do) when doing server development... comment this out to get -->
+ <!-- the maven default behavior -->
<profiles>
- <!-- LINUX -->
<profile>
- <id>linux</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
+ <id>server-side</id>
+ <activation>
+ <activeByDefault>true</activeByDefault>
+ </activation>
</profile>
- <!-- OSX -->
- <profile>
- <id>osx</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- </profile>
</profiles>
- <!-- -->
+
+ <!-- -->
<!-- BUILD -->
- <!-- -->
+ <!-- -->
<build>
-
<!-- touching templates causes rebuild -->
- <scriptSourceDirectory>${basedir}/src/main/resources/siteTemplates</scriptSourceDirectory>
-
- <!-- -->
+ <scriptSourceDirectory>
+ ${basedir}/src/main/resources/siteTemplates
+ </scriptSourceDirectory>
+
+ <!-- -->
<!-- RESOURCES -->
- <!-- -->
+ <!-- -->
<resources>
<resource>
<directory>src/main/resources/hibernate</directory>
@@ -105,9 +72,9 @@
</resource>
</resources>
- <!-- -->
+ <!-- -->
<!-- TEST RESOURCES -->
- <!-- -->
+ <!-- -->
<testResources>
<testResource>
<directory>src/test/resources</directory>
@@ -123,31 +90,10 @@
</testResources>
- <!-- -->
+ <!-- -->
<!-- PLUGINS -->
- <!-- -->
+ <!-- -->
<plugins>
- <!-- our own plugin for building the static code -->
- <plugin>
- <groupId>com.ogoglio</groupId>
- <artifactId>dev-plugins</artifactId>
- <executions>
- <execution>
- <phase>compile</phase>
- <goals>
- <goal>buildHtml</goal>
- </goals>
- <configuration>
- <templateDirectory>
- src/main/resources/siteTemplates
- </templateDirectory>
- <targetDirectory>
- target/${artifactId}-${version}
- </targetDirectory>
- </configuration>
- </execution>
- </executions>
- </plugin>
<!-- DEPENDENCY PLUGIN: We need to pull in applets -->
<plugin>
@@ -206,46 +152,53 @@
<resource>
<!-- this basedir is a workaround for bug -->
<!-- http://jira.codehaus.org/browse/MWAR-64 -->
- <directory>${basedir}/src/main/webapp/</directory>
+ <directory>
+ ${basedir}/src/main/webapp/
+ </directory>
<filtering>true</filtering>
</resource>
</webResources>
</configuration>
</plugin>
- <!-- CARGO FOR DEPLOY SERVER -->
+ <!-- Our plugin config for building templates -->
<plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>0.3-SNAPSHOT</version>
- <configuration>
- <container>
- <containerId>tomcat5x</containerId>
- </container>
- <!-- Configuration to use with the container -->
- <configuration>
- <type>existing</type>
- <home>${ogoglio.tmp.tomcat5x}</home>
- <!-- Deployer configuration -->
- <deployables>
- <deployable>
- <properties>
- <context>${pom.artifactId}</context>
- </properties>
- </deployable>
- </deployables>
- </configuration>
- </configuration>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>dev-plugins</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
<executions>
<execution>
- <id>install</id>
- <phase>integration-test</phase><!-- just must be after packaging -->
+ <phase>compile</phase>
<goals>
- <goal>deploy</goal>
+ <goal>buildHtml</goal>
</goals>
- <!-- CARGO CONFIG -->
+ <configuration>
+ <templateDirectory>
+ src/main/resources/siteTemplates
+ </templateDirectory>
+ <targetDirectory>
+ target/${artifactId}-${version}
+ </targetDirectory>
+ </configuration>
</execution>
</executions>
+
</plugin>
+ <!-- CARGO CONFIG -->
+ <plugin>
+ <groupId>org.codehaus.cargo</groupId>
+ <artifactId>cargo-maven2-plugin</artifactId>
+ <version>0.3-SNAPSHOT</version>
+ <configuration>
+ <!-- Deployer configuration -->
+ <deployables>
+ <deployable>
+ <properties>
+ <context>${pom.artifactId}</context>
+ </properties>
+ </deployable>
+ </deployables>
+ </configuration>
+ </plugin>
</plugins>
</build>
@@ -287,9 +240,9 @@
<scope>compile</scope>
</dependency>
- <!-- -->
+ <!-- -->
<!-- OGOGLIO DEPENDENCIES-->
- <!-- -->
+ <!-- -->
<dependency>
<groupId>com.ogoglio</groupId>
<artifactId>ogoglio-common</artifactId>
@@ -300,9 +253,9 @@
<artifactId>ogoglio-appdev</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
- <!-- -->
+ <!-- -->
<!-- BOGUS DEPENDENCIES-->
- <!-- -->
+ <!-- -->
<dependency>
<groupId>com.ogoglio</groupId>
<artifactId>ogoglio-viewer-applet</artifactId>
Modified: maven/trunk/ogoglio-test-applet/pom.xml
===================================================================
--- maven/trunk/ogoglio-test-applet/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-test-applet/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -2,13 +2,16 @@
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
-
- <modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-test-applet</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
<build>
<plugins>
@@ -16,12 +19,10 @@
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
- <skip>true</skip><!-- ugh no unit tests -->
+ <skip>true</skip><!-- ugh, no unit tests -->
</configuration>
</plugin>
</plugins>
</build>
-
- <dependencies></dependencies>
</project>
Modified: maven/trunk/ogoglio-viewer-applet/pom.xml
===================================================================
--- maven/trunk/ogoglio-viewer-applet/pom.xml 2007-09-02 20:04:48 UTC (rev 338)
+++ maven/trunk/ogoglio-viewer-applet/pom.xml 2007-09-02 20:29:33 UTC (rev 339)
@@ -3,55 +3,16 @@
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
- <groupId>com.ogoglio</groupId>
+
+ <!-- About this project -->
+ <parent>
+ <groupId>com.ogoglio</groupId>
+ <artifactId>ogoglio</artifactId>
+ <version>0.0.1-SNAPSHOT</version>
+ <relativePath>../ogoglio</relativePath>
+ </parent>
<artifactId>ogoglio-viewer-applet</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <packaging>jar</packaging>
- <!-- -->
- <!-- profiles -->
- <!-- -->
- <profiles>
- <!-- LINUX -->
- <profile>
- <id>linux</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.5.1</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- </profile>
- <!-- OSX -->
- <profile>
- <id>osx</id>
- <dependencies>
- <!-- jav3d stuff -->
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>j3d-core</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- <dependency>
- <groupId>java3d</groupId>
- <artifactId>vecmath</artifactId>
- <version>1.3</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- </profile>
- </profiles>
-
<dependencies>
<dependency>
<groupId>netscape</groupId>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-04 19:00:18
|
Revision: 358
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=358&view=rev
Author: iansmith
Date: 2007-09-04 12:00:02 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
First cut at a logging centralization.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/DBVersionPersistTasks.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/persist/HibernateTask.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java
maven/trunk/ogoglio-common/pom.xml
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceDuplicator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClientWire.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIUtil.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/model/Space.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/NetworkUtils.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/J3DDoorRenderable.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/J3DPageRenderable.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/J3DRenderableLoader.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/J3DRenderer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/MotionInputHandler.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/RenderableMotionInterpolator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/body/Skeleton.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/body/Skin.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/bvh/Bvh.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/viewer/j3d/smap/SkinMapParser.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/BootstrapInfo.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-integration-test/src/test/resources/log4j.properties
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/FileStore.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/site/MediaServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/AccountPersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/TemplatePersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/script/ScriptHTTPRequest.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/script/ScriptSpace.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/script/SpaceScriptEngine.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/AccountServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OgoglioServletBase.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/TemplateResource.java
maven/trunk/ogoglio-server/src/main/resources/log4j/log4j.properties
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java
maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/j3d/bvh/test/BvhTest.java
maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java
Removed Paths:
-------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/OgoglioProperties.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/DBVersionPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/DBVersionPersistTasks.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/DBVersionPersistTasks.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -6,6 +6,7 @@
import com.ogoglio.appdev.persist.HibernateTask;
import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.util.Log;
public class DBVersionPersistTasks {
public final static String FIND_VERSION = "com.ogoglio.appdev.migrate.dbversions";
@@ -28,7 +29,7 @@
int size = query.list().size();
DBVersionRecord rec;
if (expectedSize != size) {
- System.err.println("Whoa! Size of returned result for db version record was (" + size + ") but should have been " + expectedSize + "!");
+ Log.error("Whoa! Size of returned result for db version record was (" + size + ") but should have been " + expectedSize + "!");
return Boolean.FALSE;
}
if (size == 0) {
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -4,11 +4,11 @@
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
-import org.apache.commons.logging.LogFactory;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.util.Log;
import com.ogoglio.util.PropStorage;
import com.ogoglio.viewer.render.UIConstants;
@@ -21,7 +21,6 @@
public static final boolean DDL_MODE_UPDATE=true;
public static final boolean DDL_MODE_CREATE=false;
- static org.apache.commons.logging.Log log = LogFactory.getLog("com.ogoglio.migrate");
public MigrationSupport() {
}
@@ -35,7 +34,7 @@
SessionFactory sessionFactory = getCurrentConfiguration().buildSessionFactory();
int version = DBVersionPersistTasks.findVersion(sessionFactory);
if (version != getVersionNumber()) {
- log.error("DB Version Mismatch! Expected (" + getVersionNumber() + ") but got " + version + "!");
+ Log.error("DB Version Mismatch! Expected (" + getVersionNumber() + ") but got " + version + "!");
sessionFactory.close();
return tryUpgrade(servletConf, ctx, version, getVersionNumber(),
DDL_MODE_UPDATE, true, null);
@@ -44,10 +43,10 @@
return true; // we are at the expected version
} catch (PersistException e) {
if (e.innerThrowable == null) {
- log.error("Serious problem with hibernate:" + e.getMessage());
+ Log.error("Serious problem with hibernate:" + e.getMessage());
return false;
}
- log.info("Unable to figure out DB version number. Likely this is a fresh database....(" + e.innerThrowable.getClass().getName() + ")");
+ Log.info("Unable to figure out DB version number. Likely this is a fresh database....(" + e.innerThrowable.getClass().getName() + ")");
return initVersionAndUpgrade(servletConf, ctx);
}
}
@@ -63,7 +62,7 @@
factory.close();
return true;
} catch (Throwable t) {
- log.error("Error trying initialized DB:" + t.getMessage());
+ Log.error("Error trying initialized DB:" + t.getMessage());
return false;
}
}
@@ -97,7 +96,7 @@
try {
return DBVersionPersistTasks.updateVersion(targetVersion, expectedSize, sessionFactory);
} catch (PersistException e) {
- log.error("Problem updating the version of the database to version " + targetVersion + ":" + e.getMessage());
+ Log.error("Problem updating the version of the database to version " + targetVersion + ":" + e.getMessage());
return false;
}
}
@@ -105,7 +104,7 @@
public boolean tryUpgrade(ServletConfig servletConfig, Context ctx, int db_is,
int db_wants_to_be, boolean isUpdate, boolean useJNDI, PropStorage propStore) {
if (getMigrationList().length != getVersionNumber()) {
- log.error("Internal error! Migration list length should be " + getVersionNumber() + " but is " + getMigrationList().length + "!");
+ Log.error("Internal error! Migration list length should be " + getVersionNumber() + " but is " + getMigrationList().length + "!");
return false;
}
boolean canMigrate = false;
@@ -122,12 +121,12 @@
canMigrate = true;
}
} catch (NamingException e) {
- log.error("Naming exception trying to access " + MIGRATION_KEY + " from naming context!");
+ Log.error("Naming exception trying to access " + MIGRATION_KEY + " from naming context!");
canMigrate=false;
}
if (!canMigrate) {
- log.error("Cannot migrate data! Property ogoglio.okToMigrateDB is false or non-existent!");
+ Log.error("Cannot migrate data! Property ogoglio.okToMigrateDB is false or non-existent!");
return false;
}
String hbm_auto_flag="update";
@@ -138,7 +137,7 @@
for (int i = db_is; i < db_wants_to_be; ++i) {
Migration current = getMigrationList()[i];
- log.info("DB: Attempting migration from " + i + " to " + (i + 1) + " with auto HBM:"+hbm_auto_flag);
+ Log.info("DB: Attempting migration from " + i + " to " + (i + 1) + " with auto HBM:"+hbm_auto_flag);
//try to get hibernate to do the work
Configuration config = createConfigurationForHibernate(i + 1, hbm_auto_flag, useJNDI, propStore);
@@ -157,22 +156,22 @@
return false;
}
} catch (PersistException e) {
- log.error("Whoa! Patch failed at revision!"+(i+1)+" on class "+current.getClass().getName());
- log.error("Whoa! Persistance layer problem was:"+e.getMessage());
+ Log.error("Whoa! Patch failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ Log.error("Whoa! Persistance layer problem was:"+e.getMessage());
}
try {
if (!isUpdate) {
//we need to go ahead and create the data
if (!current.populate(factory, i, i+1)) {
- log.error("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ Log.error("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
factory.close();
return false;
}
}
} catch (PersistException e) {
- log.error("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
- log.error("Whoa! Persistance layer problem was:"+e.getMessage());
+ Log.error("Whoa! Populate failed at revision!"+(i+1)+" on class "+current.getClass().getName());
+ Log.error("Whoa! Persistance layer problem was:"+e.getMessage());
}
factory.close();
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/test/DBZapTest.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -5,6 +5,7 @@
import org.hibernate.SessionFactory;
import com.ogoglio.appdev.migrate.MigrationSupport;
+import com.ogoglio.util.Log;
import com.ogoglio.util.PropStorage;
public abstract class DBZapTest extends TestCase {
@@ -30,9 +31,7 @@
//if we are here, db stuff worked, but we still need to avoid all the jndi stuff
sessionFactory = support.createConfigurationForHibernate(getMigrationSupport().getVersionNumber(), null, false, ps).buildSessionFactory();
} catch (Exception e) {
- System.out.println("-------");
- e.printStackTrace(System.out);
- System.out.println("---------");
+ Log.error("Trying to setUp DBZapTest",e);
fail("Could not setup:" + e.getMessage());
}
}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/persist/HibernateTask.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/persist/HibernateTask.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/persist/HibernateTask.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -19,7 +19,9 @@
import org.hibernate.StaleObjectStateException;
import org.hibernate.Transaction;
+import com.ogoglio.util.Log;
+
public abstract class HibernateTask {
private SessionFactory sessionFactory = null;
@@ -41,8 +43,8 @@
transaction.commit();
return result;
} catch (StaleObjectStateException staleEx) {
- System.err.println("This interceptor does not implement optimistic concurrency control!");
- System.err.println("Your application will not work until you add compensation actions!");
+ Log.error("This interceptor does not implement optimistic concurrency control!",staleEx);
+ Log.error("Your application will not work until you add compensation actions!",staleEx);
throw new PersistException("This DB is not supported.");
} catch (PersistException ex) {
try {
@@ -53,9 +55,7 @@
}
throw ex;
} catch (Throwable ex) { //catches things that are created by Hibernate that are not PersistException
- System.err.println("TRUE TYPE OF CAUGHT EXCEPTION:"+ex.getClass().getName());
- System.err.println("ORIG STACK TRACE");
- ex.printStackTrace();
+ Log.error("TRUE TYPE OF CAUGHT EXCEPTION:"+ex.getClass().getName(),ex);
try {
if (transaction.isActive()) {
transaction.rollback();
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -41,6 +41,7 @@
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.ogoglio.client.DecoratedInputStream;
+import com.ogoglio.util.Log;
import com.ogoglio.util.StreamUtils;
import com.ogoglio.util.WebConstants;
import com.ogoglio.xml.SpaceDocument;
@@ -88,7 +89,7 @@
baseResource = createBaseResource(config);
if (baseResource==null) {
- System.out.println("Warning: Class "+getClass().getName()+" should be sure it eventually sets the value of the base resource on it's servlet.");
+ Log.warn("Class "+getClass().getName()+" should be sure it eventually sets the value of the base resource on it's servlet.");
} else {
if (!(baseResource.getPathElement() instanceof String)) {
throw new IllegalStateException("The base resource must have a String path element: " + baseResource.getPathElement());
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -8,6 +8,7 @@
import org.hibernate.SessionFactory;
import com.ogoglio.appdev.migrate.MigrationSupport;
+import com.ogoglio.util.Log;
public abstract class MigratedResourceServlet extends AbstractResourceServlet {
@@ -45,7 +46,7 @@
private SessionFactory getOrCreateHibernateSessionFactory(ServletConfig config, Context context) {
SessionFactory sessionFactory = (SessionFactory) config.getServletContext().getAttribute(HIBERNATE_SESSION_FACTORY_KEY);
if (sessionFactory == null) {
- System.out.println(config.getServletName()+" checking DB Version...");
+ Log.info(config.getServletName()+" checking DB Version...");
MigrationSupport ms= getMigration();
if (!ms.verifyVersion(config,context)) {
throw new IllegalStateException("Cannot find a DB configuration for hibernate!");
Modified: maven/trunk/ogoglio-common/pom.xml
===================================================================
--- maven/trunk/ogoglio-common/pom.xml 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-common/pom.xml 2007-09-04 19:00:02 UTC (rev 358)
@@ -46,6 +46,13 @@
<version>2.0.0-rc-6</version>
<scope>compile</scope>
</dependency>
+
+ <!-- for logging layer -->
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.1</version>
+ </dependency>
</dependencies>
</project>
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -11,6 +11,7 @@
import com.ogoglio.client.model.SplinePath;
import com.ogoglio.client.model.Thing;
import com.ogoglio.client.model.User;
+import com.ogoglio.util.Log;
import com.ogoglio.viewer.j3d.J3DSplinePath;
public class MultiuserTests {
@@ -82,7 +83,7 @@
}
public void disconnected() {
- System.err.println("UserRobot was disconnected");
+ Log.error("UserRobot was disconnected");
}
public void receivedChatMessage(String username, String message) {
@@ -168,7 +169,7 @@
public static void main(String[] args) {
if (args.length != 3) {
- System.err.println("usage: ... spaceURI serviceURI numRobots");
+ Log.error("usage: ... spaceURI serviceURI numRobots");
return;
}
MultiuserTests tests = null;
@@ -185,7 +186,7 @@
for (int i = 0; i < numRobots; i++) {
startPosition.setTranslation(new Vector3d(0, 0, -10));
tests.addRobot(startPosition, true);
- System.out.println("Added robot " + (i + 1) + " of " + numRobots);
+ Log.test("Added robot " + (i + 1) + " of " + numRobots);
Thread.sleep(1000);
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-09-04 15:32:46 UTC (rev 357)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-09-04 19:00:02 UTC (rev 358)
@@ -37,6 +37,7 @@
import com.ogoglio.message.PayloadFactory;
import com.ogoglio.message.TCPChannel;
import com.ogoglio.util.ArgumentUtils;
+import com.ogoglio.util.Log;
import com.ogoglio.viewer.render.UIConstants;
import com.ogoglio.xml.AccountDocument;
import com.ogoglio.xml.BodyDocument;
@@ -109,7 +110,7 @@
}
if (messenger.authStatus != messenger.SUCCESS_STATUS) {
- System.err.println("No auth, message " + messenger.errorMessage);
+ Log.error("No auth, message " + messenger.errorMessage);
messenger.cleanup();
if(messenger.errorMessage == null) {
@@ -180,7 +181,7 @@
}
public void mouseClickedUser(User user, Point3d intersection) {
- System.err.println("SpaceClient ignoring user click");
+ Log.warn("SpaceClient ignoring user click");
}
public void mouseClickedDoor(Door door, String name, Point3d intersection) {
@@ -231,7 +232,7 @@
public void mouseClickedPage(Page page, Point3d intersection) {
- System.out.println("User clicked the page. Ignoring");
+ Log.info("User clicked the page. Ignoring");
}
public void viewpointMotionChanged(SplinePath newPath) {
@@ -293,7 +294,7 @@
} else if (SpaceEvent.REMOVE_USER_EVENT.equals(event.getName())) {
User user = space.getUser(event.getStringProperty(SpaceEvent.USERNAME));
if (user == null) {
- System.err.println("Tried to remove unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
+ Log.error("Tried to remove unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
return;
}
space.removeUser(user);
@@ -314,8 +315,7 @@
template = new Template(templateDoc);
space.addTemplate(template);
} catch (IOException e) {
- e.printStackTrace();
- System.err.println("Could not add the template");
+ Log.error("Could not add the template",e);
}
}
Thing thing = new Thing(space, event.getLongProperty(SpaceEvent.THING_ID).longValue(), template, event.getStringProperty(SpaceEvent.DISPLAY_NAME), event.getStringProperty(SpaceEvent.OWNER_USERNAME), event.getLongProperty(SpaceEvent.POSSESSION_ID).longValue(), event.getTransform());
@@ -334,7 +334,7 @@
long thingID = event.getLongProperty(SpaceEvent.THING_ID).longValue();
Thing thing = space.getThing(thingID);
if (thing == null) {
- System.err.println("Tried to add a page for a non-existent thing: " + thingID);
+ Log.error("Tried to add a page for a non-existent thing: " + thingID);
return;
}
Page page = new Page(thing, event.getLongProperty(SpaceEvent.PAGE_ID).longValue(), event.getStringProperty(SpaceEvent.CONTENT_TYPE), event.getDoubleProperty(SpaceEvent.WIDTH).doubleValue(), event.getDoubleProperty(SpaceEvent.HEIGHT).doubleValue(), event.getTransform());
@@ -344,13 +344,13 @@
long thingID = event.getLongProperty(SpaceEvent.THING_ID).longValue();
Thing thing = space.getThing(thingID);
if (thing == null) {
- System.err.println("Tried to remove a page for a non-existent thing: " + thingID);
+ Log.error("Tried to remove a page for a non-existent thing: " + thingID);
return;
}
long pageID = event.getLongProperty(SpaceEvent.PAGE_ID).longValue();
Page page = thing.getPage(pageID);
if (page == null) {
- System.err.println("Tried to remove an unknown page: " + thingID + ", " + pageID);
+ Log.error("Tried to remove an unknown page: " + thingID + ", " + pageID);
return;
}
thing.removePage(page);
@@ -359,13 +359,13 @@
long thingID = event.getLongProperty(SpaceEvent.THING_ID).longValue();
Thing thing = space.getThing(thingID);
if (thing == null) {
- System.err.println("Tried to update a page for a non-existent thing: " + thingID);
+ Log.error("Tried to update a page for a non-existent thing: " + thingID);
return;
}
long pageID = event.getLongProperty(SpaceEvent.PAGE_ID).longValue();
Page page = thing.getPage(pageID);
if (page == null) {
- System.err.println("Tried to update an unknown page: " + thingID + ", " + pageID);
+ Log.error("Tried to update an unknown page: " + thingID + ", " + pageID);
return;
}
if (!page.getPosition().epsilonEquals(event.getTransform(), 0.001)) {
@@ -378,13 +378,13 @@
long thingID = event.getLongProperty(SpaceEvent.THING_ID).longValue();
Thing thing = space.getThing(thingID);
if (thing == null) {
- System.err.println("Tried to update content on a page for a non-existent thing: " + thingID);
+ Log.error("Tried to update content on a page for a non-existent thing: " + thingID);
return;
}
long pageID = event.getLongProperty(SpaceEvent.PAGE_ID).longValue();
Page page = thing.getPage(pageID);
if (page == null) {
- System.err.println("Tried to update content on an unknown page: " + thingID + ", " + pageID);
+ Log.error("Tried to update content on an unknown page: " + thingID + ", " + pageID);
return;
}
if (!page.getContentType().equals(event.getStringProperty(SpaceEvent.CONTENT_TYPE))) {
@@ -403,14 +403,14 @@
template = new Template(templateDoc);
space.addTemplate(template);
} catch (IOException e) {
- System.err.println("Could not add the template");
+ Log.error("Could not add the template",e);
}
}
try {
Door door = new Door(space, template, event.getLongProperty(SpaceEvent.DOOR_ID).longValue(), event.getStringProperty(SpaceEvent.DISPLAY_NAME), new URI(event.getStringProperty(SpaceEvent.LINK)), event.getTransform());
space.addDoor(door);
} catch (URISyntaxException e) {
- System.err.println("Could not parse the door link: " + event.getStringProperty(SpaceEvent.LINK));
+ Log.error("Could not parse the door link: " + event.getStringProperty(SpaceEvent.LINK),e);
}
} else if (SpaceEvent.UPDATE_DOOR_EVENT.equals(event.getName())) {
@@ -438,7 +438,7 @@
User user = space.getUser(event.getStringProperty(SpaceEvent.USERNAME));
if (user == null) {
- System.err.println("Got a motion event for an unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
+ Log.error("Got a motion event for an unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
return;
}
SplinePath path = event.getSplinePath();
@@ -451,7 +451,7 @@
User user = space.getUser(event.getStringProperty(SpaceEvent.USERNAME));
if (user == null) {
- System.err.println("Got a stop event for an unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
+ Log.error("Got a stop event for an unknown user: " + event.getStringProperty(SpaceEvent.USERNAME));
return;
}
user.stopMotion(event.getTransform());
@@ -476,12 +476,12 @@
long thingID = event.getLongProperty(SpaceEvent.THING_ID).longValue();
Thing thing = space.getThing(thingID);
if (thing == null) {
- System.err.println("Tried to move a shape for an unknown thing: " + thingID);
+ Log.error("Tried to move a shape for an unknown thing: " + thingID);
return;
}
Shape shape = thing.getShape(event.getStringProperty(SpaceEvent.SHAPE_NAME));
if (shape == null) {
- System.err.println("Tried to move unknown shape: " + event.getStringProperty(SpaceEvent.SHAPE_NAME));
+ Log.error("Tried to move unknown shape: " + event.getStringProperty(SpaceEvent.SHAPE_NAME));
return;
}
shape.startMotion(event.getSplinePath());
@@ -494,7 +494,7 @@
}
Shape shape = thing.getShape(event.getStringProperty(SpaceEvent.SHAPE_NAME));
if (shape == null) {
- System.err.println("Tried to stop unknown shape: " + e...
[truncated message content] |
|
From: <ian...@us...> - 2007-09-04 23:28:00
|
Revision: 359
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=359&view=rev
Author: iansmith
Date: 2007-09-04 16:28:02 -0700 (Tue, 04 Sep 2007)
Log Message:
-----------
Deleting the database in a test now implies destroying media files as well.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
maven/trunk/ogoglio-server/src/test/resources/basic-config.properties
Property Changed:
----------------
maven/trunk/ogoglio-integration-test/
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-04 19:00:02 UTC (rev 358)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-04 23:28:02 UTC (rev 359)
@@ -1,5 +1,7 @@
package com.ogoglio.appdev.migrate;
+import java.io.File;
+
import javax.naming.Context;
import javax.naming.NamingException;
import javax.servlet.ServletConfig;
@@ -189,6 +191,27 @@
return false;
}
- return tryUpgrade(null, null, 0, getVersionNumber(), DDL_MODE_CREATE, false, ps);
+ if (tryUpgrade(null, null, 0, getVersionNumber(), DDL_MODE_CREATE, false, ps)==false) {
+ Log.error("Aborted destroying data after failure to upgrade");
+ return false;
+ }
+ ps.loadPropertySet(PropStorage.BASIC_PROPS);
+ String dir = ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.mediaDirectory");
+ if (dir==null) {
+ Log.error("Can't find a property ogoglio.mediaDirectory to cleanse media store");
+ return false;
+ }
+ File store = new File(dir);
+ if ((!store.exists()) || (!store.canWrite())) {
+ Log.error("Media directory doesn't exist or can't be changed:"+dir);
+ return false;
+ }
+ File[] children= store.listFiles();
+ for (int i=0; i<children.length;++i) {
+ if (children[i].delete()!=true) {
+ Log.error("Failed to delete media file:"+children[i].getAbsolutePath());
+ }
+ }
+ return true;
}
}
Property changes on: maven/trunk/ogoglio-integration-test
___________________________________________________________________
Name: svn:ignore
- target
+ target
tomcat5x.out
Modified: maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
===================================================================
--- maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-04 19:00:02 UTC (rev 358)
+++ maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-04 23:28:02 UTC (rev 359)
@@ -13,12 +13,16 @@
limitations under the License. */
package com.ogoglio.persist.test;
+import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import com.ogoglio.appdev.migrate.MigrationSupport;
import com.ogoglio.appdev.migrate.test.DBZapTest;
import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.client.WebAPIDescriptor;
+import com.ogoglio.media.MediaService;
import com.ogoglio.migrate.OgoglioServerMigration;
import com.ogoglio.persist.AccountPersistTasks;
import com.ogoglio.persist.AccountRecord;
@@ -33,6 +37,7 @@
import com.ogoglio.persist.TemplatePersistTasks;
import com.ogoglio.persist.TemplateRecord;
import com.ogoglio.util.Log;
+import com.ogoglio.util.PropStorage;
public class PersistTest extends DBZapTest {
@@ -162,6 +167,29 @@
fail("Should have just returned null instead of failed: " + e);
}
}
+
+ public void testMediaDirectoryEmptiedByParentClass() {
+ PropStorage ps=new PropStorage();
+ if (ps.loadPropertySet(PropStorage.BASIC_PROPS)==false) {
+ fail("couldn't load properties for test");
+ }
+
+ try {
+ String key=ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.mediaDirectory");
+ if (key==null) {
+ fail("no test property ogoglio.mediaDirectory");
+ }
+ MediaService svc = new MediaService(new URI(key));
+ if (svc==null) {
+ fail("can't create a media service:"+key);
+ }
+ assertEquals(0,svc.getAllNames().length);
+ } catch (IOException e) {
+ fail("IOException talking to media service:"+e.getMessage());
+ } catch (URISyntaxException e) {
+ fail("URISytaxException talking to media service:"+e.getMessage());
+ }
+ }
private SpaceRecord checkSpaceAndSimTasks() throws PersistException {
SimRecord simRecord1;
// ok to create sim now on that URI
Modified: maven/trunk/ogoglio-server/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-server/src/test/resources/basic-config.properties 2007-09-04 19:00:02 UTC (rev 358)
+++ maven/trunk/ogoglio-server/src/test/resources/basic-config.properties 2007-09-04 23:28:02 UTC (rev 359)
@@ -1,4 +1,4 @@
# basic info needed for some tests
ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
ogoglio.baseUrl = ${ogoglio.baseURL}
-
+ogoglio.mediaDirectory = ${ogoglio.mediaDirectory}
\ No newline at end of file
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-05 23:18:47
|
Revision: 371
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=371&view=rev
Author: iansmith
Date: 2007-09-05 16:18:49 -0700 (Wed, 05 Sep 2007)
Log Message:
-----------
New Mojos for populate and reverse populate.
Modified Paths:
--------------
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/resources/populate/space-1
Added Paths:
-----------
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/OgServiceMojoBase.java
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java
Added: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/OgServiceMojoBase.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/OgServiceMojoBase.java (rev 0)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/OgServiceMojoBase.java 2007-09-05 23:18:49 UTC (rev 371)
@@ -0,0 +1,98 @@
+package com.ogoglio.plugin;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
+
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+
+import com.ogoglio.client.WebAPIAuthenticator;
+import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.client.WebAPIClientWire;
+import com.ogoglio.client.WebAPIDescriptor;
+import com.ogoglio.xml.TemplateDocument;
+
+public abstract class OgServiceMojoBase extends AbstractMojo {
+
+ protected static final String SPACE_PREFIX = "space-";
+ protected static final String TEMPLATE_PREFIX = "template-";
+ /**
+ * @parameter
+ */
+ protected File populateDir;
+ /**
+ * @parameter
+ */
+ protected String serviceURI;
+ /**
+ * @parameter
+ */
+ protected String username;
+ /**
+ * @parameter
+ */
+ private String password;
+
+ protected WebAPIClient validateArgsAndConnect() {
+ if (populateDir == null) {
+ getLog().info("No populate baseDir given. Mojo ignored.");
+ return null;
+ }
+
+ if ((!populateDir.exists()) || (!populateDir.isDirectory())
+ || (!populateDir.canRead())) {
+ getLog().error(
+ "Unable to access base dir:" + populateDir.getAbsolutePath());
+ return null;
+ }
+
+ if (serviceURI == null) {
+ getLog().info("No populate serviceURI given. Mojo ignored.");
+ return null;
+ }
+ try {
+ WebAPIClientWire wire = new WebAPIClientWire();
+ WebAPIDescriptor descriptor = new WebAPIDescriptor(new URI(
+ serviceURI));
+ WebAPIAuthenticator auth = new WebAPIAuthenticator(wire,
+ descriptor, username, password);
+ WebAPIClient client = new WebAPIClient(descriptor, auth, wire);
+ return client;
+
+ } catch (URISyntaxException e) {
+ getLog().error("Bad URI (" + serviceURI + ")", e);
+ } catch (IOException e) {
+ getLog().error("Unable to connect to service (" + serviceURI + ")",
+ e);
+ }
+ // some kind of exception
+ return null;
+ }
+
+ protected TemplateDocument fileNameToTemplateDocument(WebAPIClient client, File tempFile)
+ throws IOException {
+ String templateName = fileToTemplateName(tempFile);//.obj
+ TemplateDocument doc = client.createTemplate(templateName);
+ return doc;
+ }
+
+ protected String fileToTemplateName(File tempFile) {
+ return tempFile.getName().substring(0, tempFile.getName().length() - 4);
+ }
+
+ protected int dirNameToTemplateNumber(File candidate)
+ throws MojoExecutionException {
+ int n = -188;
+ String num = candidate.getName().substring(TEMPLATE_PREFIX.length());
+ try {
+ n = Integer.parseInt(num);
+ } catch (NumberFormatException e) {
+ throw new MojoExecutionException("Badly formed template name in populate directory:"+candidate.getName());
+ }
+ return n;
+
+ }
+
+}
Modified: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java 2007-09-05 22:32:42 UTC (rev 370)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java 2007-09-05 23:18:49 UTC (rev 371)
@@ -1,223 +1,163 @@
package com.ogoglio.plugin;
-import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
-import java.io.FileReader;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
-import java.net.URI;
-import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import nanoxml.XMLElement;
-import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugin.MojoExecutionException;
-import com.agical.rmock.core.util.StringUtils;
-import com.ogoglio.client.WebAPIAuthenticator;
import com.ogoglio.client.WebAPIClient;
-import com.ogoglio.client.WebAPIClientWire;
-import com.ogoglio.client.WebAPIDescriptor;
import com.ogoglio.util.StreamUtils;
import com.ogoglio.xml.PossessionDocument;
import com.ogoglio.xml.SpaceDocument;
import com.ogoglio.xml.TemplateDocument;
+import com.ogoglio.xml.ThingDocument;
/**
* @goal populate
*/
-public class PopulateMojo extends AbstractMojo {
- /**
- * @parameter
- */
- private File baseDir;
- /**
- * @parameter
- */
- private String serviceURI;
- /**
- * @parameter
- */
- private String username;
- /**
- * @parameter
- */
- private String password;
+public class PopulateMojo extends OgServiceMojoBase {
+ private HashMap<Long, Long> templateIdMap = new HashMap<Long, Long>();
- private HashMap<Long,Long> templateIdMap = new HashMap<Long,Long>();
- private List<SpaceDocument> spaces=new ArrayList<SpaceDocument>();
-
- private static final String TEMPLATE_PREFIX="template-";
- private static final String SPACE_PREFIX="space-";
+ private List<SpaceDocument> spaces = new ArrayList<SpaceDocument>();
- public void execute() throws MojoExecutionException {
- if (baseDir==null) {
- getLog().info("No populate baseDir given. No population done.");
- return;
- }
-
- if ((!baseDir.exists()) || (!baseDir.isDirectory()) || (!baseDir.canRead())) {
- getLog().error("Unable to access base dir:"+baseDir.getAbsolutePath());
- return;
- }
-
- if (serviceURI==null) {
- getLog().info("No populate serviceURI given. No population done.");
- return;
- }
-
- try {
- WebAPIClientWire wire=new WebAPIClientWire();
- WebAPIDescriptor descriptor=new WebAPIDescriptor(new URI(serviceURI));
- WebAPIAuthenticator auth=new WebAPIAuthenticator(wire,descriptor,username,password);
- WebAPIClient client=new WebAPIClient(descriptor,auth,wire);
- //we are now ready to upload
-
- File[] templates = baseDir.listFiles();
-
- for (int i=0; i<templates.length;++i) {
- File candidate=templates[i];
- if (candidate.getName().startsWith(TEMPLATE_PREFIX)) {
- uploadTemplate(client,candidate);
- } else if (candidate.getName().startsWith(SPACE_PREFIX)) {
- readSpace(client,candidate);
- } else {
- if (!candidate.getName().equals(".svn")) {
- getLog().warn("Unable to process in populate:"+candidate.getAbsolutePath());
- }
- }
- }
-
- patchSpaces(client);
-
- } catch (URISyntaxException e) {
- throw new MojoExecutionException("Bad URI syntax("+serviceURI+")",e);
- } catch (IOException e) {
- throw new MojoExecutionException("IO Exception (possibly auth?"+username+","+password+")",e);
- }
- }
+ public void execute() throws MojoExecutionException {
+ WebAPIClient client = validateArgsAndConnect();
- private void patchSpaces(WebAPIClient client) throws MojoExecutionException {
- SpaceDocument fakeSpaceDoc,realSpaceDoc;
-
- for (int i=0; i<spaces.size();++i) {
- fakeSpaceDoc=spaces.get(i);
- try {
- realSpaceDoc = client.createSpace(fakeSpaceDoc.getDisplayName());
- TemplateDocument templates[] = fakeSpaceDoc.getTemplateDocuments();
- for (int j=0; j<templates.length;++j) {
- long trueId = templateIdMap.get(new Long(templates[j].getTemplateID())).longValue();
- PossessionDocument possDoc = client.createPossession(trueId);
- client.addPossessionToSpace(possDoc.getPossessionID(), fakeSpaceDoc.getSpaceID());
- TemplateDocument realTemplateDoc=client.getTemplateDocument(username, trueId);
- getLog().info("Added Template "+realTemplateDoc.getDisplayName()+" to space "+realSpaceDoc.getDisplayName());
- }
- //client.setSpacePublished(realSpaceDoc.getSpaceID(), fakeSpaceDoc.getSpacePublished());
- long realSpaceID = realSpaceDoc.getSpaceID();
- client.setSpaceSeaLevel(realSpaceID, fakeSpaceDoc.getSeaLevel());
- client.setSpaceMaxGuests(realSpaceID, fakeSpaceDoc.getMaxGuests());
- client.setSpaceDisplayName(realSpaceID, fakeSpaceDoc.getDisplayName());
- client.setSpaceSeaLevel(realSpaceID, fakeSpaceDoc.getSeaLevel());
- } catch (IOException e) {
- throw new MojoExecutionException("IOException patching space ("+fakeSpaceDoc.getDisplayName()+":"+fakeSpaceDoc.getSpaceID()+")",e);
- }
- }
-
- }
+ File[] templates = populateDir.listFiles();
- private void readSpace(WebAPIClient client, File candidate) throws MojoExecutionException{
- String name = candidate.getName();
- String num= name.substring(SPACE_PREFIX.length());
- int spaceFakeId=-189;
- try {
- spaceFakeId = Integer.parseInt(num);
- } catch (NumberFormatException e) {
- getLog().error("Badly formed space name:"+name+". Ignoring.");
- }
- if (spaceFakeId==-189) {
- return;
- }
- try {
- FileInputStream inputStream = new FileInputStream(candidate);
- String docContent = StreamUtils.readInput(inputStream);
- SpaceDocument doc=new SpaceDocument(XMLElement.parseElementFromString(docContent));
- spaces.add(doc);
- inputStream.close();
- } catch (IOException e) {
- throw new MojoExecutionException("IO Error reading space",e);
- }
-
-
- }
+ for (int i = 0; i < templates.length; ++i) {
+ File candidate = templates[i];
+ if (candidate.getName().startsWith(TEMPLATE_PREFIX)) {
+ uploadTemplate(client, candidate);
+ } else if (candidate.getName().startsWith(SPACE_PREFIX)) {
+ readSpace(client, candidate);
+ } else {
+ if (!candidate.getName().equals(".svn")) {
+ getLog().warn("Unable to process in populate:" + candidate.getAbsolutePath());
+ }
+ }
+ }
- private void uploadTemplate(WebAPIClient client, File candidate) throws MojoExecutionException{
- String name = candidate.getName();
- String num= name.substring(TEMPLATE_PREFIX.length());
+ patchSpaces(client);
+ }
- int templateFakeId=-188;
- try {
- templateFakeId = Integer.parseInt(num);
- } catch (NumberFormatException e) {
- getLog().error("Badly formed template name:"+name+". Ignoring.");
- }
- if (templateFakeId==-188) {
- return;
- }
- getLog().info("Uploading template #"+templateFakeId+" to "+serviceURI);
- File[] objs=candidate.listFiles(new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return name.endsWith(".obj");
- }
- });
- if (objs.length!=1) {
- throw new MojoExecutionException("Badly formed directory "+name+". Should have 1 obj file but has "+objs.length);
- }
- try {
- String templateName=objs[0].getName();
- InputStream objStream=new FileInputStream(objs[0]);
- TemplateDocument doc = client.createTemplate(templateName.substring(0,templateName.length()-4));//.obj
- client.uploadTemplateGeometryStream(username,doc.getTemplateID(),0,objStream);
+ private void patchSpaces(WebAPIClient client) throws MojoExecutionException {
+ SpaceDocument fakeSpaceDoc, realSpaceDoc;
- templateIdMap.put(new Long(templateFakeId), new Long(doc.getTemplateID()));
- getLog().info("Created template from "+objs[0].getName()+
- " ["+templateFakeId+" -> "+doc.getTemplateID()+"]");
-
- File[] notObjs=candidate.listFiles(new FilenameFilter() {
- public boolean accept(File dir, String name) {
- return !name.endsWith(".obj");
- }
- });
- for (int i=0; i<notObjs.length; ++i) {
- File supportFile = notObjs[i];
- String supportName = supportFile.getName();
- if (supportFile.getName().endsWith(".js")) {
- String script = StreamUtils.readInput(new FileInputStream(supportFile));
- client.updateTemplateScript(username, doc.getTemplateID(), script);
- getLog().info("Uploaded script file:"+supportName);
- } else {
- if ((!(supportName.endsWith(".gif"))) && (!(supportName.endsWith(".jpg"))) &&
- (!(supportName.endsWith(".png"))) && (!(supportName.endsWith(".mtl")))) {
-
- if ((!(supportName.endsWith(".blend"))) && (!(supportName.endsWith(".3DS"))) &&
- (!(supportName.endsWith(".txt"))) && (!(supportName.equals(".svn")))) {
- getLog().warn("Don't know what to do with file "+supportName+". Ignoring.");
- }
- continue;
- }
- FileInputStream supportStream = new FileInputStream(supportFile);
- client.uploadTemplateResourceStream(username, doc.getTemplateID(), supportName, supportStream);
- getLog().info("Uploaded support file:"+supportName);
- }
- }
-
- } catch (IOException e) {
- throw new MojoExecutionException("IO Error in upload",e);
- }
- }
+ for (int i = 0; i < spaces.size(); ++i) {
+ fakeSpaceDoc = spaces.get(i);
+ try {
+ realSpaceDoc = client.createSpace(fakeSpaceDoc.getDisplayName());
+ ThingDocument things[] = fakeSpaceDoc.getThingDocuments();
+ for (int j = 0; j < things.length; ++j) {
+ ThingDocument thing = things[j];
+ PossessionDocument possDoc = client.createPossession(templateIdMap.get(thing.getTemplateID()));
+ possDoc = client.addPossessionToSpace(possDoc.getPossessionID(), realSpaceDoc.getSpaceID());
+ ThingDocument newThingDoc = client.getThingDocument(realSpaceDoc.getSpaceID(), possDoc.getThingID());
+ newThingDoc.setOrientation(thing.getOrientation());
+ newThingDoc.setTranslation(thing.getTranslation());
+ newThingDoc.setSplinePath(thing.getSplinePath());
+ newThingDoc.setScale(thing.getScale());
+ client.updateThing(realSpaceDoc.getSpaceID(), newThingDoc);
+ }
+ long realSpaceID = realSpaceDoc.getSpaceID();
+ client.setSpaceSeaLevel(realSpaceID, fakeSpaceDoc.getSeaLevel());
+ client.setSpaceMaxGuests(realSpaceID, fakeSpaceDoc.getMaxGuests());
+ client.setSpaceDisplayName(realSpaceID, fakeSpaceDoc.getDisplayName());
+ client.setSpaceSeaLevel(realSpaceID, fakeSpaceDoc.getSeaLevel());
+ getLog().info("Patched up space "+realSpaceDoc.getDisplayName());
+
+ } catch (IOException e) {
+ throw new MojoExecutionException("IOException patching space (" + fakeSpaceDoc.getDisplayName() + ":" + fakeSpaceDoc.getSpaceID() + ")", e);
+ }
+ }
+
+ }
+
+ private void readSpace(WebAPIClient client, File candidate) throws MojoExecutionException {
+ String name = candidate.getName();
+ String num = name.substring(SPACE_PREFIX.length());
+ int spaceFakeId = -189;
+ try {
+ spaceFakeId = Integer.parseInt(num);
+ } catch (NumberFormatException e) {
+ getLog().error("Badly formed space name:" + name + ". Ignoring.");
+ }
+ if (spaceFakeId == -189) {
+ return;
+ }
+ try {
+ FileInputStream inputStream = new FileInputStream(candidate);
+ String docContent = StreamUtils.readInput(inputStream);
+ SpaceDocument doc = new SpaceDocument(XMLElement.parseElementFromString(docContent));
+ spaces.add(doc);
+ inputStream.close();
+ } catch (IOException e) {
+ throw new MojoExecutionException("IO Error reading space", e);
+ }
+
+ }
+
+ private void uploadTemplate(WebAPIClient client, File candidate) throws MojoExecutionException {
+ String name = candidate.getName();
+ int templateFakeId = dirNameToTemplateNumber(candidate);
+
+ getLog().info("Uploading template #" + templateFakeId + " to " + serviceURI);
+ File[] objs = candidate.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".obj");
+ }
+ });
+ if (objs.length != 1) {
+ throw new MojoExecutionException("Badly formed directory " + name + ". Should have 1 obj file but has " + objs.length);
+ }
+ try {
+ TemplateDocument doc = fileNameToTemplateDocument(client, objs[0]);
+
+ InputStream objStream = new FileInputStream(objs[0]);
+ client.uploadTemplateGeometryStream(username, doc.getTemplateID(), 0, objStream);
+
+ templateIdMap.put(new Long(templateFakeId), new Long(doc.getTemplateID()));
+ getLog().info("Created template from " + objs[0].getName() + " [" + templateFakeId + " -> " + doc.getTemplateID() + "]");
+
+ File[] notObjs = candidate.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return !name.endsWith(".obj");
+ }
+ });
+ for (int i = 0; i < notObjs.length; ++i) {
+ File supportFile = notObjs[i];
+ String supportName = supportFile.getName();
+ if (supportFile.getName().endsWith(".js")) {
+ String script = StreamUtils.readInput(new FileInputStream(supportFile));
+ client.updateTemplateScript(username, doc.getTemplateID(), script);
+ getLog().info("Uploaded script file:" + supportName);
+ } else {
+ if ((!(supportName.endsWith(".gif"))) && (!(supportName.endsWith(".jpg"))) && (!(supportName.endsWith(".png"))) && (!(supportName.endsWith(".mtl")))) {
+
+ if ((!(supportName.endsWith(".blend"))) && (!(supportName.endsWith(".3DS"))) && (!(supportName.endsWith(".txt"))) && (!(supportName.equals(".svn")))) {
+ getLog().warn("Don't know what to do with file " + supportName + ". Ignoring.");
+ }
+ continue;
+ }
+ FileInputStream supportStream = new FileInputStream(supportFile);
+ client.uploadTemplateResourceStream(username, doc.getTemplateID(), supportName, supportStream);
+ getLog().info("Uploaded support file:" + supportName);
+ }
+ }
+
+ } catch (IOException e) {
+ throw new MojoExecutionException("IO Error in upload", e);
+ }
+ }
+
}
\ No newline at end of file
Added: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java (rev 0)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java 2007-09-05 23:18:49 UTC (rev 371)
@@ -0,0 +1,158 @@
+package com.ogoglio.plugin;
+
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.FileWriter;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.HashMap;
+
+import nanoxml.XMLElement;
+
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+
+import com.ogoglio.client.WebAPIClient;
+import com.ogoglio.util.StreamUtils;
+import com.ogoglio.xml.SpaceDocument;
+import com.ogoglio.xml.TemplateDocument;
+import com.ogoglio.xml.ThingDocument;
+
+/**
+ * @goal reverse
+ */
+public class ReverseMojo extends OgServiceMojoBase {
+ /**
+ * @parameter
+ */
+ private File reverseFile;
+
+ public void execute() throws MojoExecutionException, MojoFailureException {
+ WebAPIClient client = validateArgsAndConnect();
+ HashMap<String,Long> displayNameToLocalId = new HashMap<String, Long>();
+ HashMap<Long,Long> remoteIdTolocalId = new HashMap<Long, Long>();
+
+ long localThingId=1,localPossId=1;
+
+ if (client==null) {
+ return;
+ }
+
+ if (reverseFile==null) {
+ getLog().info("No reverse file configured. Mojo ignored.");
+ return;
+ }
+
+ if ((!reverseFile.isFile()) || (!reverseFile.canRead())) {
+ throw new MojoExecutionException("Can't read reverse file "+reverseFile.getAbsolutePath());
+ }
+
+ SpaceDocument origSpaceDoc = buildTemplateMaps(displayNameToLocalId,
+ remoteIdTolocalId);
+
+ int localSpaceId=getNextLocalSpaceId();
+
+ SpaceDocument result = rewhackSpaceDocument(remoteIdTolocalId,
+ localThingId, localPossId, origSpaceDoc, localSpaceId);
+
+ try {
+ writeSpaceDoc(result,localSpaceId);
+ } catch (IOException e) {
+ throw new MojoExecutionException(e,"IOException","can't write output file");
+ }
+ }
+
+ private SpaceDocument rewhackSpaceDocument(
+ HashMap<Long, Long> remoteIdTolocalId, long localThingId,
+ long localPossId, SpaceDocument origSpaceDoc, int localSpaceId) {
+ SpaceDocument result = new SpaceDocument(localSpaceId,origSpaceDoc.getDisplayName(),origSpaceDoc.getOwnerUsername(),
+ true /*origSpaceDoc.getPublished()*/,origSpaceDoc.getMaxGuests(),origSpaceDoc.getDisplaySea(),
+ origSpaceDoc.getSeaLevel(),origSpaceDoc.getSimID());
+
+ ThingDocument[] things=origSpaceDoc.getThingDocuments();
+ for (int i=0; i<things.length;++i) {
+ ThingDocument remoteThing=things[i];
+ ThingDocument localThing=new ThingDocument(localThingId++,remoteThing.getDisplayName(),
+ remoteIdTolocalId.get(new Long(remoteThing.getTemplateID())).longValue(),
+ remoteThing.getTemplateOwner(),remoteThing.getOwnerUsername(),
+ localPossId++, remoteThing.getTransform(),remoteThing.getSplinePath());
+ result.addThingDocument(localThing);
+ getLog().info("Fixed thing "+localThing.getDisplayName());
+ }
+ return result;
+ }
+
+ private SpaceDocument buildTemplateMaps(
+ HashMap<String, Long> displayNameToLocalId,
+ HashMap<Long, Long> remoteIdTolocalId)
+ throws MojoExecutionException, MojoFailureException {
+ SpaceDocument origSpaceDoc=null;
+ try {
+ String revContent = StreamUtils.readInput(new FileInputStream(reverseFile));
+ origSpaceDoc = new SpaceDocument(XMLElement.parseElementFromString(revContent));
+ } catch (IOException e) {
+ throw new MojoExecutionException(e,"IOException","Can't read space document "+reverseFile.getAbsolutePath());
+ }
+ File[] templateDirs= populateDir.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.startsWith(TEMPLATE_PREFIX);
+ }
+ });
+ File[] objectFiles=new File[templateDirs.length];
+ for (int i=0; i< templateDirs.length;++i) {
+ File[] objs = templateDirs[i].listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".obj");
+ }
+ });
+ if (objs.length!=1) {
+ throw new MojoExecutionException("Directory "+templateDirs[i].getName()+" has wrong number of object files:"+objs.length);
+ }
+ objectFiles[i]=objs[0];
+ }
+ for (int i=0; i<objectFiles.length;++i) {
+ String tName = fileToTemplateName(objectFiles[i]);
+ int num = dirNameToTemplateNumber(objectFiles[i].getParentFile());
+ displayNameToLocalId.put(tName,new Long(num));
+ }
+ TemplateDocument[] mentioned = origSpaceDoc.getTemplateDocuments();
+ for (int i=0; i<mentioned.length;++i) {
+ TemplateDocument candidate = mentioned[i];
+ String remoteDisplayName = candidate.getDisplayName();
+ if (!displayNameToLocalId.containsKey(remoteDisplayName)) {
+ throw new MojoFailureException("Can't find a local template with display name "+remoteDisplayName);
+ }
+ Long local=displayNameToLocalId.get(remoteDisplayName);
+ remoteIdTolocalId.put(new Long(candidate.getTemplateID()), local);
+ getLog().info("Mapped "+remoteDisplayName+" ["+candidate.getTemplateID()+" ->"+local+"]");
+ }
+ return origSpaceDoc;
+ }
+
+ private void writeSpaceDoc(SpaceDocument result, int localSpaceId) throws IOException {
+ FileWriter wr=new FileWriter(new File(populateDir,SPACE_PREFIX+localSpaceId));
+ wr.write(result.toString());
+ wr.close();
+ getLog().info("Wrote new space document:"+(SPACE_PREFIX+localSpaceId));
+ }
+
+ private int getNextLocalSpaceId() throws MojoExecutionException {
+ int attempt=1,TOO_BIG=500;
+ File f;
+ do {
+ attempt++;
+ f=new File(populateDir,SPACE_PREFIX+(attempt));
+ //sanity
+ if (attempt==TOO_BIG) {
+ break;
+ }
+ } while (f.exists());
+ if (attempt==TOO_BIG) {
+ throw new MojoExecutionException("Don't know why but there are way too many space documents...aborting at "+attempt);
+ }
+ return attempt-1;
+ }
+
+}
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-05 22:32:42 UTC (rev 370)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-05 23:18:49 UTC (rev 371)
@@ -190,7 +190,7 @@
</webResources>
</configuration>
</plugin>
- <!-- Our plugin config for building templates -->
+ <!-- Our plugin config for building templates and doing stuffing of data -->
<plugin>
<groupId>com.ogoglio</groupId>
<artifactId>og-plugin</artifactId>
@@ -201,7 +201,8 @@
<serviceURI>${ogoglio.baseURL}</serviceURI>
<username>${ogoglio.bootstrapUser}</username>
<password>${ogoglio.bootstrapUserPW}</password>
- <baseDir>src/main/resources/populate</baseDir>
+ <populateDir>src/main/resources/populate</populateDir>
+ <reverseFile>/tmp/reverse.xml</reverseFile>
<goalPrefix>og</goalPrefix>
</configuration>
Modified: maven/trunk/ogoglio-server/src/main/resources/populate/space-1
===================================================================
--- maven/trunk/ogoglio-server/src/main/resources/populate/space-1 2007-09-05 22:32:42 UTC (rev 370)
+++ maven/trunk/ogoglio-server/src/main/resources/populate/space-1 2007-09-05 23:18:49 UTC (rev 371)
@@ -1,201 +1,52 @@
<space ownerusername="library" sealevel="0.0" simid="1"
- displayname="Tech Office Space" maxguests="0" displaysea="false"
- spaceid="1" published="false">
- <thing templateid="42" rz="0.0" ry="0.0" rx="0.0" rw="1.0"
- scalez="1.0" displayname="TV" scaley="1.0" templateowner="library"
- scalex="1.0" possessionid="2" thingid="2" z="10.0" y="0.0" x="0.0"
- ownerusername="library">
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.005" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Tube.001_Tube.002" scaley="1.0" scalex="1.0" z="0.0"
- y="0.0" x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.001" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.002_Mesh" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.003" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Tube_Tube.001" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Sphere_Sphere.001" scaley="1.0" scalex="1.0" z="0.0"
- y="0.0" x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.002" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.004" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- </thing>
- <thing templateid="28" rz="0.0" ry="0.0" rx="0.0" rw="1.0"
- scalez="1.0" displayname="WhiteBoard" scaley="1.0"
- templateowner="library" scalex="1.0" possessionid="3" thingid="4"
- z="-10.0" y="0.0" x="0.0" ownerusername="library">
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.003" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube" scaley="1.0" scalex="1.0" z="0.0" y="0.0" x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.002" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.004" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.001" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <page rz="-0.0" ry="1.0" width="4.0" pageid="1" rx="0.0"
- rw="0.0" scalez="1.0" scaley="1.0" scalex="1.0"
- contenttype="text/plain" z="0.1" y="2.0" x="0.0" height="2.0" />
- </thing>
- <thing templateid="21" rz="0.0" ry="0.0" rx="0.0" rw="1.0"
- scalez="1.0" displayname="memex" scaley="1.0" templateowner="library"
- scalex="1.0" possessionid="1" thingid="1" z="0.0" y="0.0" x="-10.0"
- ownerusername="library">
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.008_Black" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cube.001_Cube.002" scaley="1.0" scalex="1.0" z="0.0"
- y="0.0" x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder.003" scaley="1.0" scalex="1.0" z="0.0" y="0.0"
- x="0.0" />
- <shape rz="0.0" ry="0.0" rx="0.0" rw="1.0" scalez="1.0"
- shapename="Cylinder" scaley="1.0" scalex="1.0" z="0.0" ...
[truncated message content] |
|
From: <ian...@us...> - 2007-09-08 19:04:06
|
Revision: 388
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=388&view=rev
Author: iansmith
Date: 2007-09-08 12:04:09 -0700 (Sat, 08 Sep 2007)
Log Message:
-----------
More combat to allow protected instances of the server to be run.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-09-08 00:30:36 UTC (rev 387)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-09-08 19:04:09 UTC (rev 388)
@@ -22,11 +22,15 @@
public abstract class AbstractRemoteServlet extends MigratedResourceServlet {
+ public static final String OGOGLIO_INTERNAL_URL_KEY = "ogoglio/internalURL";
+
private WebAPIClient ogoglioClient = null;
private String ogoglioUsername = null;
private String ogoglioPassword = null;
+
+ private String internalURL = null;
public abstract String getOgoglioUsernameContextKey();
@@ -41,6 +45,9 @@
ArgumentUtils.assertNotEmpty(ogoglioUsername);
ogoglioPassword = (String) envCtx.lookup(getOgoglioPasswordContextKey());
ArgumentUtils.assertNotEmpty(ogoglioPassword);
+
+ internalURL = (String) envCtx.lookup(OGOGLIO_INTERNAL_URL_KEY);
+
} catch (NamingException e) {
throw new ServletException("Could not init EventServlet (probably forgot env variables in setup.xml): " + e);
}
@@ -50,7 +57,7 @@
if (ogoglioClient == null) {
try {
WebAPIClientWire wire = new WebAPIClientWire();
- URI serviceURI = new URI(getBaseUrl());
+ URI serviceURI = new URI(internalURL);
WebAPIDescriptor descriptor = new WebAPIDescriptor(serviceURI);
WebAPIAuthenticator authenticator = new WebAPIAuthenticatorFactory().authenticate(wire, descriptor, ogoglioUsername, ogoglioPassword);
ogoglioClient = new WebAPIClient(new WebAPIDescriptor(serviceURI), authenticator, wire);
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-08 00:30:36 UTC (rev 387)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-08 19:04:09 UTC (rev 388)
@@ -57,7 +57,7 @@
private boolean noCache = true;
- // WARNING: This is really, really easy to hose yourself with. This will get called
+ // WARNING: This is really, really easy to hose yourself with this. This will get called
// WARNING: during the init() of this class, so it is very easy to end up calling this
// WARNING: init method "too soon" in your init method, before you are fully initialized
public abstract SiteResource createBaseResource(ServletConfig servletConfig);
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-08 00:30:36 UTC (rev 387)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-08 19:04:09 UTC (rev 388)
@@ -198,7 +198,7 @@
<!-- these are for the populate -->
<configuration>
- <serviceURI>${ogoglio.baseURL}</serviceURI>
+ <serviceURI>${ogoglio.internalURL}</serviceURI>
<username>${ogoglio.bootstrapUser}</username>
<password>${ogoglio.bootstrapUserPW}</password>
<populateDir>src/main/resources/populate</populateDir>
Modified: maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-08 00:30:36 UTC (rev 387)
+++ maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-08 19:04:09 UTC (rev 388)
@@ -2,9 +2,6 @@
<Context reloadable="true" path="/og" >
<Realm className="org.apache.catalina.realm.MemoryRealm" />
- <tomcat-users>
-
- </tomcat-users>
<Resource name="jdbc/space" scope="Shareable"
type="javax.sql.DataSource" auth='Container'
factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
@@ -16,16 +13,12 @@
show_sql="false"
maxIdle="5"
maxActive="50" />
-
- <tomcat-users>
- <role rolename="admin"/>
- <user username="seattle" password="demolove" roles="demo"/>
- </tomcat-users>
<Environment name="ogoglio/oktoZapDB" value="false" type="java.lang.String"/> <!-- not running tests! -->
<Environment name="ogoglio/okToMigrateDB" value="${ogoglio.okToMigrateDB}" type="java.lang.String"/>
<Environment name="ogoglio/mediaURL" value="${ogoglio.mediaURL}" type="java.lang.String"/>
<Environment name="ogoglio/baseURL" value="${ogoglio.baseURL}" type="java.lang.String"/>
+ <Environment name="ogoglio/internalURL" value="${ogoglio.internalURL}" type="java.lang.String"/>
<Environment name="ogoglio/simsAllowRemoteAccess" value="true" type="java.lang.String" />
<Environment name="ogoglio/mediaDirectory" value="${ogoglio.mediaDirectory}" type="java.lang.String"/>
<Environment name="ogoglio/bootstrapUser" value="${ogoglio.bootstrapUser}" type="java.lang.String"/>
Modified: maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml 2007-09-08 00:30:36 UTC (rev 387)
+++ maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml 2007-09-08 19:04:09 UTC (rev 388)
@@ -41,7 +41,7 @@
</servlet-mapping>
<servlet-mapping>
- <servlet-name>SpaceServlet</servlet-name>test
+ <servlet-name>SpaceServlet</servlet-name>
<url-pattern>/space/*</url-pattern>
</servlet-mapping>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-08 20:35:19
|
Revision: 389
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=389&view=rev
Author: iansmith
Date: 2007-09-08 13:35:20 -0700 (Sat, 08 Sep 2007)
Log Message:
-----------
Removed all the references to 127.0.0.1 and replaced with values computed from the
settings.xml file. In principle, this will allow testing of machines in the cluster
from a remote host. For now, this is just cleanliness.
Modified Paths:
--------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/SpaceDuplicatorTest.java
maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
maven/trunk/ogoglio-server/src/test/resources/basic-config.properties
maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java
Removed Paths:
-------------
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web-demo.xml
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/MultiuserTests.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -174,6 +174,8 @@
}
MultiuserTests tests = null;
try {
+ //If you are going to run a test like this, these should be pulled from
+ //the properties files....
//String serviceURI = "http://127.0.0.1:8080/og/";
//String spaceURI = "http://127.0.0.1:8080/og/space/1/";
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -134,10 +134,12 @@
if (fullScreen) {
dim = new Dimension(device.getDisplayMode().getWidth(), device.getDisplayMode().getWidth());
}
- String serviceURI = "http://127.0.0.1:8080/og/";
- String loginCookie = null;
+ String serviceURI=null;
+ String loginCookie=null;
try {
- PropStorage ps = new PropStorage();
+ PropStorage ps=new PropStorage();
+ ps.loadPropertySet(PropStorage.BASIC_PROPS);
+ serviceURI = ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseUrl");
ps.loadPropertySet(PropStorage.BOOTSTRAP_PROPS);
WebAPIAuthenticator authenticator = new WebAPIAuthenticator(new WebAPIClientWire(), new WebAPIDescriptor(new URI(serviceURI)), ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUser"), ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUserPW"));
loginCookie = authenticator.getAuthCookie();
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -87,7 +87,11 @@
public void setUp() {
try {
- serviceURI1 = new URI("http://127.0.0.1:8080/og/"); //best choice: 127.0.0.1 for tests
+ PropStorage ps=new PropStorage();
+ if (!ps.loadPropertySet(PropStorage.BASIC_PROPS)) {
+ fail("couldn't load property set (BASIC)");
+ }
+ serviceURI1 = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseUrl"));
linkURI1 = new URI("http://example.com/");
wire1 = new WebAPIClientWire();
descriptor1 = new WebAPIDescriptor(serviceURI1);
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/SpaceDuplicatorTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/SpaceDuplicatorTest.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/SpaceDuplicatorTest.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -13,6 +13,7 @@
import com.ogoglio.client.WebAPIClient;
import com.ogoglio.client.WebAPIClientWire;
import com.ogoglio.client.WebAPIDescriptor;
+import com.ogoglio.util.PropStorage;
import com.ogoglio.xml.DoorDocument;
import com.ogoglio.xml.PositionedDocument;
import com.ogoglio.xml.SpaceDocument;
@@ -42,7 +43,11 @@
try {
spaceID1 = 1;
spaceID2 = 2;
- serviceURI1 = new URI("http://127.0.0.1:8080/og/");
+ PropStorage ps=new PropStorage();
+ if (!ps.loadPropertySet(PropStorage.BASIC_PROPS)) {
+ fail("couldn't load property set (BASIC)");
+ }
+ serviceURI1 = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseUrl"));
descriptor = new WebAPIDescriptor(serviceURI1);
wire = new WebAPIClientWire();
auth = new WebAPIAuthenticator(wire, descriptor, ClientTest.USERNAME1, ClientTest.PASSWORD1);
Modified: maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-09-08 20:35:20 UTC (rev 389)
@@ -1,4 +1,6 @@
# basic info needed for some tests
ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
ogoglio.baseUrl = ${ogoglio.baseURL}
+ogoglio.internalUrl = ${ogoglio.internalURL}
+ogoglio.baseSimUrl = ${ogoglio.baseSimURL}
Deleted: maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web-demo.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web-demo.xml 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web-demo.xml 2007-09-08 20:35:20 UTC (rev 389)
@@ -1,94 +0,0 @@
-<?xml version="1.0" encoding="ISO-8859-1"?>
-<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">
- <servlet>
- <servlet-name>AccountServlet</servlet-name>
- <servlet-class>com.ogoglio.site.AccountServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet>
- <servlet-name>AuthServlet</servlet-name>
- <servlet-class>com.ogoglio.site.AuthServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet>
- <servlet-name>SpaceServlet</servlet-name>
- <servlet-class>com.ogoglio.site.SpaceServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet>
- <servlet-name>MediaServlet</servlet-name>
- <servlet-class>com.ogoglio.media.site.MediaServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet>
- <servlet-name>SimServlet</servlet-name>
- <servlet-class>com.ogoglio.sim.site.SimServlet</servlet-class>
- <load-on-startup>1</load-on-startup>
- </servlet>
-
- <servlet-mapping>
- <servlet-name>AccountServlet</servlet-name>
- <url-pattern>/account/*</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>AuthServlet</servlet-name>
- <url-pattern>/auth/*</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>SpaceServlet</servlet-name>test
- <url-pattern>/space/*</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>SimServlet</servlet-name>
- <url-pattern>/sim/*</url-pattern>
- </servlet-mapping>
-
- <servlet-mapping>
- <servlet-name>MediaServlet</servlet-name>
- <url-pattern>/media/*</url-pattern>
- </servlet-mapping>
-
- <error-page>
- <error-code>404</error-code>
- <location>/notFound.html</location>
- </error-page>
-
-<!-- Start Authentication -->
-
- <security-constraint>
- <web-resource-collection>
- <web-resource-name>SecurityRestriction</web-resource-name>
- <description>Demo For Friends Only</description>
- <url-pattern>/</url-pattern>
- <http-method>GET</http-method>
- <http-method>POST</http-method>
- <http-method>PUT</http-method>
- <http-method>DELETE</http-method>
- </web-resource-collection>
- <auth-constraint>
- <description>Demo Users Group</description>
- <role-name>demo</role-name>
- </auth-constraint>
- <user-data-constraint>
- <transport-guarantee>NONE</transport-guarantee>
- </user-data-constraint>
- </security-constraint>
-
- <login-config>
- <auth-method>BASIC</auth-method>
- </login-config>
-
- <security-role>
- <description>Demo role</description>
- <role-name>demo</role-name>
- </security-role>
-
- <!-- End Authentication -->
-</web-app>
Modified: maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
===================================================================
--- maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -20,8 +20,6 @@
import com.ogoglio.appdev.migrate.MigrationSupport;
import com.ogoglio.appdev.migrate.test.DBZapTest;
import com.ogoglio.appdev.persist.PersistException;
-import com.ogoglio.client.WebAPIClient;
-import com.ogoglio.client.WebAPIDescriptor;
import com.ogoglio.media.MediaService;
import com.ogoglio.migrate.OgoglioServerMigration;
import com.ogoglio.persist.AccountPersistTasks;
@@ -83,7 +81,11 @@
level2 = "pro";
try {
- simURI1 = new URI("http://127.0.0.1:8080/sim");
+ PropStorage ps=new PropStorage();
+ if (!ps.loadPropertySet(PropStorage.BASIC_PROPS)) {
+ fail("Can't load prop set (BASIC)");
+ }
+ simURI1 = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseSimUrl"));
} catch (URISyntaxException e) {
fail("bad URI:"+e.getMessage());
}
Modified: maven/trunk/ogoglio-server/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-server/src/test/resources/basic-config.properties 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-server/src/test/resources/basic-config.properties 2007-09-08 20:35:20 UTC (rev 389)
@@ -1,4 +1,5 @@
# basic info needed for some tests
ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
ogoglio.baseUrl = ${ogoglio.baseURL}
-ogoglio.mediaDirectory = ${ogoglio.mediaDirectory}
\ No newline at end of file
+ogoglio.mediaDirectory = ${ogoglio.mediaDirectory}
+ogoglio.baseSimUrl = ${ogoglio.baseSimURL}
Modified: maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java
===================================================================
--- maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java 2007-09-08 19:04:09 UTC (rev 388)
+++ maven/trunk/ogoglio-viewer-applet/src/test/java/com/ogoglio/viewer/test/AppletTestWindow.java 2007-09-08 20:35:20 UTC (rev 389)
@@ -45,12 +45,6 @@
EnvironmentStub clientStub1 = null;
- String host = "127.0.0.1:8080";
-
- String serviceURI = "http://" + host + "/og/";
-
- URL codeBase = getURL(serviceURI);
-
static boolean fullScreen = false;
public AppletTestWindow() {
@@ -70,9 +64,11 @@
Log.error("Can't find basic properties!");
System.exit(1);
}
+ String serviceURI=ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseURL");
HashMap parameters1 = new HashMap();
try {
- WebAPIAuthenticator authenticator = new WebAPIAuthenticator(new WebAPIClientWire(), new WebAPIDescriptor(new URI(serviceURI)),
+ WebAPIAuthenticator authenticator = new WebAPIAuthenticator(new WebAPIClientWire(),
+ new WebAPIDescriptor(new URI(serviceURI)),
ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUser"),
ps.getKeyFromSet(PropStorage.BOOTSTRAP_PROPS, "bootstrapUserPW"));
parameters1.put(WebConstants.AUTH_COOKIE, authenticator.getAuthCookie());
@@ -116,11 +112,17 @@
}
public URL getCodeBase() {
- return codeBase;
+ PropStorage ps=new PropStorage();
+ if (!ps.loadPropertySet(PropStorage.BASIC_PROPS)) {
+ Log.error("Can't find basic properties!");
+ System.exit(1);
+ }
+ String serviceURI=ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseURL");
+ return getURL(serviceURI);
}
public URL getDocumentBase() {
- return codeBase;
+ return getCodeBase();
}
public String getParameter(String name) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-10 22:36:05
|
Revision: 390
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=390&view=rev
Author: iansmith
Date: 2007-09-10 15:36:05 -0700 (Mon, 10 Sep 2007)
Log Message:
-----------
Removed config cruft for when I was trying to do security.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-09-08 20:35:20 UTC (rev 389)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-09-10 22:36:05 UTC (rev 390)
@@ -18,20 +18,17 @@
import com.ogoglio.client.WebAPIClientWire;
import com.ogoglio.client.WebAPIDescriptor;
import com.ogoglio.util.ArgumentUtils;
+import com.ogoglio.util.Log;
import com.ogoglio.xml.AuthDocument;
public abstract class AbstractRemoteServlet extends MigratedResourceServlet {
- public static final String OGOGLIO_INTERNAL_URL_KEY = "ogoglio/internalURL";
-
private WebAPIClient ogoglioClient = null;
private String ogoglioUsername = null;
private String ogoglioPassword = null;
- private String internalURL = null;
-
public abstract String getOgoglioUsernameContextKey();
public abstract String getOgoglioPasswordContextKey();
@@ -39,6 +36,8 @@
public void init(ServletConfig config) throws ServletException {
super.init(config);
try {
+ Log.info("In AbstractRemoteServlet---init");
+ System.out.println("In AbstractRemoveServlet---init no log");
Context envCtx = (Context) initCtx.lookup("java:comp/env");
ogoglioUsername = (String) envCtx.lookup(getOgoglioUsernameContextKey());
@@ -46,8 +45,6 @@
ogoglioPassword = (String) envCtx.lookup(getOgoglioPasswordContextKey());
ArgumentUtils.assertNotEmpty(ogoglioPassword);
- internalURL = (String) envCtx.lookup(OGOGLIO_INTERNAL_URL_KEY);
-
} catch (NamingException e) {
throw new ServletException("Could not init EventServlet (probably forgot env variables in setup.xml): " + e);
}
@@ -57,7 +54,7 @@
if (ogoglioClient == null) {
try {
WebAPIClientWire wire = new WebAPIClientWire();
- URI serviceURI = new URI(internalURL);
+ URI serviceURI = new URI(baseUrl);
WebAPIDescriptor descriptor = new WebAPIDescriptor(serviceURI);
WebAPIAuthenticator authenticator = new WebAPIAuthenticatorFactory().authenticate(wire, descriptor, ogoglioUsername, ogoglioPassword);
ogoglioClient = new WebAPIClient(new WebAPIDescriptor(serviceURI), authenticator, wire);
Modified: maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-09-08 20:35:20 UTC (rev 389)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-09-10 22:36:05 UTC (rev 390)
@@ -1,6 +1,5 @@
# basic info needed for some tests
ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
ogoglio.baseUrl = ${ogoglio.baseURL}
-ogoglio.internalUrl = ${ogoglio.internalURL}
ogoglio.baseSimUrl = ${ogoglio.baseSimURL}
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-08 20:35:20 UTC (rev 389)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-10 22:36:05 UTC (rev 390)
@@ -198,7 +198,7 @@
<!-- these are for the populate -->
<configuration>
- <serviceURI>${ogoglio.internalURL}</serviceURI>
+ <serviceURI>${ogoglio.baseURL}</serviceURI>
<username>${ogoglio.bootstrapUser}</username>
<password>${ogoglio.bootstrapUserPW}</password>
<populateDir>src/main/resources/populate</populateDir>
Modified: maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-08 20:35:20 UTC (rev 389)
+++ maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-10 22:36:05 UTC (rev 390)
@@ -18,7 +18,6 @@
<Environment name="ogoglio/okToMigrateDB" value="${ogoglio.okToMigrateDB}" type="java.lang.String"/>
<Environment name="ogoglio/mediaURL" value="${ogoglio.mediaURL}" type="java.lang.String"/>
<Environment name="ogoglio/baseURL" value="${ogoglio.baseURL}" type="java.lang.String"/>
- <Environment name="ogoglio/internalURL" value="${ogoglio.internalURL}" type="java.lang.String"/>
<Environment name="ogoglio/simsAllowRemoteAccess" value="true" type="java.lang.String" />
<Environment name="ogoglio/mediaDirectory" value="${ogoglio.mediaDirectory}" type="java.lang.String"/>
<Environment name="ogoglio/bootstrapUser" value="${ogoglio.bootstrapUser}" type="java.lang.String"/>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-12 17:43:27
|
Revision: 398
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=398&view=rev
Author: iansmith
Date: 2007-09-12 10:43:30 -0700 (Wed, 12 Sep 2007)
Log Message:
-----------
Fixed the build so it should always include the applets.
Integration tests now check that applets are present.
Modified Paths:
--------------
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-12 13:08:35 UTC (rev 397)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-12 17:43:30 UTC (rev 398)
@@ -19,6 +19,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
+import java.net.URISyntaxException;
import java.text.ParseException;
import java.util.Date;
import java.util.Random;
@@ -102,9 +103,27 @@
}
public void tearDown() {
+ }
+ public void testAppletsCanBeDownloaded() throws IOException, URISyntaxException {
+ checkSupportFile("ogoglio-viewer-applet.jar");
+ checkSupportFile("ogoglio-test-applet.jar");
+ checkSupportFile("ogoglio-common.jar");
+ checkSupportFile("ogoglio-body-editor-applet.jar");
}
+ private void checkSupportFile(String name) throws URISyntaxException, IOException {
+ URI supportURI=new URI(serviceURI1.toString()+name);
+ InputStream is=null;
+ try {
+ is=wire1.performGET(supportURI, null);
+ } catch (IOException e) {
+ fail("unable to get the support URI:"+supportURI+" (exception:"+e.getMessage()+")");
+ }
+ assertNotNull(is);
+ is.close();
+ }
+
public void testWebAdmin() throws AuthenticationFailedException, IOException {
PropStorage ps = new PropStorage();
if (ps.loadPropertySet(PropStorage.BOOTSTRAP_PROPS) == false) {
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-12 13:08:35 UTC (rev 397)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-12 17:43:30 UTC (rev 398)
@@ -132,7 +132,7 @@
<executions>
<execution>
<id>copy-applets</id>
- <phase>package</phase>
+ <phase>test</phase>
<goals>
<goal>copy</goal>
</goals>
@@ -140,7 +140,6 @@
<outputDirectory>
${project.build.directory}/${pom.artifactId}-${version}
</outputDirectory>
- <overwriteIfNewer>true</overwriteIfNewer>
<stripVersion>true</stripVersion>
<artifactItems>
<artifactItem>
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-09-12 13:08:35 UTC (rev 397)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-09-12 17:43:30 UTC (rev 398)
@@ -41,11 +41,11 @@
if (!(ourURI.equals(sim.getSimURI()))) {
//make it point to us
sim.setSimURI(ourURI);
- sim.setActive(true);
+ //sim.setActive(true);
SimPersistTasks.update(sim, sessionFactory);
} else {
if (!sim.isActive()) {
- sim.setActive(true);
+ //sim.setActive(true);
SimPersistTasks.update(sim, sessionFactory);
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-18 15:05:24
|
Revision: 414
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=414&view=rev
Author: iansmith
Date: 2007-09-18 08:05:26 -0700 (Tue, 18 Sep 2007)
Log Message:
-----------
Added support for spaces to know their own last modified time. og:populate mojo now respects last update time on template geometry files, template support files, and space files in the populate directory.
This change is a DB breaker, does require a drop/add to work properly.
Added support for poms that derive server port info from the settings.xml file. Requires addition of "ogoglio.port" property to your settings.xml.
Modified Paths:
--------------
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/SpaceDocument.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/TemplateDocument.java
maven/trunk/ogoglio-common/src/test/java/com/ogoglio/xml/test/XMLTest.java
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpaceRecord.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/TemplateSupportFileRecord.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/xml/server/DocumentFactory.java
maven/trunk/ogoglio-server/src/main/resources/hibernate/migration-1.xml
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/sim/script/test/ScriptTest.java
Modified: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/PopulateMojo.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -5,14 +5,17 @@
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
-import java.util.ArrayList;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.util.Date;
import java.util.HashMap;
-import java.util.List;
+import java.util.Iterator;
+import java.util.Locale;
+import java.util.Map;
import nanoxml.XMLElement;
import org.apache.maven.plugin.MojoExecutionException;
-import org.apache.maven.plugin.MojoFailureException;
import com.ogoglio.client.WebAPIClient;
import com.ogoglio.util.StreamUtils;
@@ -21,27 +24,40 @@
import com.ogoglio.xml.SettingDocument;
import com.ogoglio.xml.SpaceDocument;
import com.ogoglio.xml.TemplateDocument;
+import com.ogoglio.xml.TemplateSupportFileDocument;
import com.ogoglio.xml.ThingDocument;
/**
* @goal populate
*/
public class PopulateMojo extends OgServiceMojoBase {
- private HashMap<Long, Long> templateIdMap = new HashMap<Long, Long>();
+ private Map<Long, Long> templateIdMap = new HashMap<Long, Long>();
- private List<SpaceDocument> spaces = new ArrayList<SpaceDocument>();
+ private Map<Long,SpaceDocument> localSpaces = new HashMap<Long,SpaceDocument>();
+ private Map<String,SpaceDocument> serveSpacerNameToSpaceDoc = new HashMap<String, SpaceDocument>();
+ private Map<String, TemplateDocument> existingServerTemplates = null;
+
+ public static final DateFormat fmt = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL, Locale.US);
+
public void execute() throws MojoExecutionException {
WebAPIClient client = validateArgsAndConnect();
if (client == null) {
return;
}
+
+ try {
+ existingServerTemplates = getAllServerTemplates(client);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Couldn't get the existing templates", e);
+ }
+
File[] templates = populateDir.listFiles();
for (int i = 0; i < templates.length; ++i) {
File candidate = templates[i];
if (candidate.getName().startsWith(TEMPLATE_PREFIX)) {
- uploadTemplate(client, candidate);
+ uploadTemplate(client, candidate, existingServerTemplates);
} else if (candidate.getName().startsWith(SPACE_PREFIX)) {
readSpace(client, candidate);
} else {
@@ -50,17 +66,56 @@
}
}
}
-
+ serveSpacerNameToSpaceDoc=getAllServerSpaces(client);
patchSpaces(client);
}
- private SpaceDocument[] patchSpaces(WebAPIClient client) throws MojoExecutionException {
+ private Map<String,SpaceDocument> getAllServerSpaces(WebAPIClient client) throws MojoExecutionException{
+ try {
+ Map<String,SpaceDocument> result=new HashMap<String,SpaceDocument>();
+ SpaceDocument[] doc=client.getAccountSpaceDocuments(username);
+ for (int i=0; i<doc.length;++i) {
+ result.put(doc[i].getDisplayName(),doc[i]);
+ }
+ return result;
+ } catch (IOException e) {
+ throw new MojoExecutionException("Unable to read server set of space documents",e);
+ }
+ }
+
+ private Map<String, TemplateDocument> getAllServerTemplates(WebAPIClient client) throws IOException {
+ Map<String, TemplateDocument> result = new HashMap<String, TemplateDocument>();
+
+ TemplateDocument[] doc = client.getTemplateDocuments(username);
+ getLog().info("Checking existing server templates...total of:"+doc.length);
+ for (int i = 0; i < doc.length; ++i) {
+ result.put(doc[i].getDisplayName(), doc[i]);
+ }
+ return result;
+ }
+
+ private void patchSpaces(WebAPIClient client) throws MojoExecutionException {
SpaceDocument fakeSpaceDoc, realSpaceDoc;
- SpaceDocument[] result=new SpaceDocument[spaces.size()];
+ Iterator<Long> iter=localSpaces.keySet().iterator();
- for (int i = 0; i < spaces.size(); ++i) {
- fakeSpaceDoc = spaces.get(i);
+ while (iter.hasNext()) {
try {
+ long localModTime = iter.next();
+ fakeSpaceDoc = localSpaces.get(localModTime);
+ if (serveSpacerNameToSpaceDoc.containsKey(fakeSpaceDoc.getDisplayName())) {
+ realSpaceDoc = serveSpacerNameToSpaceDoc.get(fakeSpaceDoc.getDisplayName());
+
+ Date fileModified=new Date(localModTime);
+ Date serverModified = TemplateSupportFileDocument.fmt.parse(realSpaceDoc.getLastModifiedAsUTC());
+ if (fileModified.before(serverModified)) {
+ getLog().info("Not patching space document "+realSpaceDoc.getDisplayName()+". Server copy is newer.");
+ continue;
+ } else {
+ //need to torch the server version b/c it's too old
+ client.deleteSpace(realSpaceDoc.getSpaceID());
+ getLog().info("Deleted old server version of "+realSpaceDoc.getDisplayName()+" ["+realSpaceDoc.getSpaceID()+"]");
+ }
+ }
realSpaceDoc = client.createSpace(fakeSpaceDoc.getDisplayName());
if (realSpaceDoc == null) {
throw new MojoExecutionException("Could not create a space for population: " + fakeSpaceDoc.getDisplayName());
@@ -94,14 +149,13 @@
client.createDoor(realSpaceID, doorDocs[j].getTemplateID(), doorDocs[j].getTemplateOwner(), doorDocs[j].getDisplayName(), doorDocs[j].getLink(), doorDocs[j].getTransform());
}
- getLog().info("Patched up space " + realSpaceDoc.getDisplayName());
- result[i]=realSpaceDoc;
+ getLog().info("Patched up space " + realSpaceDoc.getDisplayName() +" ["+realSpaceDoc.getSpaceID()+"]");
+ } catch (ParseException e) {
+ throw new MojoExecutionException("Parse exception patching space", e);
} catch (IOException e) {
- throw new MojoExecutionException("IOException patching space (" + fakeSpaceDoc.getDisplayName() + ":" + fakeSpaceDoc.getSpaceID() + ")", e);
+ throw new MojoExecutionException("IOException patching space", e);
}
}
- return result;
-
}
private void readSpace(WebAPIClient client, File candidate) throws MojoExecutionException {
@@ -120,7 +174,7 @@
FileInputStream inputStream = new FileInputStream(candidate);
String docContent = StreamUtils.readInput(inputStream);
SpaceDocument doc = new SpaceDocument(XMLElement.parseElementFromString(docContent));
- spaces.add(doc);
+ localSpaces.put(candidate.lastModified(),doc);
inputStream.close();
} catch (IOException e) {
throw new MojoExecutionException("IO Error reading space", e);
@@ -128,11 +182,10 @@
}
- private void uploadTemplate(WebAPIClient client, File candidate) throws MojoExecutionException {
+ private void uploadTemplate(WebAPIClient client, File candidate, Map<String, TemplateDocument> existing) throws MojoExecutionException {
String name = candidate.getName();
- int templateFakeId = dirNameToTemplateNumber(candidate);
+ long templateFakeId = dirNameToTemplateNumber(candidate);
- getLog().info("Uploading template #" + templateFakeId + " to " + serviceURI);
File[] objs = candidate.listFiles(new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.endsWith(".obj");
@@ -141,13 +194,23 @@
if (objs.length != 1) {
throw new MojoExecutionException("Badly formed directory " + name + ". Should have 1 obj file but has " + objs.length);
}
+
+ String templateVisibleName=fileToTemplateName(objs[0]);
+ if (!checkFileTemplateIsNewer(client, candidate, existing, templateVisibleName)) {
+ getLog().info("Not uploading template " + templateVisibleName + ". Server copy is newer.");
+ templateIdMap.put(templateFakeId,existing.get(templateVisibleName).getTemplateID());
+ return;
+ } else {
+ getLog().info("Uploading template #" + templateFakeId + " to " + serviceURI);
+ }
+
try {
TemplateDocument doc = fileNameToTemplateDocument(client, objs[0]);
InputStream objStream = new FileInputStream(objs[0]);
client.uploadTemplateGeometryStream(username, doc.getTemplateID(), 0, objStream);
- templateIdMap.put(new Long(templateFakeId), new Long(doc.getTemplateID()));
+ templateIdMap.put(templateFakeId, doc.getTemplateID());
getLog().info("Created template from " + objs[0].getName() + " [" + templateFakeId + " -> " + doc.getTemplateID() + "]");
File[] notObjs = candidate.listFiles(new FilenameFilter() {
@@ -181,4 +244,114 @@
}
}
+ private boolean checkFileTemplateIsNewer(WebAPIClient client, File candidate, Map<String, TemplateDocument> existing, String displayName) throws MojoExecutionException {
+ //is it even on server?
+ if (!existing.containsKey(displayName)) {
+ return true;
+ }
+
+ TemplateDocument serverCopy = existing.get(displayName);
+
+ //first check support files
+ File[] notObjs = candidate.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return !name.endsWith(".obj");
+ }
+ });
+
+ //walk support files
+ for (int i = 0; i < notObjs.length; ++i) {
+ File supportFile = notObjs[i];
+ String supportName = supportFile.getName();
+ String modTime = null;
+ if (supportName.endsWith(".js")) {
+ if (!serverCopy.hasScriptFile()) {
+ getLog().info("You have added a javascript file since the last server update.");
+ return true;
+ }
+ modTime = serverCopy.getScriptModifiedTime();
+ } else if ((!(supportName.endsWith(".gif"))) && (!(supportName.endsWith(".jpg"))) && (!(supportName.endsWith(".png"))) && (!(supportName.endsWith(".mtl")))) {
+ continue;
+ } else {
+ modTime = serverCopy.getSupportFileModifiedTime(supportName);
+ }
+ try {
+ //if there is no modtime, then the file doesn't exist on the server
+ if (modTime == null) {
+ getLog().info("Added support file " + supportName + " to template since server copy created");
+ client.deleteTemplate(serverCopy.getTemplateID());
+ return true;
+ }
+ //modtime is now set to what the server thinks the modtime is
+ Date serverTime = fmt.parse(modTime);
+ if (serverTime.before(new Date(supportFile.lastModified()))) {
+ getLog().info("File " + supportFile + " has been modified since last upload to server...");
+ client.deleteTemplate(serverCopy.getTemplateID());
+ return true; //we can bail out now
+ }
+ } catch (IOException e) {
+ throw new MojoExecutionException("unable to delete server copy of template " + serverCopy.getDisplayName(), e);
+ } catch (ParseException e) {
+ throw new MojoExecutionException("unable to comprehend modified time", e);
+ }
+ }
+
+ //at this point we've checked the files that exist on the client side, but we might
+ //have deleted one
+ boolean destroyServerTemplate = false;
+ //special case for js
+ if (serverCopy.hasScriptFile()) {
+ File[] jsFiles = candidate.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".js");
+ }
+ });
+ if (jsFiles.length > 1) {
+ throw new MojoExecutionException("Only one script file is allowed per template (" + candidate.getPath() + ")");
+ }
+ if (jsFiles.length == 0) {
+ getLog().info("Javascript file removed since last server update.");
+ destroyServerTemplate = true;
+ }
+ }
+ //now support files
+ String name[] = serverCopy.getAllSupportFileNames();
+ for (int i = 0; i < name.length; ++i) {
+ File f = new File(candidate, name[i]);
+ if (!f.exists()) {
+ getLog().info("You have removed the file " + name[i] + " from the template.");
+ destroyServerTemplate = true;
+ break;
+ }
+ }
+ //check the obj file
+ File[] objs = candidate.listFiles(new FilenameFilter() {
+ public boolean accept(File dir, String name) {
+ return name.endsWith(".obj");
+ }
+ });
+ if (objs.length != 1) {
+ throw new MojoExecutionException("You should have exactly one object (geometry) file per template directory (was " + objs.length + ")");
+ }
+ try {
+ Date fileMod = new Date(objs[0].lastModified());
+ Date onServerMod = fmt.parse(serverCopy.getGeometryModifiedTime(0));
+ if (onServerMod.before(fileMod)) {
+ getLog().info("Local geometry file is newer than server copy.");
+ destroyServerTemplate = true;
+ }
+ //implement destruction
+ if (destroyServerTemplate) {
+ client.deleteTemplate(serverCopy.getTemplateID());
+ return true;
+ } else {
+ return false;
+ }
+ } catch (IOException e) {
+ throw new MojoExecutionException("unable to delete server copy of template " + serverCopy.getDisplayName(), e);
+ } catch (ParseException e) {
+ throw new MojoExecutionException("unable to comprehend modified time", e);
+ }
+ }
+
}
\ No newline at end of file
Modified: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/ReverseMojo.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -65,7 +65,7 @@
long localThingId = 1;
long localPossId = 1;
- SpaceDocument result = new SpaceDocument(localSpaceId, origSpaceDoc.getDisplayName(), origSpaceDoc.getOwnerUsername(), true /*origSpaceDoc.getPublished()*/, origSpaceDoc.getMaxGuests(), origSpaceDoc.getDisplaySea(), origSpaceDoc.getSeaLevel(), origSpaceDoc.getSimID());
+ SpaceDocument result = new SpaceDocument(localSpaceId, origSpaceDoc.getDisplayName(), origSpaceDoc.getOwnerUsername(), true /*origSpaceDoc.getPublished()*/, origSpaceDoc.getMaxGuests(), origSpaceDoc.getDisplaySea(), origSpaceDoc.getSeaLevel(), origSpaceDoc.getSimID(), null);
ThingDocument[] thingDocs = origSpaceDoc.getThingDocuments();
for (int i = 0; i < thingDocs.length; ++i) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClient.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClient.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -16,6 +16,7 @@
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
+import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;
@@ -37,6 +38,7 @@
import com.ogoglio.xml.SpaceDocument;
import com.ogoglio.xml.SpaceMemberDocument;
import com.ogoglio.xml.TemplateDocument;
+import com.ogoglio.xml.TemplateSupportFileDocument;
import com.ogoglio.xml.ThingDocument;
import com.ogoglio.xml.UserDocument;
@@ -68,7 +70,7 @@
}
public SpaceDocument createSpace(String spaceName) {
- SpaceDocument spaceDoc = new SpaceDocument(-1, spaceName, authenticator.getUsername(), false, 0, false, 0, -1);
+ SpaceDocument spaceDoc = new SpaceDocument(-1, spaceName, authenticator.getUsername(), false, 0, false, 0, -1, null);
try {
return new SpaceDocument(wire.sendAuthenticatedXML(descriptor.getSpacesURI(), spaceDoc.toString(), "POST", authenticator.getAuthCookie()));
} catch (IOException e) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/SpaceDocument.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/SpaceDocument.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/SpaceDocument.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -13,6 +13,8 @@
limitations under the License. */
package com.ogoglio.xml;
+import java.text.ParseException;
+
import nanoxml.XMLElement;
import com.ogoglio.util.ArgumentUtils;
@@ -37,11 +39,13 @@
public static final String SIM_ID = "simid";
+ public static final String LAST_MODIFIED="lastmodified";
+
public static final int MAX_SETTING_VALUE_SIZE = 10240;
XMLElement data = null;
- public SpaceDocument(long spaceID, String displayName, String ownerUsername, boolean published, int maxGuests, boolean displaySea, double seaLevel, long simID) {
+ public SpaceDocument(long spaceID, String displayName, String ownerUsername, boolean published, int maxGuests, boolean displaySea, double seaLevel, long simID, String lastModifiedGMT) {
data = new XMLElement(NAME);
if (spaceID != -1) {
@@ -63,6 +67,10 @@
data.setAttribute(DISPLAY_SEA, displaySea);
data.setAttribute(SEA_LEVEL, seaLevel);
+ if (lastModifiedGMT!=null) {
+ data.setAttribute(LAST_MODIFIED, lastModifiedGMT);
+ }
+
if (simID != -1) {
data.setAttribute(SIM_ID, simID);
}
@@ -222,4 +230,8 @@
public double getSeaLevel() {
return data.getDoubleAttribute(SEA_LEVEL, 0);
}
+
+ public String getLastModifiedAsUTC() {
+ return data.getStringAttribute(LAST_MODIFIED,null);
+ }
}
\ No newline at end of file
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/TemplateDocument.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/TemplateDocument.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/TemplateDocument.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -181,4 +181,13 @@
}
return (String)elem.getAttribute(LAST_MODIFIED);
}
+ public String[] getAllSupportFileNames() {
+ XMLElement elem[] = data.getChildren(SUPPORT_TAG);
+ String[] result=new String[elem.length];
+ for (int i=0; i<elem.length; ++i) {
+ XMLElement candidate = elem[i];
+ result[i]=elem[i].getStringAttribute(SUPPORT_FILE_NAME,null);
+ }
+ return result;
+ }
}
Modified: maven/trunk/ogoglio-common/src/test/java/com/ogoglio/xml/test/XMLTest.java
===================================================================
--- maven/trunk/ogoglio-common/src/test/java/com/ogoglio/xml/test/XMLTest.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-common/src/test/java/com/ogoglio/xml/test/XMLTest.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -2,7 +2,9 @@
import java.net.URI;
+import java.text.DateFormat;
import java.util.Date;
+import java.util.Locale;
import javax.media.j3d.Transform3D;
import javax.vecmath.Point3f;
@@ -230,7 +232,12 @@
}
public void testSpaceDocuments() {
- SpaceDocument doc1 = new SpaceDocument(spaceID1, displayName1, ownerUsername1, true, 23, false, 0, 44);
+ DateFormat fmt=DateFormat.getDateTimeInstance(DateFormat.FULL,
+ DateFormat.FULL, Locale.US);
+ Date now=new Date();
+ Date aSecondAgo=new Date(now.getTime()-1000);
+
+ SpaceDocument doc1 = new SpaceDocument(spaceID1, displayName1, ownerUsername1, true, 23, false, 0, 44, fmt.format(aSecondAgo));
assertEquals(spaceID1, doc1.getSpaceID());
assertEquals(displayName1, doc1.getDisplayName());
assertEquals(ownerUsername1, doc1.getOwnerUsername());
@@ -239,7 +246,7 @@
assertFalse(doc1.getDisplaySea());
assertEquals(0, doc1.getSeaLevel(), 0.001);
assertEquals(44, doc1.getSimID());
-
+ assertEquals(fmt.format(aSecondAgo), doc1.getLastModifiedAsUTC());
SpaceDocument doc2 = new SpaceDocument(XMLElement.parseElementFromString(doc1.toElement().toString()));
assertEquals(spaceID1, doc2.getSpaceID());
assertEquals(displayName1, doc2.getDisplayName());
@@ -250,7 +257,7 @@
assertEquals(0, doc2.getSeaLevel(), 0.001);
assertEquals(44, doc2.getSimID());
- SpaceDocument doc3 = new SpaceDocument(spaceID1, displayName1, ownerUsername1, true, 23, true, -2, 44);
+ SpaceDocument doc3 = new SpaceDocument(spaceID1, displayName1, ownerUsername1, true, 23, true, -2, 44, null);
assertTrue(doc3.getDisplaySea());
assertEquals(-2, doc3.getSeaLevel(), 0.00001);
SpaceDocument doc4 = new SpaceDocument(XMLElement.parseElementFromString(doc3.toElement().toString()));
@@ -258,14 +265,14 @@
assertEquals(-2, doc4.getSeaLevel(), 0.00001);
try {
- new SpaceDocument(spaceID1, displayName1, null, true, 4, true, 0, -1);
+ new SpaceDocument(spaceID1, displayName1, null, true, 4, true, 0, -1,null);
fail("Should not allow null ownerURI");
} catch (IllegalArgumentException e) {
//this should happen
}
try {
- new SpaceDocument(spaceID1, null, ownerUsername1, true, 0, true, 0, -1);
+ new SpaceDocument(spaceID1, null, ownerUsername1, true, 0, true, 0, -1,null);
fail("Should not allow null display name");
} catch (IllegalArgumentException e) {
//this should happen
Modified: maven/trunk/ogoglio-integration-test/pom.xml
===================================================================
--- maven/trunk/ogoglio-integration-test/pom.xml 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-integration-test/pom.xml 2007-09-18 15:05:26 UTC (rev 414)
@@ -118,7 +118,7 @@
<home>${ogoglio.tmp.tomcat5x}</home>
<properties>
<cargo.servlet.port>
- 8080
+ ${ogoglio.port}
</cargo.servlet.port>
<cargo.logging>high</cargo.logging>
</properties>
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-09-18 15:05:26 UTC (rev 414)
@@ -20,6 +20,7 @@
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
+import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Random;
@@ -209,6 +210,8 @@
WebAPIAuthenticator advancedAuth = new WebAPIAuthenticator(wire1, descriptor1, USERNAME1, PASSWORD1);
WebAPIClient advancedClient = new WebAPIClient(descriptor1, advancedAuth, wire1);
SpaceDocument spaceDocument = advancedClient.createSpace("Susan's Space");
+ checkSpaceDocumentCreateTime(spaceDocument);
+
assertNotNull(spaceDocument);
advancedClient.setSpacePublished(spaceDocument.getSpaceID(), true);
@@ -267,6 +270,18 @@
}
+ private void checkSpaceDocumentCreateTime(SpaceDocument spaceDocument) {
+ try {
+ long now=new Date().getTime();
+ long lastMod=TemplateSupportFileDocument.fmt.parse(spaceDocument.getLastModifiedAsUTC()).getTime();
+ assertTrue(now-lastMod < 1000); //1 sec seems pretty safe
+ assertTrue(now-lastMod > 0); // asked for now AFTER we created the space
+ } catch (ParseException e) {
+ fail("can't parse the server's timestamp on last modified time of the space");
+ }
+
+ }
+
public void testApplet() throws AuthenticationFailedException, IOException {
WebAPIAuthenticator basicAuthenticator = new WebAPIAuthenticatorFactory().authenticate(wire1, descriptor1, USERNAME1, PASSWORD1);
assertNotNull("got null auth cookie", basicAuthenticator.getAuthCookie());
@@ -481,14 +496,33 @@
private SpaceDocument checkSpaceSeaLevel(WebAPIClient webClient1, SpaceDocument spaceDocument) throws IOException {
assertFalse(spaceDocument.getDisplaySea());
- assertEquals(0, spaceDocument.getSeaLevel(), 0.001);
- webClient1.setSpaceSeaLevel(spaceDocument.getSpaceID(), -2);
- spaceDocument = webClient1.getSpaceDocument(spaceDocument.getSpaceID(), false);
- assertEquals(-2, spaceDocument.getSeaLevel(), 0.000001);
- webClient1.setSpaceDisplaySea(spaceDocument.getSpaceID(), true);
- spaceDocument = webClient1.getSpaceDocument(spaceDocument.getSpaceID(), false);
- assertTrue(spaceDocument.getDisplaySea());
- return spaceDocument;
+
+ //redefine this here b/c we don't want linkage against internal server code
+ DateFormat fmt=TemplateSupportFileDocument.fmt;
+
+ try {
+ long lastUpdateBeforeSet = fmt.parse(spaceDocument.getLastModifiedAsUTC()).getTime();
+ Thread.sleep(1000);
+ assertEquals(0, spaceDocument.getSeaLevel(), 0.001);
+ webClient1.setSpaceSeaLevel(spaceDocument.getSpaceID(), -2);
+ //also testing that the last updated time changed
+ spaceDocument = webClient1.getSpaceDocument(spaceDocument.getSpaceID(), false);
+ //side test, make sure update time changes
+ long lastUpdateAfterSet = fmt.parse(spaceDocument.getLastModifiedAsUTC()).getTime();
+ assertTrue(lastUpdateAfterSet-lastUpdateBeforeSet>=1000);
+
+ assertEquals(-2, spaceDocument.getSeaLevel(), 0.000001);
+ webClient1.setSpaceDisplaySea(spaceDocument.getSpaceID(), true);
+ spaceDocument = webClient1.getSpaceDocument(spaceDocument.getSpaceID(), false);
+ assertTrue(spaceDocument.getDisplaySea());
+ return spaceDocument;
+ } catch (ParseException e) {
+ fail("Unable to parse the date sent from the server as the last modified time of the space");
+ return null;
+ } catch (InterruptedException e) {
+ fail("Interrupted exception timing the last space updated time");
+ return null;
+ }
}
private void checkNoConnectionToSpaceWithoutAuth(long spaceID) {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java 2007-09-18 01:14:18 UTC (rev 413)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/Spa...
[truncated message content] |
|
From: <ian...@us...> - 2007-09-20 18:34:08
|
Revision: 430
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=430&view=rev
Author: iansmith
Date: 2007-09-20 11:34:07 -0700 (Thu, 20 Sep 2007)
Log Message:
-----------
First stage of externalization of all resources that are needed to run an ogoglio war.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-19 20:33:25 UTC (rev 429)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/migrate/MigrationSupport.java 2007-09-20 18:34:07 UTC (rev 430)
@@ -87,6 +87,8 @@
}
if (useJNDI) {
configuration.setProperty("hibernate.connection.datasource", "java:comp/env/jdbc/space");
+ //I have no idea why this is necessary if the datasource SPECIFIES the dialect
+ configuration.setProperty("hibernate.dialect","org.hibernate.dialect.MySQLDialect");
} else {
configuration.addProperties(ps.getAllProps(PropStorage.TEST_CONFIG_PROPS));
}
Modified: maven/trunk/ogoglio-integration-test/pom.xml
===================================================================
--- maven/trunk/ogoglio-integration-test/pom.xml 2007-09-19 20:33:25 UTC (rev 429)
+++ maven/trunk/ogoglio-integration-test/pom.xml 2007-09-20 18:34:07 UTC (rev 430)
@@ -90,56 +90,6 @@
</executions>
<configuration />
</plugin>
- <!--lots of CARGO magic to bring server up, do deploys... -->
- <plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>0.3-SNAPSHOT</version>
- <configuration></configuration>
- <executions>
- <execution>
- <!--bring up server in /tmp -->
- <id>boot-server</id>
- <phase>pre-integration-test</phase>
- <goals>
- <goal>start</goal>
- </goals>
- <configuration>
- <wait>false</wait>
- <container>
- <containerId>tomcat5x</containerId>
- <home>${cargo.tomcat5x.home}</home>
- <log>${basedir}/tomcat5x.log</log>
- <output>${basedir}/tomcat5x.out</output>
- </container>
- <!-- container configuration -->
- <configuration>
- <type>standalone</type>
- <home>${ogoglio.tmp.tomcat5x}</home>
- <properties>
- <cargo.servlet.port>
- ${ogoglio.port}
- </cargo.servlet.port>
- <cargo.logging>high</cargo.logging>
- </properties>
- <!-- tricky: this gets put in *before* the server even boots -->
- <deployables>
- <deployable>
- <groupId>com.ogoglio</groupId>
- <artifactId>
- ogoglio-server
- </artifactId>
- <type>war</type>
- <properties>
- <context>og</context>
- </properties>
- </deployable>
- </deployables>
- </configuration>
- </configuration>
- </execution>
- </executions>
- </plugin>
</plugins>
</build>
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-09-19 20:33:25 UTC (rev 429)
+++ maven/trunk/ogoglio-server/pom.xml 2007-09-20 18:34:07 UTC (rev 430)
@@ -14,41 +14,6 @@
<artifactId>ogoglio-server</artifactId>
<packaging>war</packaging>
- <profiles>
- <profile>
- <id>hot-deploy</id>
- <build>
- <plugins>
- <!-- CARGO CONFIG:INSTALL TO RUNNING SERVER -->
- <plugin>
- <groupId>org.codehaus.cargo</groupId>
- <artifactId>cargo-maven2-plugin</artifactId>
- <version>0.3-SNAPSHOT</version>
- <configuration>
- <container>
- <containerId>tomcat5x</containerId>
- </container>
- <!-- Configuration to use with the container -->
- <configuration>
- <type>existing</type>
- <home>${ogoglio.tmp.tomcat5x}</home>
- </configuration>
- <deployables>
- <deployable>
- <properties>
- <context>
- ${pom.artifactId}
- </context>
- </properties>
- </deployable>
- </deployables>
- </configuration>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
-
<!-- -->
<!-- BUILD -->
<!-- -->
@@ -200,7 +165,9 @@
<serviceURI>${ogoglio.baseURL}</serviceURI>
<username>${ogoglio.bootstrapUser}</username>
<password>${ogoglio.bootstrapUserPW}</password>
- <populateDir>src/main/resources/populate</populateDir>
+ <populateDir>
+ src/main/resources/populate
+ </populateDir>
<reverseFile>/tmp/reverse.xml</reverseFile>
<goalPrefix>og</goalPrefix>
</configuration>
@@ -224,6 +191,26 @@
</execution>
</executions>
</plugin>
+
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>tomcat-maven-plugin</artifactId>
+ <configuration>
+ <server>localMachine</server>
+ <path>/og</path>
+ </configuration>
+
+ <executions>
+ <execution>
+ <phase>install</phase>
+ <goals>
+ <goal>undeploy</goal>
+ <goal>deploy</goal>
+ </goals>
+ </execution>
+ </executions>
+
+ </plugin>
</plugins>
</build>
Modified: maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-19 20:33:25 UTC (rev 429)
+++ maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-20 18:34:07 UTC (rev 430)
@@ -2,24 +2,15 @@
<Context reloadable="true" path="/og" >
<Realm className="org.apache.catalina.realm.MemoryRealm" />
- <Resource name="jdbc/space" scope="Shareable"
- type="javax.sql.DataSource" auth='Container'
- factory="org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory"
- url="${ogoglio.mysql.url}"
- driverClassName="com.mysql.jdbc.Driver"
- username="${ogoglio.mysql.user}"
- password="${ogoglio.mysql.password}"
- dialect="org.hibernate.dialect.MySQLDialect"
- show_sql="false"
- maxIdle="5"
- maxActive="50" />
-
- <Environment name="ogoglio/oktoZapDB" value="false" type="java.lang.String"/> <!-- not running tests! -->
- <Environment name="ogoglio/okToMigrateDB" value="${ogoglio.okToMigrateDB}" type="java.lang.String"/>
- <Environment name="ogoglio/mediaURL" value="${ogoglio.mediaURL}" type="java.lang.String"/>
- <Environment name="ogoglio/baseURL" value="${ogoglio.baseURL}" type="java.lang.String"/>
- <Environment name="ogoglio/simsAllowRemoteAccess" value="true" type="java.lang.String" />
- <Environment name="ogoglio/mediaDirectory" value="${ogoglio.mediaDirectory}" type="java.lang.String"/>
- <Environment name="ogoglio/bootstrapUser" value="${ogoglio.bootstrapUser}" type="java.lang.String"/>
- <Environment name="ogoglio/bootstrapUserPW" value="${ogoglio.bootstrapUserPW}" type="java.lang.String"/>
+ <ResourceLink name="jdbc/space"
+ global="ogoglioDB"
+ type="javax.sql.DataSource"/>
+
+ <ResourceLink name="ogoglio/mediaURL" global="mediaURL" type="java.lang.String"/>
+ <ResourceLink name="ogoglio/baseURL" global="baseURL" type="java.lang.String"/>
+
+ <ResourceLink name="ogoglio/oktoZapDB" global="oktoZapDB" type="java.lang.String"/>
+ <ResourceLink name="ogoglio/okMigrateDB" global="oktoMigrateDB" type="java.lang.String"/>
+ <ResourceLink name="ogoglio/simsAllowRemoteAccess" global="simsAllowRemoteAccess" type="java.lang.String"/>
+ <ResourceLink name="ogoglio/mediaDirectory" global="mediaDirectory" type="java.lang.String"/>
</Context>
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-09-24 19:01:28
|
Revision: 437
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=437&view=rev
Author: iansmith
Date: 2007-09-24 12:01:30 -0700 (Mon, 24 Sep 2007)
Log Message:
-----------
Added support for having sim run on a different machine.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SimPersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -224,7 +224,7 @@
outputStream.flush();
outputStream.close();
}
-
+ System.out.println("FART ABOUT TOSET STATUS:"+connection.getResponseCode());
response.setStatus(connection.getResponseCode());
Map headers = connection.getHeaderFields();
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/AppletTestWindow.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -21,7 +21,6 @@
import java.awt.Frame;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
-import java.lang.management.ManagementFactory;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
@@ -34,7 +33,6 @@
import com.ogoglio.util.ArgumentUtils;
import com.ogoglio.util.PropStorage;
import com.ogoglio.viewer.applet.ViewerApplet;
-import com.sun.tools.javac.util.List;
public class AppletTestWindow extends Frame {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/migrate/AccountsForTesting.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -59,7 +59,6 @@
ServiceInitializationPersistTasks.initializeBootstrapAccount(sessionFactory, uri.getHost(), userList[i], pwList[i], cookiesList[i]);
}
- ServiceInitializationPersistTasks.initializeLocalSim(uri, sessionFactory);
ServiceInitializationPersistTasks.initializeServiceState(sessionFactory);
return true;
} catch (Exception e) {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -29,7 +29,7 @@
public static final String DEFAULT_DOOR_DISPLAY_NAME = "Default Door";
- public static void initializeLocalSim(URI serviceURI, SessionFactory sessionFactory) throws PersistException {
+ public static void DEAD_CODE_initializeLocalSim(URI serviceURI, SessionFactory sessionFactory) throws PersistException {
SimRecord[] simRecords = SimPersistTasks.findSims(sessionFactory);
URI ourURI=WebAPIUtil.appendToURI(serviceURI, "sim/");
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SimPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SimPersistTasks.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SimPersistTasks.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -25,8 +25,11 @@
public class SimPersistTasks {
public static final String SIM_BY_URI = "com.ogoglio.persist.simByURI";
+
public static final String SIM_BY_ID = "com.ogoglio.persist.simBySimID";
+
public static final String SIMS_BY_ACTIVE = "com.ogoglio.persist.simsByActive";
+
public static final String SIMS = "com.ogoglio.persist.sims";
public static SimRecord[] findSims(SessionFactory sessionFactory) throws PersistException {
@@ -40,7 +43,6 @@
return (SimRecord[]) task.execute();
}
-
public static SimRecord findSimsBySimURI(final URI simURI, SessionFactory sessionFactory) throws PersistException {
HibernateTask task = new HibernateTask() {
public Object run(Session hibernateSession) {
@@ -76,7 +78,6 @@
task.execute();
}
-
public static void delete(final SimRecord simRecord, SessionFactory sessionFactory) throws PersistException {
HibernateTask task = new HibernateTask() {
public Object run(Session hibernateSession) {
@@ -87,4 +88,16 @@
task.setSessionFactory(sessionFactory);
task.execute();
}
+
+ public static SimRecord findSimByID(final long simID, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ Query query = hibernateSession.getNamedQuery(SIM_BY_ID);
+ query.setLong("simID", simID);
+ return query.uniqueResult();
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (SimRecord) task.execute();
+ }
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -272,7 +272,7 @@
simulator = new SpaceSimulator(spaceDoc, spaceSimulatorListener);
spaceSimulators.put(new Long(record.getSpaceID()), simulator);
simulator.startSim();
- Log.info("Starting space sim " + record.getSpaceID() + ": " + record.getDisplayName());
+ Log.info("Starting space sim " + record.getSpaceID() + ": " + record.getDisplayName() + "( on sim "+ record.getSimID()+")");
return simulator;
}
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -21,6 +21,8 @@
import java.util.HashMap;
import java.util.Map;
+import javax.naming.Context;
+import javax.naming.NamingException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
@@ -32,8 +34,8 @@
import com.ogoglio.appdev.servlet.SiteResource;
import com.ogoglio.client.DecoratedInputStream;
import com.ogoglio.media.MediaService;
-import com.ogoglio.persist.AccountPersistTasks;
import com.ogoglio.persist.AccountRecord;
+import com.ogoglio.persist.ServiceInitializationPersistTasks;
import com.ogoglio.persist.SimPersistTasks;
import com.ogoglio.persist.SimRecord;
import com.ogoglio.persist.SpacePersistTasks;
@@ -72,28 +74,45 @@
public void init(ServletConfig config) throws ServletException {
super.init(config);
+ System.out.println("IN INIT:"+config.getServletName()+","+config.getServletContext().getServletContextName());
try {
- simURI = new URI(getSiteInfo().getBaseUrl() + "sim/");
+ Context envCtx = (Context) initCtx.lookup("java:comp/env");
+ simURI = new URI((String) envCtx.lookup("ogoglio/baseSimURL"));
+
SimRecord simRecord = SimPersistTasks.findSimsBySimURI(simURI, getSessionFactory());
- if (simRecord == null) {
- throw new ServletException("Configuration error, no sim record for " + simURI);
+ if (simRecord != null) {
+ //error
+ Log.warn("Restarting the sim server @ "+simRecord.getSimURI()+" but it was already in the database! Ignored.");
+ } else {
+ Log.info("Starting up sim @ " +simURI);
+ simRecord = SimPersistTasks.createSim(ServiceInitializationPersistTasks.LOCAL_SIM_DISPLAY_NAME, simURI, SimRecord.DEFAULT_EVENT_PORT, true, getSessionFactory());
+ sim = new Sim(simRecord, getMediaService(), getSessionFactory());
+ localIP = InetAddress.getByName(simURI.getHost()).getHostAddress();
}
- sim = new Sim(simRecord, getMediaService(), getSessionFactory());
- localIP = InetAddress.getByName(simURI.getHost()).getHostAddress();
- } catch (ServletException e) {
- throw e; //lame
+ } catch (NamingException e) {
+ throw new ServletException("Couldn't find the baseSimURL:"+e.getMessage(),e);
} catch (Exception e) {
- e.printStackTrace();
- throw new ServletException("SimServlet error: " + e);
- }
+ throw new ServletException("Couldn't start sim servlet:"+e.getMessage(),e);
+ }
ScriptContextFactory.setTimedContextAsGlobalContext();
}
public void destroy() {
- super.destroy();
- sim.cleanup();
- Log.info("Destroy called on SimServlet. Cleaning up sim...");
+ try {
+ super.destroy();
+ sim.cleanup();
+ SimRecord rec=SimPersistTasks.findSimsBySimURI(simURI, getSessionFactory());
+ if (rec==null) {
+ System.out.println("FART: CAN'T FIND SIM REC!");
+ } else {
+ System.out.println("FART: DESTROYING SIM REC!");
+ SimPersistTasks.delete(rec, getSessionFactory());
+ }
+ Log.info("Cleaned up sim record in database:"+simURI);
+ } catch (PersistException e) {
+ Log.error("Can't clean up Sim record in database:"+e.getMessage(),e);
+ }
}
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
@@ -108,6 +127,7 @@
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
+ System.out.println("FART: SERVICE:"+request.getPathInfo());
super.service(request, response);
}
@@ -232,8 +252,10 @@
public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
long spaceID = Long.parseLong(pathElements[2]);
try {
+
SpaceRecord spaceRecord = SpacePersistTasks.findSpaceBySpaceID(spaceID, getSessionFactory());
if (spaceRecord == null) {
+ System.out.println("FART: no space!");
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
@@ -244,6 +266,7 @@
return;
}
+ System.out.println("FART: authed:"+authedAccount.getUsername());
SpaceSimulator simulator = sim.getOrCreateSpaceSimulator(spaceRecord);
Map settings = simulator.getSettings();
@@ -267,8 +290,10 @@
public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
long spaceID = Long.parseLong(pathElements[2]);
+ System.out.println("FART: do get:"+spaceID);
try {
SpaceRecord spaceRecord = SpacePersistTasks.findSpaceBySpaceID(spaceID, getSessionFactory());
+ System.out.println("FART: do get:"+spaceID+" w/"+spaceRecord.getSimID());
if (spaceRecord == null) {
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
@@ -330,6 +355,7 @@
response.setStatus(HttpServletResponse.SC_NOT_FOUND);
return;
}
+ System.out.println("FART: do post:"+spaceID+","+spaceRecord.getSimID());
AccountRecord authedAccount = AuthServlet.getAuthedAccountRecord(request, getSessionFactory());
if (authedAccount != null && !authedAccount.getUsername().equals(spaceRecord.getOwnerUsername())) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
@@ -456,7 +482,6 @@
return;
}
-
AccountRecord authedAccount = AuthServlet.getAuthedAccountRecord(request, getSessionFactory());
if (!SpacePersistTasks.canReadSpace(authedAccount, spaceID, getSessionFactory())) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -481,8 +481,10 @@
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
+ System.out.println("FART: PROXY authed:"+authedAccount.getUsername());
SimRecord simRecord = SpacePersistTasks.findOrAssignSim(spaceRecord, getSessionFactory());
+ System.out.println("FART PROXY: "+simRecord.getSimID()+","+simRecord.getSimURI());
if (simRecord == null) {
Log.error("Could not assign a sim to space " + spaceRecord.getSpaceID());
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
@@ -494,6 +496,7 @@
proxyURI += pathElements[i] + "/";
}
+ System.out.println("FART: PROXY URI ABOUT TO GO:"+proxyURI);
proxy(new URI(proxyURI), method, request, response);
} catch (PersistException e) {
Modified: maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
===================================================================
--- maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml 2007-09-24 19:01:30 UTC (rev 437)
@@ -8,6 +8,7 @@
<ResourceLink name="ogoglio/mediaURL" global="mediaURL" type="java.lang.String"/>
<ResourceLink name="ogoglio/baseURL" global="baseURL" type="java.lang.String"/>
+ <ResourceLink name="ogoglio/baseSimURL" global="baseSimURL" type="java.lang.String"/>
<ResourceLink name="ogoglio/oktoZapDB" global="oktoZapDB" type="java.lang.String"/>
<ResourceLink name="ogoglio/okMigrateDB" global="oktoMigrateDB" type="java.lang.String"/>
Modified: maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
===================================================================
--- maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-24 18:34:16 UTC (rev 436)
+++ maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java 2007-09-24 19:01:30 UTC (rev 437)
@@ -126,7 +126,7 @@
verifyTemplateProps(templateName1, templateRec1);
SpaceRecord spaceRecord1 = checkSpaceAndSimTasks();
-
+
BodyRecord bodyRec1 = BodyPersistTasks.createBody(displayName1, "bogosity", sessionFactory);
assertNull("created body with bogus username", bodyRec1);
bodyRec1 = BodyPersistTasks.createBody(displayName1, username1, sessionFactory);
@@ -151,6 +151,19 @@
assertNotNull(possRecs1);
assertEquals(username1, possRecs1[0].getOwnerUsername());
+
+ //clean up
+ long runningOnSimID=spaceRecord1.getSimID();
+ SpacePersistTasks.deleteSpace(spaceRecord1, sessionFactory);
+ SimRecord condemnedSim = SimPersistTasks.findSimByID(runningOnSimID,sessionFactory);
+ assertNotNull(condemnedSim);
+ SimPersistTasks.delete(condemnedSim, sessionFactory);
+
+ //sanity
+ assertEquals(0, SpacePersistTasks.findAllSpaces(sessionFactory).length);
+ assertEquals(0, SimPersistTasks.findSims(sessionFactory).length);
+
+
} catch (PersistException e) {
e.printStackTrace();
fail();
@@ -218,6 +231,7 @@
SimRecord assignedSimRecord = SpacePersistTasks.findOrAssignSim(spaceRecord2, sessionFactory);
assertNotNull(assignedSimRecord);
+
//System.out.println("XXX ASSIGNED TO SIM:"
// + assignedSimRecord.getSimID() + ","
// + assignedSimRecord.getSimURI() + " -->\n" + "space was "
@@ -237,7 +251,10 @@
* assignedSimRecord.getSimID()); assertEquals(simRecord1,
* assignedSimRecord);
*/
- return spaceRecord1;
+
+ //subtle: need to return 2 ... because these differ in the assignment of the simid
+ //since we assigned the spaceRecord2 version to a sim
+ return spaceRecord2;
}
private void verifySimProps(SimRecord rec, String name, URI uri, int not_id, int port) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-10-01 21:55:46
|
Revision: 463
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=463&view=rev
Author: iansmith
Date: 2007-10-01 14:55:49 -0700 (Mon, 01 Oct 2007)
Log Message:
-----------
This commit adds support for running the separate parts of the og system on different machines. Developers should see no visible changes if they add this to their server.xml in tomcat's conf directory:
<Environment name="isSimServer" value="true" type="java.lang.String"/>
<Environment name="isMediaServer" value="true" type="java.lang.String"/>
<Environment name="isWebappServer" value="true" type="java.lang.String"/>
These properties control the obvious servlets. These servlets will return 404 if they are "turned off" via this mechanism.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIAuthenticator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClientWire.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/site/MediaServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/AccountServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/AuthServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/AuthenticatedSiteResource.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OgoglioServletBase.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/TemplateResource.java
maven/trunk/ogoglio-server/src/main/webapp/META-INF/context.xml
maven/trunk/ogoglio-server/src/test/java/com/ogoglio/persist/test/PersistTest.java
Added Paths:
-----------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/Four04SiteResource.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/WebappServletBase.java
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web-all.xml
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractRemoteServlet.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -18,7 +18,6 @@
import com.ogoglio.client.WebAPIClientWire;
import com.ogoglio.client.WebAPIDescriptor;
import com.ogoglio.util.ArgumentUtils;
-import com.ogoglio.util.Log;
import com.ogoglio.xml.AuthDocument;
public abstract class AbstractRemoteServlet extends MigratedResourceServlet {
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -65,7 +65,7 @@
protected Context initCtx=null;
protected String baseUrl=null;
- private void initContext() throws NamingException {
+ protected void initContext() throws NamingException {
if (initCtx==null) {
initCtx = new InitialContext();
}
@@ -224,6 +224,9 @@
outputStream.flush();
outputStream.close();
}
+ if (connection.getResponseCode()!=200) {
+ Log.warn("Proxy sending error to client: "+connection.getResponseCode()+" on "+uri);
+ }
response.setStatus(connection.getResponseCode());
Map headers = connection.getHeaderFields();
Added: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/Four04SiteResource.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/Four04SiteResource.java (rev 0)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/Four04SiteResource.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -0,0 +1,17 @@
+package com.ogoglio.appdev.servlet;
+
+import java.io.IOException;
+
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+public class Four04SiteResource extends SiteResource {
+
+ public Four04SiteResource(String name) {
+ super(name);
+ }
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
+ response.setStatus(HttpServletResponse.SC_NOT_FOUND);
+ }
+}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIAuthenticator.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIAuthenticator.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIAuthenticator.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -33,6 +33,7 @@
ArgumentUtils.assertNotEmpty(password);
String body = WebConstants.AUTH_USERNAME_PARAM + "=" + username + "&" + WebConstants.AUTH_PASS_PARAM + "=" + password;
authCookie = wire.getAuthCookieViaPost(serviceDescriptor.getAuthURI(), body, "application/x-www-form-urlencoded");
+ //authCookie = wire.getAuthCookieViaPost(serviceDescriptor.getAuthURI(), body, "text/plain");
if(authCookie == null) {
throw new IOException("Did not get a valid cookie for " + username);
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClientWire.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClientWire.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIClientWire.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -104,7 +104,8 @@
}
if ("POST".equals(method)) {
connection.setDoOutput(true);
- connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
+ //connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
+ connection.setRequestProperty("Content-type", "text/plain");
connection.setRequestProperty("Content-length", Integer.toString(body.length()));
OutputStream rawOutStream = connection.getOutputStream();
PrintWriter pw = new PrintWriter(rawOutStream);
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -18,8 +18,10 @@
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
+import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
+import java.net.URLConnection;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
@@ -81,7 +83,7 @@
URI linkURI1 = null;
- URI serviceURI1 = null;
+ URI serviceURI1 = null, mediaURI, simURI;
WebAPIClientWire wire1 = null;
@@ -94,6 +96,8 @@
fail("couldn't load property set (BASIC)");
}
serviceURI1 = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseUrl"));
+ mediaURI = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.mediaUrl"));
+ simURI = new URI(ps.getKeyFromSet(PropStorage.BASIC_PROPS, "ogoglio.baseSimUrl"));
linkURI1 = new URI("http://example.com/");
wire1 = new WebAPIClientWire();
descriptor1 = new WebAPIDescriptor(serviceURI1);
@@ -106,6 +110,29 @@
public void tearDown() {
}
+ public void testServersOnAmazon() throws AuthenticationFailedException, IOException {
+ //only run these when we are on the cluster
+ if (serviceURI1.getHost().endsWith("transmutable.com")) {
+ checkCantReachURI(simURI);
+ checkCantReachURI(mediaURI);
+ try {
+ new Socket(serviceURI1.getHost(),3306/*mysql port*/);
+ fail("Shouldn't be able to connect to the MySql server!");
+ } catch (IOException e) {
+ //pass
+ }
+ }
+ }
+
+ private void checkCantReachURI(URI uri) {
+ try {
+ uri.toURL().openConnection();
+ fail("should not be able to see the URI"+uri+"!");
+ } catch (IOException e) {
+ //pass
+ }
+ }
+
public void testAppletsCanBeDownloaded() throws IOException, URISyntaxException {
checkSupportFile("ogoglio-viewer-applet.jar");
checkSupportFile("ogoglio-test-applet.jar");
@@ -210,6 +237,7 @@
WebAPIAuthenticator advancedAuth = new WebAPIAuthenticator(wire1, descriptor1, USERNAME1, PASSWORD1);
WebAPIClient advancedClient = new WebAPIClient(descriptor1, advancedAuth, wire1);
SpaceDocument spaceDocument = advancedClient.createSpace("Susan's Space");
+ assertNotNull(spaceDocument);
checkSpaceDocumentCreateTime(spaceDocument);
assertNotNull(spaceDocument);
@@ -258,7 +286,10 @@
checkGeometryAvailableForSpace(advancedClient, thingDocs, spaceClient1.getSpace());
guestSpaceClient1 = checkGuestCookieOperation(spaceDocument.getSpaceID(), advancedClient, WebConstants.GUEST_COOKIE_PREFIX + "Test_Suite_Guest");
+
checkDeletingSpaceDestroysThings(spaceDocument.getSpaceID(), advancedClient, USERNAME1);
+
+
} finally {
if (spaceClient1 != null) {
spaceClient1.cleanup();
Modified: maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/basic-config.properties 2007-10-01 21:55:49 UTC (rev 463)
@@ -2,4 +2,5 @@
ogoglio.testSpaceNumber = ${ogoglio.testSpaceNumber}
ogoglio.baseUrl = ${ogoglio.baseURL}
ogoglio.baseSimUrl = ${ogoglio.baseSimURL}
+ogoglio.mediaUrl = ${ogoglio.mediaURL}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/site/MediaServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/site/MediaServlet.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/site/MediaServlet.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -13,6 +13,7 @@
import javax.servlet.http.HttpServletResponse;
import com.ogoglio.appdev.servlet.AbstractResourceServlet;
+import com.ogoglio.appdev.servlet.Four04SiteResource;
import com.ogoglio.appdev.servlet.SiteResource;
import com.ogoglio.client.DecoratedInputStream;
import com.ogoglio.media.FileStore;
@@ -23,28 +24,38 @@
private FileStore fileStore = null;
+ private boolean servletNeeded = true;
+
public void init(ServletConfig config) throws ServletException {
- super.init(config);
- Context envCtx;
- try {
- envCtx = (Context) initCtx.lookup("java:comp/env");
- File mediaDirectory = null;
- try {
- mediaDirectory = new File((String)envCtx.lookup("ogoglio/mediaDirectory"));
- } catch (NamingException e) {
- }
+ Context envCtx;
+ try {
+ initContext();
+ envCtx = (Context) initCtx.lookup("java:comp/env");
+ String useMe = (String) envCtx.lookup("ogoglio/isMediaServer");
+ if ("false".equals(useMe.toLowerCase())) {
+ servletNeeded = false;
+ }
- if (mediaDirectory == null) {
- Log.warn("Not running media service");
- } else {
- fileStore = new FileStore(mediaDirectory.toURI());
- }
- } catch (NamingException e) {
- Log.error("Unable to figure out the initial context due to Naming Exception",e);
- throw new ServletException(e);
- }
+ //has to come AFTER the useMe/servletNeeded above
+ super.init(config);
+ File mediaDirectory = null;
+ try {
+ mediaDirectory = new File((String) envCtx.lookup("ogoglio/mediaDirectory"));
+ } catch (NamingException e) {
+ }
+
+ if (mediaDirectory == null) {
+ Log.warn("Not running media service");
+ } else {
+ fileStore = new FileStore(mediaDirectory.toURI());
+ }
+ } catch (NamingException e) {
+ Log.error("Unable to figure out the initial context due to Naming Exception", e);
+ throw new ServletException(e);
+ }
+
}
public void destroy() {
@@ -52,7 +63,12 @@
}
public SiteResource createBaseResource(ServletConfig servletConfig) {
- return new MediaResource();
+ if (servletNeeded) {
+ return new MediaResource();
+ } else {
+ Log.info("Turning off media servlet, this host doesn't want it.");
+ return new Four04SiteResource("media");
+ }
}
private class MediaResource extends SiteResource {
@@ -62,26 +78,27 @@
}
public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
- if ((request.getQueryString()!=null) && (request.getQueryString().startsWith("list"))) {
- doList(request,response);
- return;
- }
+ if ((request.getQueryString() != null) && (request.getQueryString().startsWith("list"))) {
+ doList(request, response);
+ return;
+ }
sendStringResponse("I'm a media servlet (" + (fileStore == null ? "inactive" : "active") + ")", "text/plain", response);
}
+
public void doList(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (fileStore == null) {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
- OutputStream str=response.getOutputStream();
- OutputStreamWriter wr=new OutputStreamWriter(str);
- String[] allNames= fileStore.getAllNames();
- for (int i=0; i<allNames.length;++i) {
- wr.write(allNames[i]+"\n");
+ OutputStream str = response.getOutputStream();
+ OutputStreamWriter wr = new OutputStreamWriter(str);
+ String[] allNames = fileStore.getAllNames();
+ for (int i = 0; i < allNames.length; ++i) {
+ wr.write(allNames[i] + "\n");
}
wr.flush();
wr.close();
- response.setContentType("text/plain");
+ response.setContentType("text/plain");
response.setStatus(HttpServletResponse.SC_OK);
}
}
@@ -107,7 +124,7 @@
if (input.getLength() > -1) {
response.setContentLength((int) input.getLength());
}
- if(input.getMimeType() != null) {
+ if (input.getMimeType() != null) {
response.setContentType(input.getMimeType());
}
StreamUtils.write(input, response.getOutputStream());
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/ServiceInitializationPersistTasks.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -14,12 +14,10 @@
package com.ogoglio.persist;
import java.io.IOException;
-import java.net.URI;
import org.hibernate.SessionFactory;
import com.ogoglio.appdev.persist.PersistException;
-import com.ogoglio.client.WebAPIUtil;
public class ServiceInitializationPersistTasks {
@@ -29,34 +27,6 @@
public static final String DEFAULT_DOOR_DISPLAY_NAME = "Default Door";
- public static void DEAD_CODE_initializeLocalSim(URI serviceURI, SessionFactory sessionFactory) throws PersistException {
- SimRecord[] simRecords = SimPersistTasks.findSims(sessionFactory);
- URI ourURI=WebAPIUtil.appendToURI(serviceURI, "sim/");
-
- if (simRecords.length != 0) {
- //the db might have been created on another host (e.g. the amazon case)
- for (int i=0; i<simRecords.length;++i) {
- SimRecord sim=simRecords[i];
- if (LOCAL_SIM_DISPLAY_NAME.equals(sim.getDisplayName())) {
- if (!(ourURI.equals(sim.getSimURI()))) {
- //make it point to us
- sim.setSimURI(ourURI);
- //sim.setActive(true);
- SimPersistTasks.update(sim, sessionFactory);
- } else {
- if (!sim.isActive()) {
- //sim.setActive(true);
- SimPersistTasks.update(sim, sessionFactory);
- }
- }
- }
- }
- SimRecord rec = SimPersistTasks.findSimsBySimURI(ourURI, sessionFactory);
- return;
- }
- SimPersistTasks.createSim(LOCAL_SIM_DISPLAY_NAME, WebAPIUtil.appendToURI(serviceURI, "sim/"), SimRecord.DEFAULT_EVENT_PORT, true, sessionFactory);
- }
-
public static void initializeBootstrapAccount(SessionFactory sessionFactory,String host,String user, String pw, String cookie) throws PersistException, IOException {
AccountRecord accountRec = AccountPersistTasks.findAccountByUsername(user, sessionFactory);
if (accountRec != null) {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java 2007-10-01 13:57:55 UTC (rev 462)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/persist/SpacePersistTasks.java 2007-10-01 21:55:49 UTC (rev 463)
@@ -13,6 +13,11 @@
limitations under the License. */
package com.ogoglio.persist;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.ProtocolException;
+import java.net.URI;
import java.util.Date;
import java.util.Random;
@@ -22,6 +27,7 @@
import com.ogoglio.appdev.persist.HibernateTask;
import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.util.Log;
import com.ogoglio.xml.PossessionDocument;
import com.ogoglio.xml.SpaceDocument;
import com.ogoglio.xml.SpaceMemberDocument;
@@ -34,6 +40,10 @@
public static final Random RANDOM = new Random();
+ private static final long TEST_SIM_INTERVAL_MS = 15000;
+
+ private static long lastTestOfSimServers=0L;
+
public static SpaceRecord updateSpace(final long spaceID, final SpaceDocument spaceDocument, SessionFactory sessionFactory) throws PersistException {
HibernateTask task = new HibernateTask() {
public Object run(Session hibernateSession) {
@@ -71,7 +81,7 @@
}
if (dirty) {
- record=updateRecordAndUpdateModifiedTime(record,hibernateSession,true);
+ record = updateRecordAndUpdateModifiedTime(record, hibernateSession, true);
}
return record;
}
@@ -79,7 +89,16 @@
task.setSessionFactory(sessionFactory);
return (SpaceRecord) task.execute();
}
-
+
+ private static SpaceRecord updateRecordAndUpdateModifiedTime(final SpaceRecord record, SessionFactory sessionFactory, final boolean useUpdate) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ return updateRecordAndUpdateModifiedTime(record, hibernateSession, useUpdate);
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (SpaceRecord) task.execute();
+ }
private static SpaceRecord updateRecordAndUpdateModifiedTime(SpaceRecord record, Session hibernateSession, boolean useUpdate) {
record.setLastModifiedTime(new Date().getTime());
if (useUpdate) {
@@ -128,7 +147,7 @@
public static void update(final SpaceRecord record, final SessionFactory sessionFactory) throws PersistException {
HibernateTask task = new HibernateTask() {
public Object run(Session hibernateSession) {
- updateRecordAndUpdateModifiedTime(record, hibernateSession,true);
+ updateRecordAndUpdateModifiedTime(record, hibernateSession, true);
return null;
}
};
@@ -136,9 +155,118 @@
task.execute();
}
+ private static SimRecord findSimIfActive(final SpaceRecord spaceRecord, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ SimRecord simRecord = null;
+ if (spaceRecord.getSimID() != -1) {
+ Query simQuery = hibernateSession.getNamedQuery(SimPersistTasks.SIM_BY_ID);
+ simQuery.setLong("simID", spaceRecord.getSimID());
+ simRecord = (SimRecord) simQuery.uniqueResult();
+ if (simRecord == null || simRecord.isActive() == false) {
+ spaceRecord.setSimID(-1);
+ updateRecordAndUpdateModifiedTime(spaceRecord, hibernateSession, true);
+ simRecord = null;
+ return null;
+ } else {
+ return simRecord;
+ }
+ } else {
+ return null;
+ }
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (SimRecord) task.execute();
+ }
+
+ private static void markInactive(SimRecord record, SessionFactory sessionFactory) throws PersistException {
+ record.setActive(false);
+ SimPersistTasks.update(record, sessionFactory);
+ }
public static SimRecord findOrAssignSim(final SpaceRecord spaceRecord, SessionFactory sessionFactory) throws PersistException {
+ return findOrAssignSim(spaceRecord, sessionFactory, true);
+ }
+
+ public static void verifyActiveSims(SimRecord[] purportedActive, SessionFactory sessionFactory) throws PersistException {
+ //let's see if they are ok
+ for (int i=0; i<purportedActive.length;++i) {
+ try {
+ URI simURI=purportedActive[i].getSimURI();
+ HttpURLConnection connection = (HttpURLConnection) simURI.toURL().openConnection();
+ connection.setRequestMethod("GET");
+ connection.setAllowUserInteraction(false);
+ if (connection.getResponseCode()!=200) {
+ Log.warn("Can't get a connection to "+simURI+"! Marking inactive!");
+ markInactive(purportedActive[i], sessionFactory);
+ } else {
+ Log.info("Verified connection to "+simURI);
+ }
+ } catch (MalformedURLException e) {
+ Log.warn("Can't understand the URI "+purportedActive[i].getSimURI()+"! Marking inactive!");
+ markInactive(purportedActive[i], sessionFactory);
+ } catch (ProtocolException e) {
+ Log.warn("Can't understand the URI protocol "+purportedActive[i].getSimURI()+"! Marking inactive!");
+ markInactive(purportedActive[i], sessionFactory);
+ } catch (IOException e) {
+ Log.warn("Can't connect to "+purportedActive[i].getSimURI()+"! Marking inactive! IOException:"+e.getMessage());
+ markInactive(purportedActive[i], sessionFactory);
+ }
+ }
+
+ }
+ public static SimRecord findOrAssignSim(final SpaceRecord spaceRecord, SessionFactory sessionFactory, boolean use_network) throws PersistException {
+ SimRecord rec = findSimIfActive(spaceRecord, sessionFactory);
+ SimRecord[] active;
+
+ if (rec!=null) {
+ //assume that if we have a sim ID already assigned we are ok
+ return rec;
+ }
+ active=findAllActiveSims(spaceRecord, sessionFactory);
+ if (active.length==0) {
+ throw new PersistException("Unable to find any active sims!");
+ }
+ //has it been a while?
+ long now=System.currentTimeMillis();
+ if ((now-lastTestOfSimServers<TEST_SIM_INTERVAL_MS) || (!use_network)) {
+ return pickSimRandomly(spaceRecord, sessionFactory, active);
+ }
+ //update the time check
+ lastTestOfSimServers=now;
+
+ verifyActiveSims(active,sessionFactory);
+
+ active=findAllActiveSims(spaceRecord, sessionFactory);
+ if (active.length==0) {
+ throw new PersistException("Unable to find any active sims (after doing a check)!");
+ }
+ return pickSimRandomly(spaceRecord, sessionFactory, active);
+ }
+
+ private static SimRecord pickSimRandomly(final SpaceRecord spaceRecord, SessionFactory sessionFactory, SimRecord[] active) throws PersistException {
+ SimRecord rec;
+ //pick randomly among actives
+ rec = (SimRecord) active[Math.abs(RANDOM.nextInt() % active.length)];
+ spaceRecord.setSimID(rec.getSimID());
+ updateRecordAndUpdateModifiedTime(spaceRecord, sessionFactory, true);
+ return rec;
+ }
+
+ private static SimRecord[] findAllActiveSims(final SpaceRecord spaceRecord, SessionFactory sessionFactory) throws PersistException {
HibernateTask task = new HibernateTask() {
public Object run(Session hibernateSession) {
+ Query simsQuery = hibernateSession.getNamedQuery(SimPersistTasks.SIMS_BY_ACTIVE);
+ simsQuery.setBoolean("active", true);
+ return (SimRecord[]) simsQuery.list().toArray(new SimRecord[0]);
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (SimRecord[]) task.execute();
+ }
+ public static SimRecord findOrAssignSim_OLD_VERSION(final SpaceRecord spaceRecord, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
SimRecord simRecord = null;
if (spaceRecord.getSimID() != -1) {
Query simQuery = hibernateSession.getNamedQuery(SimPersistTasks.SIM_BY_ID);
@@ -146,7 +274,7 @@
simRecord = (SimRecord) simQuery.uniqueResult();
if (simRecord == null || simRecord.isActive() == false) {
spaceRecord.setSimID(-1);
- updateRecordAndUpdateModifiedTime(spaceRecord,hibernateSession,true);
+ updateRecordAndUpdateModifiedTime(spaceRecord, hibernateSession, true);
simRecord = null;
} else {
return simRecord;
@@ -162,7 +290,7 @@
//TODO pick a sim based on load, not at random
simRecord = (SimRecord) sims[Math.abs(RANDOM.nextInt() % sims.length)];
spaceRecord.setSimID(simRecord.getSimID());
- updateRecordAndUpdateModifiedTime(spaceRecord,hibernateSession,true);
+ updateRecordAndUpdateModifiedTime(spaceRecord, hibernateSession, true);
return simRecord;
}
};
@@ -180,7 +308,7 @@
return null;
}
SpaceRecord record = new SpaceRecord(displayName, ownerUsername);
- record=updateRecordAndUpdateModifiedTime(record, hibernateSession, false);
+ record = updateRecordAndUpdateModifiedTime(record, hibernateSession, false);
return record;
}
};
@@ -265,7 +393,7 @@
if (account == null) { //happens for guests, who can never write
return false;
}
- if(account.isFrozen()){ //tsk tsk
+ if (account.isFrozen()) { //tsk tsk
return false;
}
@@ -292,7 +420,7 @@
for (int i = 0; i < members.length; i++) {
if (account.getUsername().equals(members[i].getMemberUsername())) {
- if(members[i].getRole() == SpaceMemberDocument.BUILDER_ROLE || members[i].getRole() == SpaceMemberDocument.EDITOR_ROLE){
+ if (members[i].getRole() == SpaceMemb...
[truncated message content] |
|
From: <ian...@us...> - 2007-10-07 00:23:16
|
Revision: 484
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=484&view=rev
Author: iansmith
Date: 2007-10-06 17:23:19 -0700 (Sat, 06 Oct 2007)
Log Message:
-----------
After feeling guilty about the build situations, I've added at least a bandage.
There is a new mojo connected to ogoglio-server's build process that verifies that your server.xml is complete with respect to the context.xml in the server's war. It will print out various helpful messages if it sees your configuration is wrong. This means that the context.xml in a war is *the law* and that we will refuse to build (much less run) on a development machine that is incorrectly configured in terms of server.xml in the tomcat dir.
You need to add <tomcat.home> to your settings.xml--but I have improved the error messages so at least it will tell you if you don't have it.
Updated the wiki.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
Added Paths:
-----------
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java
Added: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java (rev 0)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java 2007-10-07 00:23:19 UTC (rev 484)
@@ -0,0 +1,167 @@
+package com.ogoglio.plugin;
+
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+import nanoxml.XMLElement;
+
+import org.apache.maven.plugin.AbstractMojo;
+import org.apache.maven.plugin.MojoExecutionException;
+import org.apache.maven.plugin.MojoFailureException;
+
+/**
+ * @goal verifyEnvironment
+ */
+public class VerifyEnvironmentMojo extends AbstractMojo {
+ private static final String RESOURCE_MSG = "Typically, <Resource> configurations look like this:\n" + "<Resource name=\"UserDatabase\" auth=\"Container\"" + "\ttype=\"org.apache.catalina.UserDatabase\"\n" + "\tdescription=\"User database that can be updated and saved (for the manager appl.)\"\n" + "\tfactory=\"org.apache.catalina.users.MemoryUserDatabaseFactory\"\n"
+ + "\tpathname=\"conf/tomcat-users.xml\" />\n" + "<Resource name=\"ogoglioDB\" scope=\"Shareable\"\n" + "\ttype=\"javax.sql.DataSource\" auth='Container'\n" + "\tfactory=\"org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory\"\n" + "\turl=\"jdbc:mysql://127.0.0.1/og\"\n" + "\tdriverClassName=\"com.mysql.jdbc.Driver\"\n" + "\tusername=\"oguser\n" + "\tpassword=\"sssh\"\n"
+ + "\tdialect=\"org.hibernate.dialect.MySQLDialect\"\n" + "\tshow_sql=\"false\"\n" + "\tmaxIdle=\"5\"\n" + "\tmaxActive=\"50\"/>";
+
+
+ private static final String[] MAJOR_RESOURCES = {
+ "ogoglioDB",
+ "UserDatabase"
+ };
+ /**
+ * @parameter
+ */
+ protected File contextFile;
+
+ /**
+ * @parameter
+ */
+ protected File tomcatDir;
+
+ public void execute() throws MojoExecutionException, MojoFailureException {
+
+ verifyNotNull(tomcatDir, "tomcat.home");
+
+ fileOkForReading(contextFile);
+ if ((!tomcatDir.isDirectory()) || (!tomcatDir.canRead())) {
+ throw new MojoExecutionException("Can't read tomcat directory:" + tomcatDir);
+ }
+ File serverFile = new File(new File(tomcatDir, "conf"), "server.xml");
+ fileOkForReading(serverFile);
+
+ getLog().info("Verifying project context variables against server.xml config in tomcat.");
+
+ try {
+ XMLElement serverRoot = new XMLElement();
+ serverRoot.parseFromReader(new FileReader(serverFile));
+
+ XMLElement contextRoot = new XMLElement();
+ contextRoot.parseFromReader(new FileReader(contextFile));
+
+ checkContextAgainstServer(contextRoot, serverRoot);
+ } catch (IOException e) {
+ throw new MojoExecutionException("Can't read in the server or context files!", e);
+ }
+ }
+
+ private void checkContextAgainstServer(XMLElement contextRoot, XMLElement serverRoot) throws MojoExecutionException, MojoFailureException {
+ Map<String, String> resourceLinkMap;
+
+ resourceLinkMap = computeExpectedLinks(contextRoot);
+ List<String> badLinks = findMissingLinks(serverRoot, resourceLinkMap);
+ if (badLinks.size() != 0) {
+ getLog().error("Bad tomcat config file server.xml. You seem to be missing:");
+ Iterator<String> it = badLinks.iterator();
+ while (it.hasNext()) {
+ String missingGlobal = it.next();
+ getLog().error("<Environment name=\"" + missingGlobal + "\" value=\"someValue\" type=\"java.lang.String\"/>");
+ }
+ throw new MojoFailureException("Failed to verify that server.xml and context.xml are in sync!");
+ }
+ }
+
+ private List<String> findMissingLinks(XMLElement serverRoot, Map<String, String> resourceLinkMap) throws MojoExecutionException, MojoFailureException {
+ ArrayList<String> result = new ArrayList<String>();
+ List<String> areDefined=new ArrayList<String>();
+
+ XMLElement global = getChildElementSafe(serverRoot, "GlobalNamingResources");
+ XMLElement[] resource = global.getChildren("Resource");
+ if (resource.length != MAJOR_RESOURCES.length ) {
+ throw new MojoFailureException("You don't have the resource tags for the user database and the mysql database!" + RESOURCE_MSG);
+ } else {
+ for (int i=0; i<resource.length;++i) {
+ areDefined.add(resource[i].getStringAttribute("name"));
+ }
+ for (int i=0; i<MAJOR_RESOURCES.length;++i){
+ if (!areDefined.contains(MAJOR_RESOURCES[i])) {
+ throw new MojoFailureException("You are missing resource "+MAJOR_RESOURCES[i]+"."+RESOURCE_MSG);
+ }
+ }
+ }
+
+ XMLElement[] env = global.getChildren("Environment");
+ for (int i=0; i<env.length;++i) {
+ areDefined.add(env[i].getStringAttribute("name",""));
+ }
+
+ Iterator<String> it = resourceLinkMap.keySet().iterator();
+ while (it.hasNext()) {
+ String target = it.next();
+ if (!areDefined.contains(target)) {
+ result.add(target);
+ }
+ }
+ return result;
+
+ }
+
+ private Map<String,String> computeExpectedLinks(XMLElement contextRoot) throws MojoExecutionException {
+ Map<String,String> result=new HashMap<String,String>();
+
+ XMLElement[] link=contextRoot.getChildren("ResourceLink");
+ if (link.length==0) {
+ throw new MojoExecutionException("Can't find any resource links inside context element! Normally, they look like this: <ResourceLink name=\"ogoglio/mediaURL\" global=\"mediaURL\" type=\"java.lang.String\"/>");
+ }
+
+ for (int i=0; i<link.length;++i) {
+ if (link[i].getAttribute("name")==null) {
+ throw new MojoExecutionException("Badly formed resource link inside context element:"+link[i].toString()+". Normally, they look like this: <ResourceLink name=\"ogoglio/mediaURL\" global=\"mediaURL\" type=\"java.lang.String\"/>");
+ }
+ if (link[i].getAttribute("global")==null) {
+ throw new MojoExecutionException("Badly formed resource link inside context element:"+link[i].toString()+". Normally, they look like this: <ResourceLink name=\"ogoglio/mediaURL\" global=\"mediaURL\" type=\"java.lang.String\"/>");
+ }
+ if (link[i].getAttribute("type")==null) {
+ throw new MojoExecutionException("Badly formed resource link inside context element:"+link[i].toString()+". Normally, they look like this: <ResourceLink name=\"ogoglio/mediaURL\" global=\"mediaURL\" type=\"java.lang.String\"/>");
+ }
+ String name=(String)link[i].getAttribute("name");
+ String global=(String)link[i].getAttribute("global");
+ String type=(String)link[i].getAttribute("type");
+ if ((!("java.lang.String".equals(type))) && (!("javax.sql.DataSource".equals(type)))) {
+ throw new MojoExecutionException("We don't understand that resource link inside context element:"+link[i].toString()+". Normally, they look like this: <ResourceLink name=\"ogoglio/mediaURL\" global=\"mediaURL\" type=\"java.lang.String\"/>");
+ }
+ result.put(global, name);
+ }
+ return result;
+ }
+
+ private XMLElement getChildElementSafe(XMLElement contextRoot, String childName) throws MojoExecutionException {
+ XMLElement context = contextRoot.getChild(childName);
+ if (context == null) {
+ throw new MojoExecutionException("No \""+childName+"\" element found!");
+ }
+ return context;
+ }
+
+ private void fileOkForReading(File f) throws MojoExecutionException {
+ if ((!f.exists()) || (!f.canRead())) {
+ throw new MojoExecutionException("Can't read context file:" + contextFile);
+ }
+ }
+
+ public void verifyNotNull(File f, String var) throws MojoExecutionException {
+ if (f == null) {
+ throw new MojoExecutionException("You probably need to set your " + var + " in your settings.xml");
+ }
+ }
+}
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-10-06 03:11:44 UTC (rev 483)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-10-07 00:23:19 UTC (rev 484)
@@ -137,6 +137,13 @@
String[] pathElements = getPathElements((String) baseResource.getPathElement(), requestURI);
+ if (pathElements==null) {
+ Log.error("Can't understand path elements in "+getClass().getCanonicalName()+"! "+requestURI);
+ Log.error(" baseResource for errant service() is "+baseResource.getClass().getCanonicalName());
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ }
+
SiteResource requestedResource = getSiteResource(pathElements, baseResource);
if (requestedResource == null) {
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-10-06 03:11:44 UTC (rev 483)
+++ maven/trunk/ogoglio-server/pom.xml 2007-10-07 00:23:19 UTC (rev 484)
@@ -204,6 +204,8 @@
</populateDir>
<reverseFile>/tmp/reverse.xml</reverseFile>
<goalPrefix>og</goalPrefix>
+ <contextFile>${basedir}/src/main/webapp/META-INF/context.xml</contextFile>
+ <tomcatDir>${tomcat.home}</tomcatDir>
</configuration>
@@ -223,6 +225,13 @@
</targetDirectory>
</configuration>
</execution>
+ <execution>
+ <phase>process-resources</phase>
+ <id>verifyXMLProperties</id>
+ <goals>
+ <goal>verifyEnvironment</goal>
+ </goals>
+ </execution>
</executions>
</plugin>
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java 2007-10-06 03:11:44 UTC (rev 483)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java 2007-10-07 00:23:19 UTC (rev 484)
@@ -90,7 +90,7 @@
return new BaseSpaceResource();
} else {
Log.info("Turning off space servlet, this host doesn't want it.");
- return new Four04SiteResource("account");
+ return new Four04SiteResource("space");
}
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-10-10 23:31:35
|
Revision: 490
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=490&view=rev
Author: iansmith
Date: 2007-10-10 16:31:38 -0700 (Wed, 10 Oct 2007)
Log Message:
-----------
Refactored the existing socket code into package and can pass all the tests against the new abstract API (AsyncProto).
No functional effect, but this readies to switch to a new underlying protocol, Comet, real soon now.
If you are not running on the apache portable runtime the CometServlet won't do anything. Since it is not in the code path right now, it's not a functional change.
Modified Paths:
--------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml
Added Paths:
-----------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoServer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsyncServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/CometServlet.java
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java 2007-10-08 12:51:24 UTC (rev 489)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -19,6 +19,9 @@
import java.net.Socket;
import java.util.Vector;
+import com.ogoglio.message.proto.AsyncProto;
+import com.ogoglio.message.proto.AsyncProtoFactory;
+import com.ogoglio.message.proto.AsyncProtoServer;
import com.ogoglio.util.BlockingQueue;
import com.ogoglio.util.Log;
import com.ogoglio.util.NetworkUtils;
@@ -27,7 +30,7 @@
private Vector channels = new Vector();
- private ServerSocket serverSocket = null;
+ private AsyncProtoServer serverProto = null;
private ChannelSocketListenerThread listenerThread = new ChannelSocketListenerThread();
@@ -35,21 +38,13 @@
private MessageHandler messageHandler = null;
- private Listener listener = null;
-
private boolean ensureOrigin = false;
- public NetworkChannelServer(MessageHandler messageHandler, boolean ensureOrigin, Listener listener) {
- this(messageHandler, 0, ensureOrigin, listener);
- }
-
+ private Listener listener;
+
public NetworkChannelServer(MessageHandler messageHandler, int port, boolean ensureOrigin, Listener listener) {
try {
- if (port == -1) {
- serverSocket = new ServerSocket(0);
- } else {
- serverSocket = new ServerSocket(port);
- }
+ serverProto= AsyncProtoFactory.getDefaultServer(port);
} catch (IOException e) {
throw new IllegalStateException("Could not open a server socket: " + e);
}
@@ -58,13 +53,12 @@
if (listener == null) {
throw new IllegalArgumentException("bad listener " + listener);
}
- this.listener = listener;
+ this.listener=listener;
listenerThread.start();
}
public interface Listener {
public void channelAdded(TCPChannel channel);
-
public void channelRemoved(TCPChannel channel);
}
@@ -115,13 +109,13 @@
}
public Locator getLocator() {
- return new Locator(NetworkUtils.getLocalHostAddress(), serverSocket.getLocalPort());
+ return new Locator(NetworkUtils.getLocalHostAddress(), serverProto.getLocalPort());
}
public void cleanup() {
cleaned = true;
try {
- serverSocket.close();
+ serverProto.shutdown();
} catch (Exception e) {
Log.info("Trying to close server socket of NCServer",e);
// don't care
@@ -142,11 +136,11 @@
public void run() {
while (!cleaned) {
try {
- Socket clientSocket = serverSocket.accept();
- if (clientSocket == null) {
+ AsyncProto clientProto = serverProto.waitForClient();
+ if (clientProto == null) {
break;
}
- TCPChannel channel = new TCPChannel(clientSocket, messageHandler, ensureOrigin, NetworkChannelServer.this);
+ TCPChannel channel = new TCPChannel(clientProto, messageHandler, ensureOrigin, NetworkChannelServer.this);
addChannel(channel);
listener.channelAdded(channel);
} catch (IOException e) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-10-08 12:51:24 UTC (rev 489)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -18,6 +18,7 @@
import java.io.OutputStream;
import java.net.Socket;
+import com.ogoglio.message.proto.AsyncProto;
import com.ogoglio.util.BlockingQueue;
import com.ogoglio.util.Log;
@@ -26,16 +27,15 @@
private BlockingQueue messageQueue = new BlockingQueue();
- private Socket clientSocket = null;
+ private AsyncProto clientProto;
- private OutputStream socketOutput = null;
-
private boolean cleaned = false;
- public SenderQueue(Socket clientSocket, int maxSize) {
+ public SenderQueue(AsyncProto clientProto, int maxSize) {
messageQueue.setMaxSize(maxSize);
+ this.clientProto = clientProto;
try {
- socketOutput = clientSocket.getOutputStream();
+ this.clientProto.prepareOutput();
} catch (IOException e) {
throw new IllegalStateException("Could not get socket output stream: " + e);
}
@@ -47,18 +47,9 @@
public void cleanup() {
cleaned = true;
- try {
- if (clientSocket!=null) {
- clientSocket.close();
- }
- if (socketOutput!=null) {
- socketOutput.close();
- }
- if (messageQueue!=null) {
- messageQueue.close();
- }
- } catch (IOException e) {
- Log.info("IOException trying cleanup SenderQueue",e);
+ clientProto.shutdown();
+ if (messageQueue != null) {
+ messageQueue.close();
}
}
@@ -70,8 +61,7 @@
String messageString = message.toString();
Command command = new Command(Command.MESSAGE, messageString.length());
try {
- socketOutput.write((command + "\n").getBytes());
- socketOutput.write(messageString.getBytes());
+ clientProto.sendMessage(command.toString(),messageString);
} catch (IOException e) {
if (!cleaned) {
e.printStackTrace();
@@ -92,7 +82,7 @@
Message message = (Message) messageQueue.dequeue();
unsafeSendMessage(message);
} catch (Throwable e) {
- Log.error("Could not send message",e);
+ Log.error("Could not send message", e);
break;
}
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-08 12:51:24 UTC (rev 489)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -15,9 +15,9 @@
package com.ogoglio.message;
import java.io.IOException;
-import java.net.InetSocketAddress;
-import java.net.Socket;
+import com.ogoglio.message.proto.AsyncProto;
+import com.ogoglio.message.proto.AsyncProtoFactory;
import com.ogoglio.util.Log;
import com.ogoglio.util.NetworkUtils;
import com.ogoglio.util.BlockingQueue.QueueClosedException;
@@ -25,7 +25,7 @@
public class TCPChannel implements TCPMessageReader.Listener {
- private Socket clientSocket = null;
+ private AsyncProto clientProto = null;
private String remoteHostName = null;
@@ -44,13 +44,13 @@
private boolean ensureOrigin = false;
public TCPChannel(String remoteHost, int remotePort, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
- this(new Socket(remoteHost, remotePort), messageHandler, ensureOrigin, listener);
+ this(AsyncProtoFactory.getDefaultClient(remoteHost, remotePort), messageHandler, ensureOrigin, listener);
}
- public TCPChannel(Socket clientSocket, MessageHandler message_handler, boolean ensureOrigin, Listener listener) {
- this.clientSocket = clientSocket;
- remoteHostName = ((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getAddress().getHostAddress();
- remoteHostPort = ((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getPort();
+ public TCPChannel(AsyncProto proto, MessageHandler message_handler, boolean ensureOrigin, Listener listener) {
+ this.clientProto= proto;
+ remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
+ remoteHostPort = clientProto.getRemoteAddress().getPort();
if (message_handler == null) {
throw new IllegalArgumentException("bad message handler " + message_handler);
}
@@ -62,10 +62,10 @@
this.listener = listener;
// TODO Don't spand two threads for each socket! No effing way!
- senderQueue = new SenderQueue(clientSocket, 1000); //TODO what should the max queue size be?
+ senderQueue = new SenderQueue(clientProto, 1000); //TODO what should the max queue size be?
senderQueue.start();
- readerThread = new TCPMessageReader(clientSocket, message_handler, this);
+ readerThread = new TCPMessageReader(clientProto, message_handler, this);
readerThread.start();
}
@@ -75,7 +75,7 @@
}
public Locator getLocalLocator() {
- return new Locator(NetworkUtils.getLocalHostAddress(), clientSocket.getLocalPort());
+ return new Locator(NetworkUtils.getLocalHostAddress(), clientProto.getLocalPort());
}
public Locator getRemoteLocator() {
@@ -122,7 +122,7 @@
}
public String toString() {
- return "TCPChannel from " + NetworkUtils.getLocalHostAddress() + ":" + clientSocket.getLocalPort() + " to " + remoteHostName + ":" + remoteHostPort;
+ return "TCPChannel from " + NetworkUtils.getLocalHostAddress() + ":" + clientProto.getLocalPort() + " to " + remoteHostName + ":" + remoteHostPort;
}
public void socketClosed() {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-10-08 12:51:24 UTC (rev 489)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -15,30 +15,14 @@
package com.ogoglio.message;
import java.io.IOException;
-import java.io.InputStream;
-import java.net.InetSocketAddress;
-import java.net.Socket;
+import com.ogoglio.message.proto.AsyncProto;
import com.ogoglio.util.Log;
public class TCPMessageReader extends Thread {
- //TODO make this not suck ass
-
- public static int MAX_COMMAND_LENGTH = 2048; //TODO decide whether 2048 bytes is enough for a max command length
-
- public static int MAX_MESSAGE_LENGTH = 2048; //TODO decide whether 2048 bytes is enough for a max message length
-
private boolean cleaned = false;
- private boolean inCommandState = true;
-
- private StringBuffer commandBuffer = new StringBuffer();
-
- private StringBuffer messageBuffer = new StringBuffer();
-
- private InputStream socketInput = null;
-
private MessageHandler messageHandler = null;
private TCPChannel channel = null;
@@ -46,20 +30,17 @@
private String remoteHostName = null;
private int remotePort = -1;
+
+ private AsyncProto clientProto=null;
- public TCPMessageReader(Socket clientSocket, MessageHandler messageHandler, TCPChannel channel) {
+ public TCPMessageReader(AsyncProto clientProto, MessageHandler messageHandler, TCPChannel channel) {
super("TCPMessageReader");
setDaemon(true);
- if (clientSocket == null) {
- throw new IllegalArgumentException("bad socket " + clientSocket);
+ if (clientProto == null) {
+ throw new IllegalArgumentException("bad protocol to TCPMessageReader" + clientProto);
}
- try {
- socketInput = clientSocket.getInputStream();
- } catch (IOException e) {
- throw new IllegalStateException("Couldn't get client socket input stream " + e);
- }
- remoteHostName = ((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getAddress().getHostAddress();
- remotePort = ((InetSocketAddress) clientSocket.getRemoteSocketAddress()).getPort();
+ remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
+ remotePort = clientProto.getRemoteAddress().getPort();
if (messageHandler == null) {
throw new IllegalArgumentException("bad message handler: " + messageHandler);
}
@@ -68,6 +49,14 @@
throw new IllegalArgumentException("bad listener " + channel);
}
this.channel = channel;
+ this.clientProto = clientProto;
+
+ try {
+ this.clientProto.prepareInput();
+ } catch (IOException e) {
+ throw new IllegalStateException("Couldn't get client socket input stream " + e);
+ }
+
}
public interface Listener {
@@ -76,65 +65,38 @@
public void cleanup() {
cleaned = true;
- try {
- if (socketInput!=null) {
- socketInput.close();
- }
- } catch (IOException e) {
- Log.info("IOException caught trying to clean up TCPMessageReader",e);
- }
+
+ clientProto.shutdown();
}
public void run() {
try {
Command command = new Command();
while (!cleaned) {
- int inInt = socketInput.read(); //TODO speed up message reading by using a receiving buffer
+ String commandLine = clientProto.readLine();
if (cleaned) {
- return;
+ return;//somebody shut us down during our wait
}
- if (inInt == -1) {
- channel.socketClosed();
+ if (commandLine==null) {
+ channel.socketClosed(); //other side went bye-bye
return;
}
- char inChar = (char) inInt;
- if (inCommandState) {
- if (commandBuffer.length() > MAX_COMMAND_LENGTH - 1) {
- throw new IllegalStateException("Command exceeds max length: " + commandBuffer);
- }
-
- if (inChar == '\r') { // this shouldn't happen, but people are silly
- continue;
- }
- if (inChar != '\n') {
- commandBuffer.append(inChar);
- } else {
- command.reset(commandBuffer.toString());
- commandBuffer.delete(0, commandBuffer.length());
- inCommandState = false;
- }
- } else {
- if (messageBuffer.length() > MAX_MESSAGE_LENGTH - 1) {
- throw new IllegalStateException("Message exceeds max length: " + messageBuffer);
- }
-
- messageBuffer.append(inChar);
- if (messageBuffer.length() == command.getMessageLength()) {
- Message message = Message.parseMessage(messageBuffer.toString());
- if (channel.ensureOrigin()) {
- message.getOrigin().setHost(remoteHostName);
- message.getOrigin().setPort(remotePort);
- }
- try {
- messageHandler.handleMessage(message, channel);
- } catch (Throwable e) {
- Log.error("Error handling message",e);
- e.printStackTrace();
- }
- messageBuffer.delete(0, messageBuffer.length());
- inCommandState = true;
- }
+ command.reset(commandLine);
+ if (!command.getType().equals(Command.MESSAGE)) {
+ throw new IllegalStateException("Whoa! Bad message type!"+command.getType());
}
+ String msg = clientProto.readString(command.getMessageLength());
+ Message message = Message.parseMessage(msg);
+ if (channel.ensureOrigin()) {
+ message.getOrigin().setHost(remoteHostName);
+ message.getOrigin().setPort(remotePort);
+ }
+ try {
+ messageHandler.handleMessage(message, channel);
+ } catch (Throwable e) {
+ Log.error("Error handling message",e);
+ e.printStackTrace();
+ }
}
} catch (Exception e) {
if (!cleaned) {
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -0,0 +1,54 @@
+package com.ogoglio.message.proto;
+
+import java.io.IOException;
+import java.net.InetSocketAddress;
+
+/**
+ * This class represents the notion of a protocol that can be sent over a socket. The
+ * simplest possible implementation is a socket, but it could be implemented on top of
+ * something else (in our case, COMET). Note that this is used by BOTH client and server
+ * once the two are connected.
+ *
+ * @author iansmith
+ *
+ */
+public interface AsyncProto {
+
+ /**
+ * The caller needs to be able to get at the endpoint to which this proto is speaking.
+ */
+ public InetSocketAddress getRemoteAddress();
+ /**
+ * The caller needs to get the port we are talking on.
+ */
+ public int getLocalPort();
+ /**
+ * Deal with various shutdown issues.
+ */
+ public void shutdown();
+ /**
+ * Pump out a message with a given command header.
+ */
+ public void sendMessage(String command, String message) throws IOException;
+ /**
+ * Read in a line terminated by CRLF. If the socket gets closed we return null. We return
+ * "" if the line was empty. IOException means something really unexpected happened.
+ */
+ public String readLine() throws IOException;
+ /**
+ * Read in a string that is known to be a given number of bytes. Again, we return null if
+ * the socket closes but "" for a zero length string. IOException means something bad happened.
+ */
+ public String readString(int length) throws IOException;
+ /**
+ * Insure that we are ready for writing to the output.
+ * @throws IOException
+ */
+ public void prepareOutput() throws IOException;
+ /**
+ * Insure that we are ready for reading from the input.
+ * @throws IOException
+ */
+ public void prepareInput() throws IOException;
+
+}
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -0,0 +1,35 @@
+package com.ogoglio.message.proto;
+
+import java.io.IOException;
+import java.net.ServerSocket;
+
+/**
+ * This is a factory for other classes to get a handle on our async protocol handler and so
+ * we can "throw the switch" in exactly one place if we want to switch protocols.
+ *
+ * @author iansmith
+ *
+ */
+public class AsyncProtoFactory {
+
+ /**
+ * Get a handler for this protocol. This is the client side call.
+ *
+ * @param host
+ * @param port
+ * @return
+ * @throws IOException
+ */
+ public static AsyncProto getDefaultClient(String host, int port) throws IOException {
+ return new SimpleSocketAsync(host,port);
+ }
+ /**
+ * Become a serevr who waits for connections.
+ *
+ * If we are going to wait on a port, you pass it here. Note that you may not end up waiting
+ * on that port if the underlying protocol doesn't need to.
+ */
+ public static AsyncProtoServer getDefaultServer(int port) throws IOException {
+ return new SimpleSocketAsyncServer(port);
+ }
+}
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoServer.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoServer.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoServer.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -0,0 +1,20 @@
+package com.ogoglio.message.proto;
+
+import java.io.IOException;
+
+public interface AsyncProtoServer {
+ /**
+ * Wait for a client to show up and connect to us. If he does, return the object of the right type.
+ */
+ public AsyncProto waitForClient() throws IOException ;
+
+ /**
+ * Clean up
+ */
+ public void shutdown() throws IOException;
+
+ /**
+ * Get the local port, if there is one
+ */
+ public int getLocalPort();
+}
\ No newline at end of file
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -0,0 +1,84 @@
+package com.ogoglio.message.proto;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.OutputStreamWriter;
+import java.io.PrintWriter;
+import java.net.HttpURLConnection;
+import java.net.Socket;
+import java.net.URL;
+import java.net.URLConnection;
+
+import com.ogoglio.message.MessageHandler;
+import com.ogoglio.message.TCPChannel;
+import com.ogoglio.message.TCPChannel.Listener;
+
+public class CometClient {
+
+ //comet works over HTTP
+ private HttpURLConnection connection;
+
+ //most people just want to read/write to it
+ public OutputStream os;
+ public InputStream is;
+
+ private static final String CRLF="\r\n";
+ private static final String EOC = "0"+CRLF+CRLF; //end of chunk
+
+ public CometClient(String remoteHost, int remotePort, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
+ Socket socket=new Socket(remoteHost,remotePort);
+ is = socket.getInputStream();
+ os = socket.getOutputStream();
+
+ StringBuffer buff=new StringBuffer();
+ buff.append("POST /og/comet HTTP/1.1"+CRLF);
+ buff.append("content-type: text/plain"+CRLF);
+ buff.append("host: "+remoteHost+":"+remotePort+CRLF);
+ buff.append("connection: keep-alive"+CRLF);
+ buff.append("user-agent: ogoglio/viewer"+CRLF);
+ //if you omit this, the server generates the "end" immediately
+ buff.append("content-length: 17"+CRLF);
+ //buff.append("accept= text/plain"+CRLF);
+ buff.append("method: POST"+CRLF);
+ //buff.append("transfer-encoding= chunked"+CRLF);
+ buff.append(CRLF);
+ os.write(buff.toString().getBytes());
+ os.flush();
+
+ }
+
+
+ public static void main(String[] argv) {
+
+ try {
+ CometClient client=new CometClient("localhost",8080,null,false,null);
+ OutputStreamWriter wr=new OutputStreamWriter(client.os);
+ PrintWriter pr=new PrintWriter(wr);
+ StringBuffer data=new StringBuffer();
+ data.append(argv[0]+":"+argv[1]+"\n");
+
+ pr.print(data.toString());
+ pr.flush();
+
+
+ InputStreamReader isr=new InputStreamReader(client.is);
+ BufferedReader rd=new BufferedReader(isr);
+ String line=null;
+ do {
+ line=rd.readLine();
+ if (line!=null) {
+ System.out.println("<--:"+line);
+ }
+ } while (rd!=null);
+
+ } catch (IOException e) {
+ System.out.println("WHOA! IO EXCEPTION");
+ e.printStackTrace();
+ }
+ }
+
+
+}
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java 2007-10-10 23:31:38 UTC (rev 490)
@@ -0,0 +1,121 @@
+package com.ogoglio.message.proto;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+
+import com.ogoglio.util.Log;
+
+/**
+ * This is a simple impementation of a custom async proto that works on a standard TCP
+ * socket in the naive way.
+ *
+ * @author iansmith
+ *
+ */
+public class SimpleSocketAsync implements AsyncProto {
+
+ public static int MAX_COMMAND_LENGTH = 2048; //TODO decide whether 2048 bytes is enough for a max command length
+
+ public static int MAX_MESSAGE_LENGTH = 2048; //TODO decide whether 2048 bytes is enough for a max message length
+
+ private Socket socket = null;
+
+ private OutputStream socketOutput = null;
+
+ private InputStream socketInput = null;
+
+ private StringBuffer commandBuffer = new StringBuffer();
+
+ private StringBuffer messageBuffer = new StringBuffer();
+
+ public SimpleSocketAsync(String host, int port) throws IOException {
+ this(new Socket(host, port));
+ }
+
+ public SimpleSocketAsync(Socket socket) {
+ this.socket=socket;
+ }
+
+ public InetSocketAddress getRemoteAddress() {
+ return (InetSocketAddress) socket.getRemoteSocketAddress();
+ }
+
+ public int getLocalPort() {
+ return socket.getLocalPort();
+ }
+
+ public void shutdown() {
+ try {
+ if (socket != null) {
+ socket.close();
+ }
+ } catch (IOException e) {
+ Log.error("Unable to cleanup and shutdown SimpleSocketAsyncProto!", e);
+ }
+ }
+
+ public void sendMessage(String command, String message) throws IOException {
+ socketOutput.write((command + "\n").getBytes());
+ socketOutput.write(message.getBytes());
+
+ }
+
+ public String readLine() throws IOException {
+ boolean EOL = false;
+ do {
+ int inInt = socketInput.read(); //TODO speed up message reading by using a receiving buffer
+ if (inInt == -1) {
+ return null;
+ }
+ if (commandBuffer.length() > MAX_COMMAND_LENGTH - 1) {
+ throw new IllegalStateException("Command exceeds max length: " + commandBuffer);
+ }
+ char inChar = (char) inInt;
+ if (inChar == '\r') { // this shouldn't happen, but people are silly
+ continue;
+ }
+ if (inChar != '\n') {
+ commandBuffer.append(inChar);
+ } else {
+ EOL = true;
+ }
+ } while (!EOL);
+ String result = commandBuffer.toString();
+ commandBuffer.delete(0, commandBuffer.length());
+ return result;
+ }
+
+ public String readString(int length) throws IOException {
+ int ct = 0;
+ while (ct < length) {
+ int inInt = socketInput.read(); //TODO speed up message reading by using a receiving buffer
+ if (inInt == -1) {
+ return null;
+ }
+ if (messageBuffer.length() > MAX_MESSAGE_LENGTH - 1) {
+ throw new IllegalStateException("Message exceeds max length: " + messageBuffer);
+ }
+ char inChar = (char) inInt;
+ ...
[truncated message content] |
|
From: <ian...@us...> - 2007-10-16 14:23:29
|
Revision: 503
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=503&view=rev
Author: iansmith
Date: 2007-10-16 07:23:32 -0700 (Tue, 16 Oct 2007)
Log Message:
-----------
More comet prep and some reorg.
Modified Paths:
--------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Command.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NoSuchDestinationException.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml
Added Paths:
-----------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/Locator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncClientReady.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoShutdownHandle.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/MeasPerfServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/NetworkChannelServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/SimpleSocketAsyncServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/SimpleSocketWaiterThread.java
Removed Paths:
-------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Locator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoServer.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsyncServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/CometServlet.java
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -39,6 +39,7 @@
import com.ogoglio.message.NoSuchDestinationException;
import com.ogoglio.message.PayloadFactory;
import com.ogoglio.message.TCPChannel;
+import com.ogoglio.message.proto.AsyncProtoFactory;
import com.ogoglio.util.ArgumentUtils;
import com.ogoglio.util.Log;
import com.ogoglio.util.WebConstants;
@@ -56,8 +57,6 @@
public class SpaceClient implements UserInputListener, Space.Context {
- public static int DEFAULT_EVENT_PORT = 43455;
-
private Listener listener = null;
private WebAPIClient webClient = null;
@@ -104,7 +103,9 @@
space = new Space(this, spaceDoc.getSpaceID(), spaceDoc.getDisplayName(), spaceDoc.getOwnerUsername(), spaceDoc.getDisplaySea(), spaceDoc.getSeaLevel());
//create the event channel and start queuing events
- messageChannel = new TCPChannel(serviceURI.getHost(), DEFAULT_EVENT_PORT, messenger, true, new ChannelListener());
+ Object selector = AsyncProtoFactory.getDefaultInfo().getProxySpecificSelector();
+ messageChannel = new TCPChannel(AsyncProtoFactory.getDefaultClient(serviceURI.getHost(), selector),
+ messenger, true, new ChannelListener());
messenger.authenticate(authCookie);
long startWait = System.currentTimeMillis();
@@ -406,7 +407,6 @@
if (!page.getContentType().equals(event.getStringProperty(SpaceEvent.CONTENT_TYPE))) {
page.setContentType(event.getStringProperty(SpaceEvent.CONTENT_TYPE));
}
- System.out.println("Page content type: " + page.getContentType());
page.reloadContent();
} else if (SpaceEvent.ADD_DOOR_EVENT.equals(event.getName())) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Command.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Command.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Command.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -59,10 +59,10 @@
throw new IllegalStateException("Cannot have a message length < 0: " + commandString);
}
} catch (NumberFormatException e) {
- throw new IllegalArgumentException("Bad command string (bad length): " + commandString);
+ throw new IllegalArgumentException("Bad command string (bad length): >" + commandString+"<");
}
} else {
- throw new IllegalArgumentException("Bad command string: " + commandString);
+ throw new IllegalArgumentException("Bad command string: >" + commandString+"<");
}
}
Deleted: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Locator.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Locator.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Locator.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -1,98 +0,0 @@
-/* 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.message;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-
-public class Locator {
-
- public static final String SCHEME = "og";
-
- private URI uri = null;
-
- public Locator(String locatorString) {
- try {
- uri = new URI(locatorString);
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("Bad locatorString: " + locatorString);
- }
- if (uri.getPort() <= 0) {
- throw new IllegalArgumentException("bad port: " + uri.getPort());
- }
- if (!SCHEME.equals(uri.getScheme())) {
- throw new IllegalArgumentException("bad scheme: " + uri.getScheme());
- }
- }
-
- public Locator(String host, int port) {
- if (port <= 0) {
- throw new IllegalArgumentException("bad port: " + port);
- }
- try {
- uri = new URI(SCHEME + "://" + host + ":" + port + "/");
- } catch (URISyntaxException e) {
- throw new IllegalArgumentException("bad args: " + host + ", " + port);
- }
- }
-
- public String getHost() {
- return uri.getHost();
- }
-
- public void setPort(int port) {
- String newURI = uri.getScheme() + "://" + uri.getHost() + ":" + port + "/";
- try {
- uri = new URI(newURI);
- } catch (URISyntaxException e) {
- throw new IllegalStateException("Bad uri: " + newURI);
- }
- }
-
- public void setHost(String host) {
- if (host == null || host.trim().length() == 0) {
- throw new IllegalArgumentException("Bad host name: " + host);
- }
- String newURI = uri.getScheme() + "://" + host + ":" + uri.getPort() + "/";
- try {
- uri = new URI(newURI);
- } catch (URISyntaxException e) {
- throw new IllegalStateException("Bad uri: " + newURI);
- }
- }
-
- public int getPort() {
- return uri.getPort();
- }
-
- public String toString() {
- return uri.toString();
- }
-
- public boolean equals(Object object) {
- if (object == null || !(object instanceof Locator)) {
- return false;
- }
- return toString().equals(((Locator) object).toString());
- }
-
- public int hashCode() {
- return toString().hashCode();
- }
-
- public boolean matchesHostAndPort(Locator locator) {
- return getHost().equals(locator.getHost()) && getPort() == locator.getPort();
- }
-}
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -0,0 +1,144 @@
+package com.ogoglio.message;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Random;
+
+import com.ogoglio.message.proto.AsyncProto;
+import com.ogoglio.message.proto.AsyncProtoFactory;
+
+
+public class MeasPerfClient extends Thread implements MessageHandler, TCPChannel.Listener {
+
+ private static final double THRESHOLD_DANGER= 2.0; //make a note if it takes longer than this
+ private static final int MAX_SLEEP_TIME_MS= 5000; //avg 2.5secs
+ private static final int RAMP_UP_TIME= 250; //time btwn two thread creations
+ private static final int THRESHOLD_TERMINATE = 10; //we start culling senders if we see this many over THRESHOLD_DANGER
+
+ private TCPChannel channel;
+ private static Map timeMap=Collections.synchronizedMap(new HashMap());
+ private static Map senderMap=new HashMap();
+ private static List deathList=Collections.synchronizedList(new ArrayList());
+
+ private static double totalTime = 0.0;
+ private static double totalSamples=0.0;
+ private static Object totalTimeLock=new Object();
+
+ private static int warningCounter =0;
+ private static Object warningCounterLock = new Object();
+
+ private Random r=new Random();
+
+ public static void main(String[] argv) {
+ int n = Integer.parseInt(argv[0]);
+
+ try {
+ for (int i = 0; i < n; ++i) {
+ AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], AsyncProtoFactory.getDefaultInfo().getSimSpecificSelector());
+ Thread t =new MeasPerfClient(proto);
+ t.start();
+ try {
+ Thread.sleep(RAMP_UP_TIME);
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ public MeasPerfClient(AsyncProto proto) {
+ channel = new TCPChannel(proto,this,false,this);
+ }
+
+ public void run() {
+ while (true) {
+ Payload p ;
+ Message m;
+
+ try {
+ Long me=new Long(Thread.currentThread().getId());
+ while (true) {
+ p=new PayloadFactory.HeartbeatPayload();
+ long id=r.nextLong();
+ m=new Message(channel.getLocalLocator(),channel.getRemoteLocator(),id,p);
+ timeMap.put(new Long(id),new Long(System.currentTimeMillis()));
+ senderMap.put(new Long(id),me);
+ channel.sendMessage(m);
+ int ms=r.nextInt(MAX_SLEEP_TIME_MS);
+ Thread.yield();
+ Thread.sleep(ms);
+ synchronized (deathList) {
+ if (deathList.contains(me)) {
+ channel.cleanup();
+ return;
+ }
+ }
+ //did somebody close this?
+ if (channel==null) {
+ return;
+ }
+ }
+ } catch (NoSuchDestinationException e) {
+ e.printStackTrace();
+ } catch (InterruptedException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+
+ public void handleMessage(Message message, TCPChannel sourceChannel) throws NoSuchDestinationException {
+ Long id=new Long(message.getSpaceID());
+ long now=System.currentTimeMillis();
+ if (!timeMap.containsKey(id)) {
+ System.out.println("Can't find id in time map! Ignoring id:"+id);
+ return;
+ }
+ Long before=(Long)timeMap.get(id);
+ long diff = now-before.longValue();
+ double secs = ((double)diff)/1000.0;
+ synchronized (totalTimeLock) {
+ totalTime+=secs;
+ totalSamples+=1.0;
+ }
+ if (r.nextInt(100)==0) {
+ double avg;
+ synchronized (totalTimeLock) {
+ avg=totalTime/totalSamples;
+ }
+ System.out.println(""+ channel.getLocalLocator() +" Sample Turnaround time on heartbeat:"+secs+" and avg:"+avg);
+ }
+ if (secs>THRESHOLD_DANGER) {
+ boolean cull=false;
+
+ synchronized (warningCounterLock) {
+ warningCounter++;
+ if (warningCounter>THRESHOLD_TERMINATE) {
+ cull=true;
+ warningCounter=0;
+ }
+ }
+ //not enough to convince us to blow up somebody?
+ if (!cull) {
+ return;
+ }
+ //ok, the sender of the message should die if it took too long...
+ Long die = (Long)senderMap.get(id);
+ synchronized (deathList) {
+ if (!deathList.contains(die)) {
+ System.out.println("Killing sender "+die+" because of too much time elapsed:"+secs);
+ deathList.add(die);
+ }
+ }
+ }
+ }
+
+ public void channelClosed(TCPChannel channel) {
+ System.out.println("Got a message about closing channel:"+channel.hashCode()+ " vs. "+this.channel.hashCode());
+ }
+}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -16,6 +16,7 @@
import nanoxml.XMLElement;
+import com.ogoglio.message.proto.Locator;
import com.ogoglio.util.ArgumentUtils;
public class Message {
Deleted: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NetworkChannelServer.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -1,182 +0,0 @@
-/* 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.message;
-
-import java.io.IOException;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.Vector;
-
-import com.ogoglio.message.proto.AsyncProto;
-import com.ogoglio.message.proto.AsyncProtoFactory;
-import com.ogoglio.message.proto.AsyncProtoServer;
-import com.ogoglio.util.BlockingQueue;
-import com.ogoglio.util.Log;
-import com.ogoglio.util.NetworkUtils;
-
-public class NetworkChannelServer implements TCPChannel.Listener {
-
- private Vector channels = new Vector();
-
- private AsyncProtoServer serverProto = null;
-
- private ChannelSocketListenerThread listenerThread = new ChannelSocketListenerThread();
-
- private boolean cleaned = false;
-
- private MessageHandler messageHandler = null;
-
- private boolean ensureOrigin = false;
-
- private Listener listener;
-
- public NetworkChannelServer(MessageHandler messageHandler, int port, boolean ensureOrigin, Listener listener) {
- try {
- serverProto= AsyncProtoFactory.getDefaultServer(port);
- } catch (IOException e) {
- throw new IllegalStateException("Could not open a server socket: " + e);
- }
- this.messageHandler = messageHandler;
- this.ensureOrigin = ensureOrigin;
- if (listener == null) {
- throw new IllegalArgumentException("bad listener " + listener);
- }
- this.listener=listener;
- listenerThread.start();
- }
-
- public interface Listener {
- public void channelAdded(TCPChannel channel);
- public void channelRemoved(TCPChannel channel);
- }
-
- public void distribute(Payload payload, long spaceID) {
- TCPChannel[] channels = getChannels();
- for (int i = 0; i < channels.length; i++) {
- Message message = new Message(getLocator(), channels[i].getRemoteLocator(), spaceID, payload);
- try {
- channels[i].sendMessage(message);
- } catch (NoSuchDestinationException e) {
- e.printStackTrace();
- } catch (BlockingQueue.QueueClosedException e) {
- e.printStackTrace();
- }
- }
- }
-
- public void distributeExclusively(Payload payload, Locator excludedLocator) {
- TCPChannel[] channels = getChannels();
- for (int i = 0; i < channels.length; i++) {
- if (!channels[i].getRemoteLocator().matchesHostAndPort(excludedLocator)) {
- Message message = new Message(getLocator(), channels[i].getRemoteLocator(), -1, payload);
- try {
- channels[i].sendMessage(message);
- } catch (NoSuchDestinationException e) {
- e.printStackTrace();
- }
- }
- }
- }
-
- public synchronized void sendMessage(Message message) throws NoSuchDestinationException {
- Locator remoteLocator = message.getProxy() != null ? message.getProxy() : message.getDestination();
- TCPChannel[] channels = getChannels();
- for (int i = 0; i < channels.length; i++) {
- if (channels[i].getRemoteLocator().matchesHostAndPort(remoteLocator)) {
- channels[i].sendMessage(message);
- return;
- }
- }
-
- Log.info("Attempted location??: " + remoteLocator);
- //for (int i = 0; i < channels.length; i++) {
- // System.out.println("Available channels: " + channels[i].getRemoteLocator());
- //}
-
- throw new NoSuchDestinationException("Not local or for a connected channel: " + message);
- }
-
- public Locator getLocator() {
- return new Locator(NetworkUtils.getLocalHostAddress(), serverProto.getLocalPort());
- }
-
- public void cleanup() {
- cleaned = true;
- try {
- serverProto.shutdown();
- } catch (Exception e) {
- Log.info("Trying to close server socket of NCServer",e);
- // don't care
- }
- TCPChannel[] channels = getChannels();
- for (int i = 0; i < channels.length; i++) {
- channels[i].cleanup();
- }
- }
-
- private class ChannelSocketListenerThread extends Thread {
-
- public ChannelSocketListenerThread() {
- super("NetworkChannelServer");
- setDaemon(true);
- }
-
- public void run() {
- while (!cleaned) {
- try {
- AsyncProto clientProto = serverProto.waitForClient();
- if (clientProto == null) {
- break;
- }
- TCPChannel channel = new TCPChannel(clientProto, messageHandler, ensureOrigin, NetworkChannelServer.this);
- addChannel(channel);
- listener.channelAdded(channel);
- } catch (IOException e) {
- if (!cleaned) {
- e.printStackTrace();
- }
- break;
- }
- }
- if (!cleaned) {
- Log.error("Unclean client socket listener thread exiting.");
- }
- }
- }
-
- public synchronized void closeChannel(Locator remoteLocator) {
- TCPChannel[] channels = getChannels();
- for (int i = 0; i < channels.length; i++) {
- if (remoteLocator.equals(channels[i].getRemoteLocator())) {
- channels[i].cleanup();
- return;
- }
- }
- }
-
- private synchronized void addChannel(TCPChannel channel) {
- channels.add(channel);
- }
-
- public synchronized TCPChannel[] getChannels() {
- return (TCPChannel[]) channels.toArray(new TCPChannel[0]);
- }
-
- public synchronized void channelClosed(TCPChannel channel) {
- channels.remove(channel);
- listener.channelRemoved(channel);
- }
-
-}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NoSuchDestinationException.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NoSuchDestinationException.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/NoSuchDestinationException.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -14,6 +14,8 @@
package com.ogoglio.message;
+import com.ogoglio.message.proto.Locator;
+
public class NoSuchDestinationException extends Exception {
public NoSuchDestinationException(Locator destination) {
super("No such destination: " + destination.toString());
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -18,6 +18,7 @@
import com.ogoglio.message.proto.AsyncProto;
import com.ogoglio.message.proto.AsyncProtoFactory;
+import com.ogoglio.message.proto.Locator;
import com.ogoglio.util.Log;
import com.ogoglio.util.NetworkUtils;
import com.ogoglio.util.BlockingQueue.QueueClosedException;
@@ -27,9 +28,9 @@
private AsyncProto clientProto = null;
- private String remoteHostName = null;
+// private String remoteHostName = null;
- private int remoteHostPort = -1;
+ // private int remoteHostPort = -1;
private TCPMessageReader readerThread = null;
@@ -43,14 +44,14 @@
private boolean ensureOrigin = false;
- public TCPChannel(String remoteHost, int remotePort, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
- this(AsyncProtoFactory.getDefaultClient(remoteHost, remotePort), messageHandler, ensureOrigin, listener);
+ public TCPChannel(String remoteHost, Object selector, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
+ this(AsyncProtoFactory.getDefaultClient(remoteHost, selector), messageHandler, ensureOrigin, listener);
}
public TCPChannel(AsyncProto proto, MessageHandler message_handler, boolean ensureOrigin, Listener listener) {
this.clientProto= proto;
- remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
- remoteHostPort = clientProto.getRemoteAddress().getPort();
+ //remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
+ //remoteHostPort = clientProto.getRemoteAddress().getPort();
if (message_handler == null) {
throw new IllegalArgumentException("bad message handler " + message_handler);
}
@@ -70,16 +71,20 @@
}
+
+ public void clientReady(AsyncProto newlyConnectedProto) {
+ Log.info("Client connected from: "+newlyConnectedProto.getRemoteLocator());
+ }
public interface Listener {
public void channelClosed(TCPChannel channel);
}
public Locator getLocalLocator() {
- return new Locator(NetworkUtils.getLocalHostAddress(), clientProto.getLocalPort());
+ return clientProto.getLocalLocator();
}
public Locator getRemoteLocator() {
- return new Locator(remoteHostName, remoteHostPort);
+ return clientProto.getRemoteLocator();
}
public void cleanup() {
@@ -103,26 +108,26 @@
public void sendMessage(Message message) throws NoSuchDestinationException {
if(message.getProxy() != null) {
- if(message.getProxy().getPort() != remoteHostPort || !message.getProxy().getHost().equals(remoteHostName)){
+ if (!message.getProxy().equals(clientProto.getRemoteLocator())) {
throw new NoSuchDestinationException("Passed a message to a TCPChannel with the wrong proxy: " + message.getProxy());
}
- } else if (message.getDestination().getPort() != remoteHostPort || !message.getDestination().getHost().equals(remoteHostName)){
+ } else if (!message.getDestination().equals(clientProto.getRemoteLocator())){
throw new NoSuchDestinationException("Passed a message to a TCPChannel with the wrong destination: " + message.getDestination());
}
try {
senderQueue.sendMessage(message);
} catch (QueueOverflowException e) {
- Log.error("Queue overflow: " + remoteHostName + ":" + remoteHostPort,e);
+ Log.error("Queue overflow: " + clientProto.getRemoteLocator(),e);
cleanup();
} catch (QueueClosedException e) {
- Log.error("Queue closed: " + remoteHostName + ":" + remoteHostPort,e);
+ Log.error("Queue closed: " + clientProto.getRemoteLocator(),e);
cleanup();
}
}
public String toString() {
- return "TCPChannel from " + NetworkUtils.getLocalHostAddress() + ":" + clientProto.getLocalPort() + " to " + remoteHostName + ":" + remoteHostPort;
+ return "TCPChannel from " + clientProto.getLocalLocator() + " to " +clientProto.getRemoteLocator();
}
public void socketClosed() {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-10-15 19:10:23 UTC (rev 502)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-10-16 14:23:32 UTC (rev 503)
@@ -27,9 +27,9 @@
private TCPChannel channel = null;
- private String remoteHostName = null;
+ //private String remoteHostName = null;
- private int remotePort = -1;
+ //private int remotePort = -1;
private AsyncProto clientProto=null;
@@ -39,8 +39,8 @@
if (clientProto == null) {
throw new IllegalArgumentException("bad protocol to TCPMessageReader" + clientProto);
}
- remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
- remotePort = clientProto.getRemoteAddress().getPort();
+ //remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
+ //remotePort = clientProto.getRemoteAddress().getPort();
if (messageHandler == null) {
throw new IllegalArgumentException("bad message handler: " + messageHandler);
}
@@ -82,14 +82,12 @@
return;
}
command.reset(commandLine);
- if (!command.getType().equals(Command.MESSAGE)) {
- throw new IllegalStateException("Whoa! Bad message type!"+command.getType());
- }
String msg = clientProto.readString(command.getMessageLength());
Message message = Message.parseMessage(msg);...
[truncated message content] |
|
From: <ian...@us...> - 2007-10-27 23:33:45
|
Revision: 543
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=543&view=rev
Author: iansmith
Date: 2007-10-27 16:33:47 -0700 (Sat, 27 Oct 2007)
Log Message:
-----------
More comet support, currently turned off. No external effect.
Modified Paths:
--------------
maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java
maven/trunk/ogoglio-server/pom.xml
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/MeasPerfServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/NetworkChannelServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/SimpleSocketAsyncServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
Added Paths:
-----------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometInfo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometChannelManager.java
Modified: maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java
===================================================================
--- maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/dev-plugins/src/main/java/com/ogoglio/plugin/VerifyEnvironmentMojo.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -8,7 +8,6 @@
import java.util.Iterator;
import java.util.List;
import java.util.Map;
-import java.util.Set;
import nanoxml.XMLElement;
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -57,6 +57,8 @@
public class SpaceClient implements UserInputListener, Space.Context {
+ private static final long START_UP_WAIT_MS = 15000;
+
private Listener listener = null;
private WebAPIClient webClient = null;
@@ -104,11 +106,11 @@
//create the event channel and start queuing events
Object selector = AsyncProtoFactory.getDefaultInfo().getProxySpecificSelector();
- messageChannel = new TCPChannel(AsyncProtoFactory.getDefaultClient(serviceURI.getHost(), selector), messenger, true, new ChannelListener());
+ messageChannel = new TCPChannel(AsyncProtoFactory.getDefaultClient(serviceURI.getHost(), selector), messenger, true, new ChannelListener(), true);
messenger.authenticate(authCookie);
long startWait = System.currentTimeMillis();
- while (System.currentTimeMillis() < startWait + 45000 && messenger.authStatus == messenger.INIT_STATUS) {
+ while (System.currentTimeMillis() < startWait + START_UP_WAIT_MS && messenger.authStatus == messenger.INIT_STATUS) {
try {
Thread.sleep(100);
} catch (Exception e) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -38,7 +38,8 @@
try {
for (int i = 0; i < n; ++i) {
- AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], AsyncProtoFactory.getDefaultInfo().getSimSpecificSelector());
+// AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], AsyncProtoFactory.getDefaultInfo().getSimSpecificSelector());
+ AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], "/fart/poop");
Thread t =new MeasPerfClient(proto);
t.start();
try {
@@ -53,7 +54,8 @@
}
public MeasPerfClient(AsyncProto proto) {
- channel = new TCPChannel(proto,this,false,this);
+ System.out.println("FOUND A CLIENT PROTO:"+(proto!=null));
+ channel = new TCPChannel(proto,this,false,this,true);
}
public void run() {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -15,8 +15,6 @@
package com.ogoglio.message;
import java.io.IOException;
-import java.io.OutputStream;
-import java.net.Socket;
import com.ogoglio.message.proto.AsyncProto;
import com.ogoglio.util.BlockingQueue;
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -14,13 +14,9 @@
package com.ogoglio.message;
-import java.io.IOException;
-
import com.ogoglio.message.proto.AsyncProto;
-import com.ogoglio.message.proto.AsyncProtoFactory;
import com.ogoglio.message.proto.Locator;
import com.ogoglio.util.Log;
-import com.ogoglio.util.NetworkUtils;
import com.ogoglio.util.BlockingQueue.QueueClosedException;
import com.ogoglio.util.BlockingQueue.QueueOverflowException;
@@ -44,11 +40,8 @@
private boolean ensureOrigin = false;
- public TCPChannel(String remoteHost, Object selector, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
- this(AsyncProtoFactory.getDefaultClient(remoteHost, selector), messageHandler, ensureOrigin, listener);
- }
-
- public TCPChannel(AsyncProto proto, MessageHandler message_handler, boolean ensureOrigin, Listener listener) {
+ public TCPChannel(AsyncProto proto, MessageHandler message_handler, boolean ensureOrigin,
+ Listener listener, boolean needAReaderThread) {
this.clientProto= proto;
//remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
//remoteHostPort = clientProto.getRemoteAddress().getPort();
@@ -66,9 +59,16 @@
senderQueue = new SenderQueue(clientProto, 1000); //TODO what should the max queue size be?
senderQueue.start();
- readerThread = new TCPMessageReader(clientProto, message_handler, this);
- readerThread.start();
+ //this is a wee bit hairy. all clients need a reader thread. servers need a reader
+ //thread depending on their protocol.
+ Log.info("Comet got into a TCP channel:"+needAReaderThread);
+ if (needAReaderThread) {
+ readerThread = new TCPMessageReader(clientProto, message_handler, this);
+ readerThread.start();
+ }
+
+
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -6,13 +6,12 @@
* This is a factory for other classes to get a handle on our async protocol handler and so
* we can "throw the switch" in exactly one place if we want to switch protocols.
*
- * Clients call the getDefaultClient() routine and servers call the waitForClient() routine.
- *
* @author iansmith
*
*/
public class AsyncProtoFactory {
-
+ //this is the magic switch
+ private static final boolean USE_SIMPLE_SOCKET=true;
/**
* Get a handler for this protocol. This is the client side call. This fails if the connection
* cannot be made. It returns a connected proto object.
@@ -23,10 +22,38 @@
* @throws IOException
*/
public static AsyncProto getDefaultClient(String host, Object selector) throws IOException {
+ if (USE_SIMPLE_SOCKET) {
+ return simpleSocketProto(host, selector);
+ } else {
+ return cometProto(host,(String)selector);
+ }
+ }
+
+ private static AsyncProto cometProto(String host, String selector) throws IOException {
+ return new CometClient(host,selector).getProto();
+ }
+
+ private static AsyncProto simpleSocketProto(String host, Object selector) throws IOException {
+ if (USE_SIMPLE_SOCKET) {
+ return simpleSocketInfo(host, selector);
+ } else {
+ return cometProto(host,(String)selector);
+ }
+ }
+
+ private static AsyncProtoInfo cometInfo() {
+ return new CometInfo();
+ }
+
+ private static AsyncProto simpleSocketInfo(String host, Object selector) throws IOException {
return new SimpleSocketAsync(host, ((Integer)selector).intValue());
}
public static AsyncProtoInfo getDefaultInfo() {
- return new SimpleSocketInfo();
+ if (USE_SIMPLE_SOCKET) {
+ return new SimpleSocketInfo();
+ } else {
+ return new CometInfo();
+ }
}
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -1,7 +1,5 @@
package com.ogoglio.message.proto;
-import java.net.URI;
-import java.net.URISyntaxException;
/**
* The intention of this interface is to hide various specifics about how the underlying async
@@ -13,7 +11,5 @@
public interface AsyncProtoInfo {
public String getScheme();
public Object getProxySpecificSelector();
- public Object getSimSpecificSelector();
-
- public URI getURI(String host, Object selector) throws URISyntaxException;
+ public Object getSimSpecificSelector();
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -7,7 +7,9 @@
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
+import java.io.Writer;
import java.net.HttpURLConnection;
+import java.net.InetSocketAddress;
import java.net.Socket;
import com.ogoglio.message.MessageHandler;
@@ -25,13 +27,49 @@
private static final String CRLF="\r\n";
private static final String EOC = "0"+CRLF+CRLF; //end of chunk
+ public static final int XXX_PORT=8080;
+ public static final String XXX_MOUNT_POINT="/og/comet";
+
+ private Locator remote;
+ private Locator local;
+
+ public CometClient(String remoteHost, String selector) throws IOException {
+ Socket socket=new Socket(remoteHost,XXX_PORT); ///UGH
+ is = socket.getInputStream();
+ os = socket.getOutputStream();
+
+ StringBuffer buff=new StringBuffer();
+ buff.append("POST "+XXX_MOUNT_POINT+selector+" HTTP/1.1"+CRLF);
+ buff.append("content-type: text/plain"+CRLF);
+ buff.append("host: "+remoteHost+":"+XXX_PORT+CRLF);
+ buff.append("connection: keep-alive"+CRLF);
+ buff.append("user-agent: ogoglio/viewer"+CRLF);
+ //if you omit this, the server generates the "end" immediately
+ buff.append("content-length: 17"+CRLF);
+ //buff.append("accept= text/plain"+CRLF);
+ buff.append("method: POST"+CRLF);
+ //buff.append("transfer-encoding= chunked"+CRLF);
+ buff.append(CRLF);
+ os.write(buff.toString().getBytes());
+ os.flush();
+
+ String scheme = new CometInfo().getScheme();
+ remote = new Locator(scheme+"://"+remoteHost+":"+XXX_PORT+XXX_MOUNT_POINT+selector);
+ InetSocketAddress addr=(InetSocketAddress)socket.getLocalSocketAddress();
+ local = new Locator(scheme+"://UNKNOWN@"+addr.getHostName()+":"+addr.getPort()+"/");
+ }
+
+ public CometProto getProto() {
+ return new CometProto(new PrintWriter(os), is, remote, local);
+ }
+
public CometClient(String remoteHost, int remotePort, MessageHandler messageHandler, boolean ensureOrigin, Listener listener) throws IOException {
Socket socket=new Socket(remoteHost,remotePort);
is = socket.getInputStream();
os = socket.getOutputStream();
StringBuffer buff=new StringBuffer();
- buff.append("POST /og/comet HTTP/1.1"+CRLF);
+ buff.append("POST /og/comet/fart/poop HTTP/1.1"+CRLF);
buff.append("content-type: text/plain"+CRLF);
buff.append("host: "+remoteHost+":"+remotePort+CRLF);
buff.append("connection: keep-alive"+CRLF);
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometInfo.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometInfo.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometInfo.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -0,0 +1,21 @@
+package com.ogoglio.message.proto;
+
+
+public class CometInfo implements AsyncProtoInfo {
+
+ public CometInfo() {
+ }
+
+ public Object getProxySpecificSelector() {
+ return "/proxy";
+ }
+
+ public String getScheme() {
+ return "comet";
+ }
+
+ public Object getSimSpecificSelector() {
+ return "/sim";
+ }
+
+}
Added: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java (rev 0)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -0,0 +1,88 @@
+package com.ogoglio.message.proto;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.Writer;
+
+import com.ogoglio.util.Log;
+
+public class CometProto implements AsyncProto {
+ private Writer writer;
+ private InputStream input;
+ private Locator local;
+ private Locator remote;
+
+ private StringBuffer waiting=new StringBuffer();
+
+ public CometProto(Writer writer, InputStream input, Locator remote, Locator local) {
+ this.writer=writer;
+ this.input=input;
+ this.local=local;
+ this.remote=remote;
+ }
+
+ public Locator getLocalLocator() {
+ return local;
+ }
+
+ public Locator getRemoteLocator() {
+ return remote;
+ }
+
+ public void prepareInput() throws IOException {
+ //no effect in comet
+ }
+
+ public void prepareOutput() throws IOException {
+ //no effect in comment
+ }
+
+ public String readLine() throws IOException {
+ byte[] buf = new byte[512];
+ waiting.delete(0, waiting.length());
+ do {
+ int n = input.read(buf); //can throw an IOException
+ if (n > 0) {
+ waiting.append(new String(buf, 0, n));
+ } else if (n < 0) {
+ Log.error("Unable to read from stream! Error: read returned < 0:"+n);
+ throw new IOException("Can't read from stream [<0 in read()]");
+ }
+ } while (input.available() >0);
+
+ if (waiting.indexOf("\n")!=waiting.length()) {
+ Log.error("Did not get a single string terminated by a newline!");
+ }
+ return waiting.toString();
+ }
+
+ public String readString(int length) throws IOException {
+ byte[] buf = new byte[512];
+ waiting.delete(0, waiting.length());
+ do {
+ int n = input.read(buf); //can throw an IOException
+ if (n > 0) {
+ waiting.append(new String(buf,0,n));
+ } else if (n < 0) {
+ Log.error("Unable to read from stream! Error: read returned < 0:"+n);
+ throw new IOException("Can't read from stream [<0 in read()]");
+ }
+ } while (waiting.length()<length);
+ return waiting.toString();
+ }
+
+ public void sendMessage(String command, String message) throws IOException {
+ writer.write(command + "\n");
+ writer.write(message);
+ }
+
+ public void shutdown() {
+ try {
+ input.close();
+ writer.close();
+ } catch (IOException e) {
+ Log.error("Error closing input/output streams of comet!",e);
+ }
+ }
+
+}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -23,8 +23,4 @@
return new Integer(DEFAULT_SIM_PORT);
}
- public URI getURI(String host, Object selector) throws URISyntaxException {
- return new URI(getScheme() + "://" + host + ":" + selector+ "/");
- }
-
}
Modified: maven/trunk/ogoglio-server/pom.xml
===================================================================
--- maven/trunk/ogoglio-server/pom.xml 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-server/pom.xml 2007-10-27 23:33:47 UTC (rev 543)
@@ -196,6 +196,7 @@
<!-- these are for the populate -->
<configuration>
+
<serviceURI>${ogoglio.baseURL}</serviceURI>
<username>${ogoglio.bootstrapUser}</username>
<password>${ogoglio.bootstrapUserPW}</password>
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -1,12 +1,22 @@
package com.ogoglio.message.server;
import java.io.IOException;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import com.ogoglio.message.MessageHandler;
import com.ogoglio.message.proto.AsyncProtoInfo;
+import com.ogoglio.message.proto.CometInfo;
import com.ogoglio.message.proto.SimpleSocketInfo;
+import com.ogoglio.util.Log;
public class AsyncProtoServerFactory {
+ //this is the magic switch
+ private static final boolean USE_SIMPLE_SOCKET=true;
+ private static Map selectorToChannelManager = Collections.synchronizedMap(new HashMap());
+
/**
* Become a server who waits for connections.
*
@@ -17,11 +27,19 @@
* used when you want to not be a server anymore and want to clean up the resources.
*/
public static AsyncProtoShutdownHandle waitForClient(Object serverSelector, AsyncClientReady ready) throws IOException {
- return simpleSocketImpl(((Integer)serverSelector).intValue(),ready);
+ if (USE_SIMPLE_SOCKET) {
+ return simpleSocketImpl(((Integer)serverSelector).intValue(),ready);
+ } else {
+ return cometImpl(serverSelector, ready);
+ }
}
public static AsyncProtoInfo getInfo() {
- return simpleSocketInfo();
+ if (USE_SIMPLE_SOCKET) {
+ return simpleSocketInfo();
+ } else {
+ return cometInfo();
+ }
}
private static AsyncProtoInfo simpleSocketInfo() {
@@ -34,4 +52,33 @@
return waiter.getShutdownHandle();
}
+ private static AsyncProtoInfo cometInfo() {
+ return new CometInfo();
+ }
+
+ private static AsyncProtoShutdownHandle cometImpl(Object serverSelector, AsyncClientReady ready) {
+ String urlPart = (String)serverSelector;
+ CometChannelManager mgr = new CometChannelManager(urlPart,ready);
+ selectorToChannelManager.put(serverSelector, mgr);
+ return mgr;
+ }
+
+ public static boolean needsReaderThreadsOnServerSide() {
+ return USE_SIMPLE_SOCKET;
+ }
+
+ public static void registerMessageHandler(Object serverSelector, MessageHandler messageHandler) {
+ if (USE_SIMPLE_SOCKET) {
+ Log.error("Should NEVER call registerMessageHandler with simple socket proto!");
+ return;
+ }
+
+ if (!selectorToChannelManager.containsKey(serverSelector)) {
+ throw new IllegalArgumentException("Bad server selector provided to registerMessageHandler:"+serverSelector.getClass().getCanonicalName());
+ }
+
+ CometChannelManager mgr = (CometChannelManager) selectorToChannelManager.get(serverSelector);
+ mgr.setMessageHandler(messageHandler);
+ }
+
}
Added: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometChannelManager.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometChannelManager.java (rev 0)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometChannelManager.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -0,0 +1,56 @@
+package com.ogoglio.message.server;
+
+import com.ogoglio.message.MessageHandler;
+import com.ogoglio.message.proto.CometClient;
+import com.ogoglio.message.proto.CometInfo;
+import com.ogoglio.message.proto.CometProto;
+import com.ogoglio.message.proto.Locator;
+import com.ogoglio.util.Log;
+
+public class CometChannelManager implements AsyncProtoShutdownHandle {
+
+ private AsyncClientReady ready;
+ private CometProto proto;
+ private StringBuffer buffer=new StringBuffer();
+ private String urlPart;
+ private MessageHandler messageHandler;
+
+ public CometChannelManager(String urlPart, AsyncClientReady ready) {
+ this.ready=ready;
+ this.urlPart=urlPart;
+ CometServlet.addChannel(urlPart, this);
+ }
+
+ public Locator getLocalLocator() {
+ if (proto==null) {
+ String XXX_localMachine = "localhost";
+ String scheme = new CometInfo().getScheme();
+ String cometURL=scheme+"://"+XXX_localMachine+":"+CometClient.XXX_PORT+CometClient.XXX_MOUNT_POINT+urlPart;
+ return new Locator(cometURL);
+ }
+ return proto.getLocalLocator();
+ }
+
+ public AsyncClientReady getReady() {
+ return ready;
+ }
+
+ public void setConn(CometProto proto) {
+ this.proto=proto;
+ }
+ public void shutdown() {
+ if (proto!=null) {
+ proto.shutdown();
+ }
+ }
+ public void addData(byte[] buf, int n) {
+ //ugh, stupid inefficiency
+ String tmp=new String(buf,0,n);
+ buffer.append(tmp);
+ Log.info("COMET: Got some data in the buffer:"+buffer);
+ }
+
+ public void setMessageHandler(MessageHandler messageHandler) {
+ this.messageHandler=messageHandler;
+ }
+}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java 2007-10-22 23:58:51 UTC (rev 542)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java 2007-10-27 23:33:47 UTC (rev 543)
@@ -2,8 +2,14 @@
import java.io.IOException;
import java.io.InputStream;
+import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
@@ -12,28 +18,51 @@
import org.apache.catalina.CometEvent;
import org.apache.catalina.CometProcessor;
+import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;
+import com.ogoglio.message.proto.CometProto;
+import com.ogoglio.message.proto.Locator;
import com.ogoglio.util.Log;
public class CometServlet extends HttpServlet implements CometProcessor {
- protected ArrayList connections = new ArrayList();
- protected MessageSender messageSender = null;
-
public void init() throws ServletException {
- messageSender = new MessageSender();
- Thread messageSenderThread = new Thread(messageSender, "MessageSender[" + getServletContext() + "]");
- messageSenderThread.setDaemon(true);
- messageSenderThread.start();
+ //TEMP
+ //MeasPerfServer measServer=new MeasPerfServer();
+ //NetworkChannelServer ncs=new NetworkChannelServer(measServer,"/fart/poop",false,measServer);
+ //measServer.channelServer(ncs);
}
public void destroy() {
- connections.clear();
- messageSender.stop();
- messageSender = null;
+ for (Iterator iterator = clientChannelMap.keySet().iterator(); iterator.hasNext();) {
+ String subspace = (String) iterator.next();
+ List mgrList = (List)clientChannelMap.get(subspace);
+ for (Iterator iterator2 = mgrList.iterator(); iterator2.hasNext();) {
+ CometChannelManager mgr = (CometChannelManager) iterator2.next();
+ mgr.shutdown();
+ }
+ }
}
+ private static Map clientChannelMap=Collections.synchronizedMap(new HashMap());
+ public static void addChannel(String subspace, CometChannelManager mgr) {
+ if (!clientChannelMap.containsKey(subspace)) {
+ clientChannelMap.put(subspace, Collections.synchronizedList(new ArrayList()));
+ Log.info("Comet listener on space:"+subspace);
+ }
+ List clienChannList = (List)clientChannelMap.get(subspace);
+ clienChannList.add(mgr);
+ }
+ public static void removeChannel(String subspace, CometChannelManager mgr) {
+ if (!clientChannelMap.containsKey(subspace)) {
+ Log.error("Tried to remove a channel for a subspace we don't have in CometServlet:"+subspace);
+ } else {
+ List clientChannList = (List)clientChannelMap.get(subspace);
+ clientChannList.remove(mgr);
+ }
+ }
+
/**
* Process the given Comet event.
*
@@ -47,119 +76,79 @@
if (event.getEventType() == CometEvent.EventType.BEGIN) {
//event.setTimeout(60000);
Log.info("Begin for session: " + request.getSession(true).getId());
- PrintWriter writer = response.getWriter();
- response.setContentType("text/plain");
- writer.println("<!doctype html public \"-//w3c//dtd html 4.0 transitional//en\">");
- writer.println("<head><title>JSP Chat</title></head><body bgcolor=\"#FFFFFF\">");
- writer.flush();
- synchronized (connections) {
- connections.add(response);
+ String path = request.getPathInfo();
+ if (clientChannelMap.containsKey(path)) {
+ List channList = (List)clientChannelMap.get(path);
+ for (Iterator iterator = channList.iterator(); iterator.hasNext();) {
+ CometChannelManager mgr= (CometChannelManager)iterator.next();
+ prepareComet(request, response, mgr);
+ }
+ } else {
+ Log.warn("Path "+path+" request for comet but nobody interested....");
+ Log.info("Paths of interest to somebody in comet:");
+ Iterator iterator=clientChannelMap.keySet().iterator();
+ while (iterator.hasNext()) {
+ String p= (String ) iterator.next();
+ Log.info("Interested in comet path:"+p);
+ }
}
- //drainDataBuffer(event, request);
} else if (event.getEventType() == CometEvent.EventType.ERROR) {
Log.error("Error for session: " + request.getSession(true).getId()+"-->"+event.getEventSubType());
if (event.getEventSubType()==CometEvent.EventSubType.TIMEOUT) {
Log.info("Timeout ignored!");
return;
}
- synchronized (connections) {
- ...
[truncated message content] |
|
From: <ian...@us...> - 2007-11-09 00:10:45
|
Revision: 566
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=566&view=rev
Author: iansmith
Date: 2007-11-08 16:10:49 -0800 (Thu, 08 Nov 2007)
Log Message:
-----------
Whew. It's in, comet support is now turned on. This should have no effect on coders or users, except that we can now pass quietly through firewalls.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-common/pom.xml
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIDescriptor.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/Locator.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketAsync.java
maven/trunk/ogoglio-integration-test/pom.xml
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncClientReady.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/AsyncProtoServerFactory.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometChannelManager.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/CometServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/MeasPerfServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/NetworkChannelServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/message/server/SimpleSocketAsyncServer.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/Sim.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/SpaceServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/WebappServletBase.java
maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java
Added Paths:
-----------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/LineOrientedCRLFSocket.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/NegativeReadValueException.java
maven/trunk/ogoglio-integration-test/src/main/java/com/
maven/trunk/ogoglio-integration-test/src/main/java/com/ogoglio/
maven/trunk/ogoglio-integration-test/src/main/java/com/ogoglio/amazon/
maven/trunk/ogoglio-integration-test/src/main/java/com/ogoglio/amazon/test/
maven/trunk/ogoglio-integration-test/src/main/java/com/ogoglio/amazon/test/CometTest.java
maven/trunk/ogoglio-integration-test/src/main/scripts/
maven/trunk/ogoglio-integration-test/src/main/scripts/testComet
Removed Paths:
-------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometInfo.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/SimpleSocketInfo.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -224,7 +224,6 @@
String headerName = (String) headerNames.nextElement();
connection.setRequestProperty(headerName, request.getHeader(headerName));
}
-
if ("POST".equals(method)) {
connection.setDoOutput(true);
InputStream requestInput = request.getInputStream();
Modified: maven/trunk/ogoglio-common/pom.xml
===================================================================
--- maven/trunk/ogoglio-common/pom.xml 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/pom.xml 2007-11-09 00:10:49 UTC (rev 566)
@@ -50,6 +50,7 @@
<artifactId>commons-logging</artifactId>
<version>1.1</version>
</dependency>
+
</dependencies>
</project>
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -17,6 +17,8 @@
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
+import java.util.Timer;
+import java.util.TimerTask;
import java.util.Vector;
import java.util.zip.ZipInputStream;
@@ -75,8 +77,12 @@
private boolean cleanedUp = false;
+ private static final long HEARTBEAT_INTERVAL=5000L;
+
private BodyDataProvider bodyDataProvider = new NetworkBodyDataProvider();
+ private Timer heartbeatTimer=null;
+
public SpaceClient(long spaceID, URI serviceURI, String authCookie, Listener listener) throws IOException {
ArgumentUtils.assertNotNegative(spaceID);
ArgumentUtils.assertNotNull(serviceURI);
@@ -105,8 +111,7 @@
space = new Space(this, spaceDoc.getSpaceID(), spaceDoc.getDisplayName(), spaceDoc.getOwnerUsername(), spaceDoc.getDisplaySea(), spaceDoc.getSeaLevel());
//create the event channel and start queuing events
- Object selector = AsyncProtoFactory.getDefaultInfo().getProxySpecificSelector();
- messageChannel = new TCPChannel(AsyncProtoFactory.getDefaultClient(serviceURI.getHost(), selector), messenger, true, new ChannelListener(), true);
+ messageChannel = new TCPChannel(AsyncProtoFactory.getDefaultClient(descriptor, true), messenger, true, new ChannelListener(), true, "space-client");
messenger.authenticate(authCookie);
long startWait = System.currentTimeMillis();
@@ -128,6 +133,11 @@
}
}
+ //this download can take longer than the timeout of our connection, so force heartbeats
+ //before we start doing all this
+ heartbeatTimer = new Timer("Heartbeat Client", true);
+ heartbeatTimer.schedule(new HeartbeatTimer(), 0L, HEARTBEAT_INTERVAL);
+
ThingDocument[] thingDocs = spaceDoc.getThingDocuments();
for (int i = 0; i < thingDocs.length; i++) {
Template template = space.getTemplate(thingDocs[i].getTemplateID());
@@ -684,6 +694,15 @@
messageChannel.cleanup();
waitingMessages.clear();
}
+
+ public void heartbeat() throws IOException {
+ Message message = new Message(messageChannel.getLocalLocator(), messageChannel.getRemoteLocator(), space.getSpaceID(), new PayloadFactory.HeartbeatPayload());
+ try {
+ messageChannel.sendMessage(message);
+ } catch (NoSuchDestinationException e) {
+ throw new IOException("Could not send heartbeat message");
+ }
+ }
}
private class ChannelListener implements TCPChannel.Listener {
@@ -732,7 +751,9 @@
messageChannel.sendMessage(new Message(messageChannel.getLocalLocator(), messageChannel.getRemoteLocator(), space.getSpaceID(), new PayloadFactory.LogoutPayload(accountDoc.getUsername())));
} catch (Exception e) {
}
-
+ if (heartbeatTimer!=null) { //there is a race condition at startup that makes this necessary
+ heartbeatTimer.cancel();
+ }
messenger.cleanup();
}
@@ -757,7 +778,7 @@
public ZipInputStream getBodyData(long bodyDataID) {
try {
- if(bodyDataID == -1){
+ if (bodyDataID == -1) {
return webClient.getBodyData(WebConstants.GUEST_BODY_FILE_NAME);
} else {
BodyDataDocument dataDoc = webClient.getBodyDataDocument(bodyDataID);
@@ -803,4 +824,14 @@
}
+ private class HeartbeatTimer extends TimerTask {
+ public void run() {
+ try {
+ messenger.heartbeat();
+ } catch (IOException e) {
+ Log.error("Unable to send heartbeat message, IOException:"+e.getMessage());
+ }
+ }
+ }
+
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIDescriptor.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIDescriptor.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/WebAPIDescriptor.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -3,6 +3,8 @@
import java.io.IOException;
import java.net.URI;
+import com.ogoglio.message.proto.AsyncProto;
+import com.ogoglio.message.proto.AsyncProtoFactory;
import com.ogoglio.util.ArgumentUtils;
import com.ogoglio.util.WebConstants;
@@ -181,4 +183,20 @@
public URI getServiceStateURI() {
return WebAPIUtil.appendToURI(getSpacesURI(), "state/");
}
+
+ public URI getCometProxyURI() {
+ return WebAPIUtil.appendToURI(serviceURI, "comet/"+getCometProxyPath());
+ }
+
+ public URI getCometSimURI() {
+ return WebAPIUtil.appendToURI(serviceURI, "comet/"+getCometSimPath());
+ }
+
+ public String getCometProxyPath() {
+ return "proxy";
+ }
+
+ public String getCometSimPath() {
+ return "sim";
+ }
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/MeasPerfClient.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -39,7 +39,7 @@
try {
for (int i = 0; i < n; ++i) {
// AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], AsyncProtoFactory.getDefaultInfo().getSimSpecificSelector());
- AsyncProto proto=AsyncProtoFactory.getDefaultClient(argv[1], "/fart/poop");
+ AsyncProto proto=null;/*AsyncProtoFactory.getDefaultClient(argv[1], "/fart/poop");*/
Thread t =new MeasPerfClient(proto);
t.start();
try {
@@ -48,14 +48,14 @@
e.printStackTrace();
}
}
- } catch (IOException e) {
+ } catch (Exception e) {
e.printStackTrace();
}
}
public MeasPerfClient(AsyncProto proto) {
System.out.println("FOUND A CLIENT PROTO:"+(proto!=null));
- channel = new TCPChannel(proto,this,false,this,true);
+ channel = new TCPChannel(proto,this,false,this,true,"measure-perf-client");
}
public void run() {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/Message.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -21,7 +21,7 @@
public class Message {
- private static final String MESSAGE = "Message";
+ public static final String MESSAGE = "Message";
private static final String PROXY = "proxy";
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -39,7 +39,9 @@
}
}
- public void start() {
+ public void start(String debugInfo) {
+ senderThread.setName("sender-thread-"+debugInfo+"-"+senderThread.getId());
+ //Log.info("Launching thread "+senderThread.getName());
senderThread.start();
}
@@ -62,8 +64,7 @@
clientProto.sendMessage(command.toString(),messageString);
} catch (IOException e) {
if (!cleaned) {
- e.printStackTrace();
- throw new IllegalStateException("Error writing " + message);
+ throw new IllegalStateException("Error writing to client:" + message);
}
}
}
@@ -80,8 +81,8 @@
Message message = (Message) messageQueue.dequeue();
unsafeSendMessage(message);
} catch (Throwable e) {
- Log.error("Could not send message", e);
- break;
+ //Log.error("Could not send message [aborting thread:"+Thread.currentThread().getName()+"]:"+ e.getClass().getName()+":"+e.getMessage());
+ cleaned=true;
}
}
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -32,7 +32,7 @@
private SenderQueue senderQueue = null;
- //private MessageHandler messageHandler = null;
+ private MessageHandler messageHandler = null;
//private boolean cleaned = false;
@@ -41,7 +41,8 @@
private boolean ensureOrigin = false;
public TCPChannel(AsyncProto proto, MessageHandler message_handler, boolean ensureOrigin,
- Listener listener, boolean needAReaderThread) {
+ Listener listener, boolean needAReaderThread, String debugInfo) {
+
this.clientProto= proto;
//remoteHostName = clientProto.getRemoteAddress().getAddress().getHostAddress();
//remoteHostPort = clientProto.getRemoteAddress().getPort();
@@ -57,21 +58,21 @@
// TODO Don't spand two threads for each socket! No effing way!
senderQueue = new SenderQueue(clientProto, 1000); //TODO what should the max queue size be?
- senderQueue.start();
+ senderQueue.start(debugInfo);
//this is a wee bit hairy. all clients need a reader thread. servers need a reader
//thread depending on their protocol.
- Log.info("Comet got into a TCP channel:"+needAReaderThread);
if (needAReaderThread) {
readerThread = new TCPMessageReader(clientProto, message_handler, this);
+ readerThread.setName("tcp-reader-"+debugInfo+"-"+readerThread.getId());
+ //Log.info("Starting reader thread:"+readerThread.getName());
readerThread.start();
}
-
+ this.messageHandler=message_handler;
+
}
-
-
public void clientReady(AsyncProto newlyConnectedProto) {
Log.info("Client connected from: "+newlyConnectedProto.getRemoteLocator());
}
@@ -112,7 +113,7 @@
throw new NoSuchDestinationException("Passed a message to a TCPChannel with the wrong proxy: " + message.getProxy());
}
} else if (!message.getDestination().equals(clientProto.getRemoteLocator())){
- throw new NoSuchDestinationException("Passed a message to a TCPChannel with the wrong destination: " + message.getDestination());
+ throw new NoSuchDestinationException("Passed a message to a TCPChannel with the wrong destination: " + message.getDestination() + " but should be " + clientProto.getRemoteLocator());
}
try {
@@ -137,4 +138,7 @@
public boolean ensureOrigin() {
return ensureOrigin;
}
+ public MessageHandler getMessageHandler() {
+ return messageHandler;
+ }
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPMessageReader.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -17,6 +17,7 @@
import java.io.IOException;
import com.ogoglio.message.proto.AsyncProto;
+import com.ogoglio.message.proto.NegativeReadValueException;
import com.ogoglio.util.Log;
public class TCPMessageReader extends Thread {
@@ -71,39 +72,38 @@
public void run() {
try {
- Command command = new Command();
while (!cleaned) {
- String commandLine = clientProto.readLine();
- if (cleaned) {
- return;//somebody shut us down during our wait
+ String msg=clientProto.readLine();
+ if (msg!=null) {
+ //Log.info("TCP Message Reader:"+msg);
+ Message message = Message.parseMessage(msg);
+ if (channel.ensureOrigin()) {
+ message.setOrigin(clientProto.getRemoteLocator());
+ //message.getOrigin().setHost(remoteHostName);
+ //message.getOrigin().setPort(remotePort);
+ }
+ try {
+ messageHandler.handleMessage(message, channel);
+ } catch (Throwable e) {
+ Log.error("Error handling our message",e);
+ e.printStackTrace();
+ }
}
- if (commandLine==null) {
- channel.socketClosed(); //other side went bye-bye
- return;
- }
- command.reset(commandLine);
- String msg = clientProto.readString(command.getMessageLength());
- Message message = Message.parseMessage(msg);
- if (channel.ensureOrigin()) {
- message.setOrigin(clientProto.getRemoteLocator());
- //message.getOrigin().setHost(remoteHostName);
- //message.getOrigin().setPort(remotePort);
- }
- try {
- messageHandler.handleMessage(message, channel);
- } catch (Throwable e) {
- Log.error("Error handling message",e);
- e.printStackTrace();
- }
}
+ } catch (NegativeReadValueException e) {
+ //Log.info("Negative value from read, assuming server closed connection!");
+ channel.socketClosed();
+ cleaned=true;
} catch (Exception e) {
if (!cleaned) {
e.printStackTrace();
}
}
if (!cleaned) {
- Log.warn("Unclean client socket listener thread exiting");
+ Log.warn("Unclean client socket listener thread exiting:"+Thread.currentThread().getName());
channel.socketClosed();
+ } else {
+ //Log.info("Cleaned up and exiting TCPMessageReader thread:"+Thread.currentThread().getName());
}
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProto.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -1,7 +1,6 @@
package com.ogoglio.message.proto;
import java.io.IOException;
-import java.net.InetSocketAddress;
/**
* This class represents the notion of a protocol that can be sent over a socket. The
@@ -30,17 +29,9 @@
* Pump out a message with a given command header.
*/
public void sendMessage(String command, String message) throws IOException;
- /**
- * Read in a line terminated by CRLF. If the socket gets closed we return null. We return
- * "" if the line was empty. IOException means something really unexpected happened.
- */
+ //returns the next fully ready message or null
public String readLine() throws IOException;
/**
- * Read in a string that is known to be a given number of bytes. Again, we return null if
- * the socket closes but "" for a zero length string. IOException means something bad happened.
- */
- public String readString(int length) throws IOException;
- /**
* Insure that we are ready for writing to the output.It is required this be called before
* attempting to send.
* @throws IOException
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -1,7 +1,11 @@
package com.ogoglio.message.proto;
import java.io.IOException;
+import java.net.Socket;
+import java.net.URI;
+import com.ogoglio.client.WebAPIDescriptor;
+
/**
* This is a factory for other classes to get a handle on our async protocol handler and so
* we can "throw the switch" in exactly one place if we want to switch protocols.
@@ -11,49 +15,46 @@
*/
public class AsyncProtoFactory {
//this is the magic switch
- private static final boolean USE_SIMPLE_SOCKET=true;
+ private static final boolean USE_SIMPLE_SOCKET=false;
/**
* Get a handler for this protocol. This is the client side call. This fails if the connection
* cannot be made. It returns a connected proto object.
*
- * @param host
- * @param selector a proto-specific object
+ * @param host pass in a service descriptor (tells us how to find the server)
+ * @param boolean wantProxy true if you want the proxy server, false if you want the real sim server
* @return
* @throws IOException
*/
- public static AsyncProto getDefaultClient(String host, Object selector) throws IOException {
+ public static AsyncProto getDefaultClient(WebAPIDescriptor descriptor, boolean wantProxy) throws IOException {
if (USE_SIMPLE_SOCKET) {
- return simpleSocketProto(host, selector);
+ if (wantProxy) {
+ return simpleSocketProto(descriptor.getServiceStateURI().getHost(),SimpleSocketAsync.DEFAULT_PROXY_PORT);
+ } else {
+ return simpleSocketProto(descriptor.getServiceStateURI().getHost(),SimpleSocketAsync.DEFAULT_SIM_PORT);
+ }
} else {
- return cometProto(host,(String)selector);
+ if (wantProxy) {
+ return cometProto(descriptor.getCometProxyURI());
+ } else {
+ return cometProto(descriptor.getCometSimURI());
+ }
}
}
- private static AsyncProto cometProto(String host, String selector) throws IOException {
- return new CometClient(host,selector).getProto();
+ private static AsyncProto cometProto(URI cometURI) throws IOException {
+ //return new CometClient(host,selector).getProto();
+ return CometClient.getProto(cometURI);
}
- private static AsyncProto simpleSocketProto(String host, Object selector) throws IOException {
- if (USE_SIMPLE_SOCKET) {
- return simpleSocketInfo(host, selector);
- } else {
- return cometProto(host,(String)selector);
- }
+ private static AsyncProto simpleSocketProto(String host, int port) throws IOException {
+ return new SimpleSocketAsync(new Socket(host,port));
}
- private static AsyncProtoInfo cometInfo() {
- return new CometInfo();
- }
-
- private static AsyncProto simpleSocketInfo(String host, Object selector) throws IOException {
- return new SimpleSocketAsync(host, ((Integer)selector).intValue());
- }
-
- public static AsyncProtoInfo getDefaultInfo() {
+ public static String getScheme() {
if (USE_SIMPLE_SOCKET) {
- return new SimpleSocketInfo();
+ return "og";
} else {
- return new CometInfo();
+ return "comet";
}
}
}
Deleted: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoInfo.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -1,15 +0,0 @@
-package com.ogoglio.message.proto;
-
-
-/**
- * The intention of this interface is to hide various specifics about how the underlying async
- * protocol is implemented. The objects returned here should be considered opaque.
- *
- * @author iansmith
- *
- */
-public interface AsyncProtoInfo {
- public String getScheme();
- public Object getProxySpecificSelector();
- public Object getSimSpecificSelector();
-}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-11-08 00:25:45 UTC (rev 565)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-11-09 00:10:49 UTC (rev 566)
@@ -1,119 +1,141 @@
package com.ogoglio.message.proto;
-import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
-import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
-import java.io.PrintWriter;
import java.io.Writer;
-import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.URI;
-import com.ogoglio.message.MessageHandler;
-import com.ogoglio.message.TCPChannel.Listener;
+import com.ogoglio.message.Command;
+import com.ogoglio.util.Log;
public class CometClient {
- //comet works over HTTP
- private HttpURLConnection connection;
+ public static final int BAD_CMD = -210;
+ public static final int CMD_BUFFERED = -230;
+
+ private static final String EXPECTED_OK="HTTP/1.1 200";
- //most people just want to read/write to it
- public OutputStream os;
- public InputStream is;
+ public static final String CRLF="\r\n";
+ public static final String EOC = "0"+CRLF+CRLF; //end of chunk
- private static final String CRLF="\r\n";
- private static final String EOC = "0"+CRLF+CRLF; //end of chunk
+ public static final int COMET_BUFF_SIZE=512;
- public static final int XXX_PORT=8080;
- public static final String XXX_MOUNT_POINT="/og/comet";
+ //public static final int XXX_PORT=8080;
+ //public static final String XXX_MOUNT_POINT="/og/comet";
+ //public static final String XXX_HOST="localhost";
- private Locator remote;
- private Locator local;
-
- public CometClient(String remoteHost, String selector) throws IOException {
- Socket socket=new Socket(remoteHost,XXX_PORT); ///UGH
- is = socket.getInputStream();
- os = socket.getOutputStream();
+ public static CometProto getProto(URI uri) throws IOException {
+ Socket socket = new Socket();
+ int port=80;
+ if (uri.getPort()>0) {
+ port=uri.getPort();
+ }
+ SocketAddress address = new InetSocketAddress(uri.getHost(),port);
+ socket.connect(address,15000);
- StringBuffer buff=new StringBuffer();
- buff.append("POST "+XXX_MOUNT_POINT+selector+" HTTP/1.1"+CRLF);
- buff.append("content-type: text/plain"+CRLF);
- buff.append("host: "+remoteHost+":"+XXX_PORT+CRLF);
- buff.append("connection: keep-alive"+CRLF);
- buff.append("user-agent: ogoglio/viewer"+CRLF);
- //if you omit this, the server generates the "end" immediately
- buff.append("content-length: 17"+CRLF);
- //buff.append("accept= text/plain"+CRLF);
- buff.append("method: POST"+CRLF);
- //buff.append("transfer-encoding= chunked"+CRLF);
- buff.append(CRLF);
- os.write(buff.toString().getBytes());
- os.flush();
-
- String scheme = new CometInfo().getScheme();
- remote = new Locator(scheme+"://"+remoteHost+":"+XXX_PORT+XXX_MOUNT_POINT+selector);
+ InputStream is=socket.getInputStream();
+ OutputStream os=socket.getOutputStream();
+ Writer writer=new OutputStreamWriter(os);
+
+ sendHTTPStartupInfo(writer, uri.getHost(), uri.getPath());
+ String response=getHTTPRes...
[truncated message content] |
|
From: <ian...@us...> - 2007-11-09 01:53:23
|
Revision: 567
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=567&view=rev
Author: iansmith
Date: 2007-11-08 17:53:26 -0800 (Thu, 08 Nov 2007)
Log Message:
-----------
Fixed the stupid thing where URLs in the server.xml had to end in /.
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-11-09 00:10:49 UTC (rev 566)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/AbstractResourceServlet.java 2007-11-09 01:53:26 UTC (rev 567)
@@ -76,6 +76,10 @@
initContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
baseUrl = (String) envCtx.lookup(OGOGLIO_BASE_URL_KEY);
+ if (!baseUrl.endsWith("/")) {
+ baseUrl=baseUrl+"/";
+ Log.warn(OGOGLIO_BASE_URL_KEY+" in server.xml should end in / but we're patching it:"+baseUrl);
+ }
}
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-11-09 00:10:49 UTC (rev 566)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/site/SimServlet.java 2007-11-09 01:53:26 UTC (rev 567)
@@ -64,6 +64,8 @@
import com.ogoglio.xml.server.DocumentFactory;
public class SimServlet extends OgoglioServletBase {
+ private static final String OGOGLIO_BASE_SIM_URL_KEY = "ogoglio/baseSimURL";
+
private static final String RELOAD_PARAMETER = "reload";
public static final String THING_SERVICE_PATH_ELEMENT = "service";
@@ -91,7 +93,12 @@
//don't bother with the sim if nobody wants it
if (servletNeeded) {
- simURI = new URI((String) envCtx.lookup("ogoglio/baseSimURL"));
+ String tmpSimUrl=(String) envCtx.lookup(OGOGLIO_BASE_SIM_URL_KEY);
+ if (!tmpSimUrl.endsWith("/")) {
+ tmpSimUrl=tmpSimUrl+"/";
+ Log.warn(OGOGLIO_BASE_SIM_URL_KEY+" in server.xml should end in / but we are patching it:"+tmpSimUrl);
+ }
+ simURI = new URI(tmpSimUrl);
SimRecord simRecord = SimPersistTasks.findSimsBySimURI(simURI, getSessionFactory());
if (simRecord != null) {
//error
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-11-13 00:39:05
|
Revision: 573
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=573&view=rev
Author: iansmith
Date: 2007-11-12 16:39:09 -0800 (Mon, 12 Nov 2007)
Log Message:
-----------
Added support for logging using log4j if you have it. Otherwise, no effect.
A
Modified Paths:
--------------
maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java
maven/trunk/ogoglio-common/src/test/java/com/ogoglio/loadtest/MultiuserTests.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
Modified: maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java
===================================================================
--- maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-appdev/src/main/java/com/ogoglio/appdev/servlet/MigratedResourceServlet.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -50,14 +50,14 @@
private SessionFactory getOrCreateHibernateSessionFactory(ServletConfig config, Context context) {
SessionFactory sessionFactory = (SessionFactory) config.getServletContext().getAttribute(HIBERNATE_SESSION_FACTORY_KEY);
if (sessionFactory == null) {
- Log.test(config.getServletName() + ": checking DB version");
+ Log.info(config.getServletName() + ": checking DB version");
MigrationSupport ms = getMigration();
if (!ms.verifyVersion(config, context)) {
throw new IllegalStateException("Cannot find a DB configuration for hibernate!");
}
sessionFactory = ms.getCurrentConfiguration().configure().buildSessionFactory();
config.getServletContext().setAttribute(HIBERNATE_SESSION_FACTORY_KEY, sessionFactory);
- Log.test(config.getServletName() + ": DB version OK");
+ //Log.info(config.getServletName() + ": DB version OK");
}
return sessionFactory;
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/AsyncProtoFactory.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -41,6 +41,15 @@
}
}
+ public static AsyncProto getDefaultClient(URI uri) throws IOException {
+ if (USE_SIMPLE_SOCKET) {
+ return simpleSocketProto(uri.getHost(), uri.getPort());
+ } else {
+ return cometProto(uri);
+ }
+ }
+
+
private static AsyncProto cometProto(URI cometURI) throws IOException {
//return new CometClient(host,selector).getProto();
return CometClient.getProto(cometURI);
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -2,10 +2,14 @@
import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import com.ogoglio.xml.SpaceEvent;
+
public class Log {
- private static class Logger {
+ private static class SimpleLogger {
public void debug(Object msg) {
System.out.println(msg);
@@ -42,41 +46,163 @@
}
}
- static Logger log = new Logger();
+ static SimpleLogger simple = new SimpleLogger();
+ static boolean haveLog4J = false;
+ static Object reallyALogger=null;
+ static Object reallyTheSpaceLogger=null;
+ static boolean faultedInAlready=false;
+ static Method m_debug=null;
+ static Method m_info=null;
+ static Method m_info_throw=null;
+ static Method m_warn=null;
+ static Method m_error=null;
+ static Method m_error_throw=null;
+ static Method m_trace=null;
+ static Method m_test=null;
+ static Method m_logMemory=null;
+ static String[] ignoredSpaceEventNames = {
+ SpaceEvent.USER_START_MOTION_EVENT,
+ SpaceEvent.THING_START_MOTION_EVENT,
+ SpaceEvent.SHAPE_START_MOTION_EVENT
+ };
+ public static void faultInLogger() {
+ try {
+ if (faultedInAlready) {
+ return;
+ }
+ faultedInAlready=true;
+ //do we have linkage to log4j?
+ Class clazz=Class.forName("org.apache.log4j.Logger");
+ Object[] arrayOfOneInstWithString = new Object[] {"com.ogoglio"};
+ Object[] arrayOfOneInstWithSpaceString = new Object[] {"com.ogoglio.space"};
+
+ Class[] arrayOfOneClass = new Class[] {new Object().getClass()};
+ Class[] arrayOfTwoClasses = new Class[] {new Object().getClass(), new Throwable().getClass()};
+
+ haveLog4J=true;
+ Method m=clazz.getMethod("getLogger", new Class[] { "".getClass()});
+ //setup the methods
+ reallyALogger=m.invoke(null, arrayOfOneInstWithString);
+ reallyTheSpaceLogger=m.invoke(null, arrayOfOneInstWithSpaceString);
+ m_debug=clazz.getMethod("debug",arrayOfOneClass);
+ m_info=clazz.getMethod("info",arrayOfOneClass);
+ m_info_throw=clazz.getMethod("info",arrayOfTwoClasses);
+ m_warn=clazz.getMethod("warn",arrayOfOneClass);
+ m_error=clazz.getMethod("error",arrayOfOneClass);
+ m_error_throw=clazz.getMethod("error",arrayOfTwoClasses);
+ m_trace=clazz.getMethod("info",arrayOfOneClass);
+ m_test=clazz.getMethod("debug",arrayOfOneClass);
+ m_logMemory=clazz.getMethod("info",arrayOfOneClass);
+
+
+
+ } catch (IllegalAccessException e) {
+ haveLog4J=false;
+ simple.warn("Something went wrong in log4j init [illegalaccess]:"+e.getMessage());
+ } catch (InvocationTargetException e) {
+ haveLog4J=false;
+ simple.warn("Something went wrong in log4j init [invocationtarget]:"+e.getMessage());
+ } catch (NoSuchMethodException e) {
+ haveLog4J=false;
+ simple.warn("Something went wrong in log4j init [nosuchmethod]:"+e.getMessage());
+ } catch (ClassNotFoundException exception) {
+ haveLog4J=false;
+ simple.warn("Didn't find log4j, so using a simple logger.");
+ }
+ }
+
public static void debug(Object msg) {
- log.debug(msg);
+ faultInLogger();
+ useLog4jOrSimple(msg, m_debug);
}
+ private static void useLog4jOrSimple(Object msg,Method method) {
+ useLog4jOrSimple(msg, null,method);
+ }
+ private static void useLog4jOrSimple(Object msg, Object throwable, Method method) {
+ useLog4jOrSimple(msg, reallyALogger, throwable,method);
+ }
+
+ private static void useLog4jOrSimple(Object msg, Object logger, Object throwable, Method method) {
+ try {
+ if (haveLog4J) {
+ if (throwable==null) {
+ method.invoke(logger, new Object[] {msg});
+ } else {
+ method.invoke(logger, new Object[] {msg,throwable});
+ }
+ } else {
+ simple.debug(msg);
+ }
+ } catch (InvocationTargetException ex) {
+ haveLog4J=false;
+ simple.debug("Probablem using log4j [invocationtarget]:"+ex.getMessage());
+ } catch (IllegalAccessException ex) {
+ haveLog4J=false;
+ simple.debug("Probably using log4j [illegalaccess]:"+ex.getMessage());
+ }
+ }
+
public static void info(Object msg) {
- log.info(msg);
+ faultInLogger();
+ useLog4jOrSimple(msg, m_info);
}
public static void info(Object msg, Throwable t) {
- log.info(msg, t);
+ useLog4jOrSimple(msg, t, m_info_throw);
}
public static void warn(Object msg) {
- log.warn(msg);
+ faultInLogger();
+ useLog4jOrSimple(msg, m_warn);
}
public static void error(Object msg) {
- log.error(msg);
+ faultInLogger();
+ useLog4jOrSimple(msg, m_error);
}
public static void error(Object msg, Throwable t) {
- log.error(msg, t);
+ useLog4jOrSimple(msg, t, m_error_throw);
}
public static void trace(Object msg) {
- log.trace(msg);
+ faultInLogger();
+ useLog4jOrSimple(msg, m_trace);
}
public static void test(Object msg) {
- log.debug("TEST:" + msg);
+ faultInLogger();
+ useLog4jOrSimple("TEST:"+msg, m_debug);
}
public static void logMemoryUsage(){
- log.logMemoryUsage();
+ faultInLogger();
+ MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
+ useLog4jOrSimple("\tHeap: " + (memoryBean.getHeapMemoryUsage().getUsed() / 1024 / 1024f) + "MB / " + (memoryBean.getHeapMemoryUsage().getCommitted() / 1024 / 1024f) + "MB / " + (memoryBean.getHeapMemoryUsage().getMax() / 1024 / 1024f) + "MB",m_info);
+ useLog4jOrSimple("\tNon: " + (memoryBean.getNonHeapMemoryUsage().getUsed() / 1024 / 1024f) + "MB / " + (memoryBean.getNonHeapMemoryUsage().getCommitted() / 1024 / 1024f) + "MB / " + (memoryBean.getNonHeapMemoryUsage().getMax() / 1024 / 1024f) + "MB", m_info);
}
+
+ public static void logSpaceEvent(SpaceEvent event) {
+ faultInLogger();
+ if (!haveLog4J) {
+ return;//don't bother unless we have fancy logging capabilities
+ }
+ String n=event.getName();
+ for (int i=0; i<ignoredSpaceEventNames.length;++i) {
+ //reduce size of logs a bit
+ if (n.equals(ignoredSpaceEventNames[i])) {
+ return;
+ }
+ }
+ useLog4jOrSimple(event.toString(), reallyTheSpaceLogger, null, m_info);
+ }
+ public static void logSpaceEvent(String msg) {
+ faultInLogger();
+ if (!haveLog4J) {
+ return;
+ }
+ useLog4jOrSimple(msg, reallyTheSpaceLogger, null, m_info);
+ }
}
Modified: maven/trunk/ogoglio-common/src/test/java/com/ogoglio/loadtest/MultiuserTests.java
===================================================================
--- maven/trunk/ogoglio-common/src/test/java/com/ogoglio/loadtest/MultiuserTests.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-common/src/test/java/com/ogoglio/loadtest/MultiuserTests.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -65,7 +65,7 @@
for (int i = 0; i < numRobots; i++) {
startPosition.setTranslation(new Vector3d(0, 0, -50));
tests.addRobot(startPosition, true);
- Log.test("Added robot " + (i + 1) + " of " + numRobots);
+ Log.info("Added robot " + (i + 1) + " of " + numRobots);
Thread.sleep(1000);
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SpaceSimulator.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -188,7 +188,7 @@
}
public void startSim() {
- simThread.setName("space-sim-thread-"+Thread.currentThread().getId());
+ simThread.setName("space-"+space.getSpaceID());
//Log.info("Starting up thread: "+simThread.getName());
simThread.start();
}
@@ -201,14 +201,16 @@
BlockingQueue queue = new BlockingQueue();
public SimThread() {
- super("SimThread");
+ super();
setDaemon(true);
}
public void run() {
+ Log.logSpaceEvent("SPACE START:"+space.getDisplayName()+","+space.getSpaceID());
while (!cleaned) {
try {
SpaceEvent event = (SpaceEvent) queue.dequeue();
+ Log.logSpaceEvent(event);
if (cleaned) {
return;
}
@@ -428,6 +430,8 @@
Log.error("Error handling space event", e);
}
}
+ Log.logSpaceEvent("SPACE STOP:"+space.getDisplayName()+","+space.getSpaceID());
+
}
private String markdownChatMessage(String chatMessage) {
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java 2007-11-12 17:37:16 UTC (rev 572)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/MessageProxy.java 2007-11-13 00:39:09 UTC (rev 573)
@@ -16,6 +16,7 @@
import java.io.IOException;
import java.net.URI;
+import java.net.URISyntaxException;
import java.util.Timer;
import java.util.TimerTask;
@@ -57,7 +58,7 @@
private NetworkChannelServer channelServer = null;
private SessionFactory sessionFactory = null;
-
+
private SimChannelHandler simMessageHandler = new SimChannelHandler();
private ClientMessageHandler clientMessageHandler = new ClientMessageHandler();
@@ -68,13 +69,9 @@
private static final long HEARTBEAT_INTERVAL_TO_SIM = 5000;
- //needed because we are CLIENT of the sim servlet and need to know how to reach it
- private WebAPIDescriptor descriptor;
-
public MessageProxy(SessionFactory sessionFactory, WebAPIDescriptor descriptor) throws IOException {
ArgumentUtils.assertNotNull(sessionFactory);
this.sessionFactory = sessionFactory;
- this.descriptor = descriptor;
channelServer = new NetworkChannelServer(clientMessageHandler, descriptor.getCometProxyURI(), true, this);
Log.info("Started Message Proxy on port " + channelServer.getLocator().getPort() + " with target of " + descriptor.getCometSimURI());
outgoingHeartbeatTimer.schedule(new OutgoingHeartbeatTask(), 5000, 60000);
@@ -203,7 +200,7 @@
sendMessageToSpace(locatorAuth.uri, locatorAuth.spaceID, simMessage);
return;
} else if (request.getPayload() instanceof PayloadFactory.LogoutPayload) {
- request.getPayload(); //XXX is this necessary?
+ request.getPayload(); //XXX is this necessary? is there a side effect??
logout(request.getOrigin());
return;
} else if (request.getPayload() instanceof PayloadFactory.SpaceEventPayload) {
@@ -321,13 +318,16 @@
simChannel = (TCPChannel) simChannels.getForward(uri);
if (simChannel == null) {
try {
- /*Object selector=AsyncProtoFactory.getDefaultInfo().getSimSpecificSelector();
- AsyncProto proto=AsyncProtoFactory.getDefaultClient(uri.getHost(), selector);*/
- AsyncProto proto = AsyncProtoFactory.getDefaultClient(descriptor, false);
+ //the reason we don't use the service API descriptor here is that in the case
+ //of splitting across multiple machines (sims on different machine from the
+ //webapp) the sim isn't actually part of the service URI space, it has it's
+ //own location, communicated out of band (via the DB)
+ URI cometURI=representativeURIToCometUR(uri);
+ AsyncProto proto=AsyncProtoFactory.getDefaultClient(cometURI);
simChannel = new TCPChannel(proto, simMessageHandler, false, simMessageHandler, true, "sim-client");
} catch (IOException e) {
e.printStackTrace();
- throw new NoSuchDestinationException("Could not open a channel to " + uri);
+ throw new NoSuchDestinationException("Could not open a channel to " + uri + "(original exception was:"+e.getMessage());
}
simChannels.put(uri, simChannel);
}
@@ -336,6 +336,21 @@
simChannel.sendMessage(message);
}
+ private URI representativeURIToCometUR(URI representativeURI) throws IOException {
+ String cometPath="/og/comet/sim";
+
+ if (!representativeURI.getPath().endsWith("/og/sim/")) {
+ throw new IOException("Can't understand the path well enough to convert this to a comet URI:"+representativeURI.getPath());
+ }
+ try {
+ URI result=new URI(representativeURI.getScheme(),null,representativeURI.getHost(),representativeURI.getPort(),cometPath,null,null);
+ Log.warn("Somewhat dodgy: Converting the URI "+representativeURI+" to "+result+" for comet!");
+ return result;
+ } catch (URISyntaxException e) {
+ throw new IOException("Our converted URI was not well formed! Started with:"+representativeURI);
+ }
+ }
+
public void channelAdded(TCPChannel channel) {
}
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-11-13 00:44:28
|
Revision: 574
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=574&view=rev
Author: iansmith
Date: 2007-11-12 16:44:33 -0800 (Mon, 12 Nov 2007)
Log Message:
-----------
Removed ancient log4j.properties files.
This should be done in one place your $CATALINA_HOME/lib/log4j.properties file.
Modified Paths:
--------------
maven/trunk/ogoglio-server/.classpath
Removed Paths:
-------------
maven/trunk/ogoglio-integration-test/src/test/resources/log4j.properties
maven/trunk/ogoglio-server/src/main/resources/log4j/
Deleted: maven/trunk/ogoglio-integration-test/src/test/resources/log4j.properties
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/resources/log4j.properties 2007-11-13 00:39:09 UTC (rev 573)
+++ maven/trunk/ogoglio-integration-test/src/test/resources/log4j.properties 2007-11-13 00:44:33 UTC (rev 574)
@@ -1,49 +0,0 @@
-### direct log messages to stdout ###
-log4j.appender.stdout=org.apache.log4j.ConsoleAppender
-log4j.appender.stdout.Target=System.out
-log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
-log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
-### direct messages to file hibernate.log ###
-#log4j.appender.file=org.apache.log4j.FileAppender
-#log4j.appender.file.File=hibernate.log
-#log4j.appender.file.layout=org.apache.log4j.PatternLayout
-#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
-
-### set log levels - for more verbose logging change 'info' to 'debug' ###
-
-log4j.rootLogger=warn, stdout
-
-log4j.logger.com.ogoglio=debug
-
-log4j.logger.org.hibernate=error
-#log4j.logger.org.hibernate=debug
-
-### log HQL query parser activity
-#log4j.logger.org.hibernate.hql.ast.AST=debug
-
-### log just the SQL
-#log4j.logger.org.hibernate.SQL=debug
-
-### log JDBC bind parameters ###
-#log4j.logger.org.hibernate.type=info
-#log4j.logger.org.hibernate.type=debug
-
-### log schema export/update ###
-#log4j.logger.org.hibernate.tool.hbm2ddl=info
-
-### log HQL parse trees
-#log4j.logger.org.hibernate.hql=debug
-
-### log cache activity ###
-#log4j.logger.org.hibernate.cache=debug
-
-### log transaction activity
-#log4j.logger.org.hibernate.transaction=debug
-
-### log JDBC resource acquisition
-#log4j.logger.org.hibernate.jdbc=debug
-
-### enable the following line if you want to track down connection ###
-### leakages when using DriverManagerConnectionProvider ###
-#log4j.logger.org.hibernate.connection.DriverManagerConnectionProvider=trace
Modified: maven/trunk/ogoglio-server/.classpath
===================================================================
--- maven/trunk/ogoglio-server/.classpath 2007-11-13 00:39:09 UTC (rev 573)
+++ maven/trunk/ogoglio-server/.classpath 2007-11-13 00:44:33 UTC (rev 574)
@@ -4,7 +4,6 @@
<classpathentry excluding="**" kind="src" output="src/main/resources/siteTemplates" path="src/main/resources/siteTemplates"/>
<classpathentry kind="src" path="src/test/java"/>
<classpathentry excluding="**" kind="src" output="src/main/resources/hibernate" path="src/main/resources/hibernate"/>
- <classpathentry excluding="**" kind="src" output="src/main/resources/log4j" path="src/main/resources/log4j"/>
<classpathentry excluding="**" kind="src" output="src/test/resources" path="src/test/resources"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="con" path="org.maven.ide.eclipse.MAVEN2_CLASSPATH_CONTAINER">
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|
|
From: <ian...@us...> - 2007-11-15 02:59:30
|
Revision: 582
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=582&view=rev
Author: iansmith
Date: 2007-11-14 18:59:34 -0800 (Wed, 14 Nov 2007)
Log Message:
-----------
Added some support for getting status information from a server running on linux. This is installed in /og/status and /og/status/all to get information about a cluster. You can use the parameter "?format=xml" or "?format=human" to control which output you want.
The servlet remembers the last ten status updates and shows you these in the results.
It tries to be smart about "clusters of one machine."
Modified Paths:
--------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/ServiceDocument.java
maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/MediaService.java
maven/trunk/ogoglio-server/src/main/webapp/WEB-INF/web.xml
Added Paths:
-----------
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/StatusServlet.java
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/ServiceDocument.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/ServiceDocument.java 2007-11-14 21:17:12 UTC (rev 581)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/xml/ServiceDocument.java 2007-11-15 02:59:34 UTC (rev 582)
@@ -1,5 +1,8 @@
package com.ogoglio.xml;
+import java.lang.management.ManagementFactory;
+import java.lang.management.MemoryMXBean;
+
import nanoxml.XMLElement;
public class ServiceDocument {
@@ -16,8 +19,18 @@
data = new XMLElement(NAME);
data.setAttribute(USER_COUNT, userCount);
data.setAttribute(SIM_COUNT, simCount);
+
+ data.addChild(getMemoryChild());
}
+ public XMLElement getMemoryChild() {
+ MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
+ XMLElement result= new XMLElement("memory");
+ result.setAttribute("heapMemoryUsage", memoryBean.getHeapMemoryUsage());
+ result.setAttribute("nonHeapMemoryUsage", memoryBean.getNonHeapMemoryUsage());
+ return result;
+ }
+
public ServiceDocument(XMLElement data) {
if (!NAME.equals(data.getName())) {
throw new IllegalArgumentException("data is not named " + NAME + ": " + data);
Modified: maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java
===================================================================
--- maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-11-14 21:17:12 UTC (rev 581)
+++ maven/trunk/ogoglio-integration-test/src/test/java/com/ogoglio/client/test/ClientTest.java 2007-11-15 02:59:34 UTC (rev 582)
@@ -21,6 +21,7 @@
import java.net.Socket;
import java.net.URI;
import java.net.URISyntaxException;
+import java.net.URL;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
@@ -50,6 +51,7 @@
import com.ogoglio.client.model.Thing;
import com.ogoglio.client.model.User;
import com.ogoglio.util.Log;
+import com.ogoglio.util.OgoglioSpecBase;
import com.ogoglio.util.PropStorage;
import com.ogoglio.util.StreamUtils;
import com.ogoglio.util.UIConstants;
@@ -70,6 +72,7 @@
import com.ogoglio.xml.TemplateSupportFileDocument;
import com.ogoglio.xml.ThingDocument;
import com.ogoglio.xml.UserDocument;
+import com.sun.corba.se.impl.javax.rmi.CORBA.Util;
import com.sun.org.apache.xalan.internal.xsltc.compiler.Template;
public class ClientTest extends TestCase {
@@ -968,6 +971,50 @@
return newTemplateDoc;
}
+ private XMLElement getStatusXML() throws IOException, URISyntaxException {
+ InputStream s=new URI(serviceURI1.toString()+"status?format=xml").toURL().openConnection().getInputStream();
+ XMLElement result=XMLElement.parseElementFromString(StreamUtils.readInput(s));
+ s.close();
+ return result;
+ }
+
+ public void testStatus() throws IOException, URISyntaxException {
+ try {
+
+ InputStream forEffect=new URI(serviceURI1.toString()+"status?clear=true").toURL().openConnection().getInputStream();
+ forEffect.close();
+
+ //it's pretty hard to know what *should* be in the status message unless you dummy
+ //up a bunch of stuff in /proc ....this test, thus, is very weak
+
+ checkStatusReportChildren(1);
+
+ getStatusXML();
+ getStatusXML();
+
+ checkStatusReportChildren(4);
+
+ forEffect=new URI(serviceURI1.toString()+"status?clear=true").toURL().openConnection().getInputStream();
+ forEffect.close();
+
+ checkStatusReportChildren(1);//make sure clear works and wasn't lucky above
+
+
+ } catch (IOException e) {
+ if (e.getMessage().startsWith("Server returned HTTP response code: 412")) {
+ Log.info("Ignoring response code 412 for status URL. You probably aren't on linux.");
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ private XMLElement checkStatusReportChildren(int n) throws IOException, URISyntaxException {
+ XMLElement element=getStatusXML();
+ assertEquals(element.getName(),"statusreports");
+ assertEquals(n,element.getChildren().size());
+ return element;
+ }
private void assertStreamsEqual(InputStream input1, InputStream input2) throws IOException {
if(input1 == null || input2 == null){
fail("Not equal, null inputs: " + input1 + ", " + input2);
@@ -1181,5 +1228,4 @@
}
}
-
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/MediaService.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/MediaService.java 2007-11-14 21:17:12 UTC (rev 581)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/media/MediaService.java 2007-11-15 02:59:34 UTC (rev 582)
@@ -39,6 +39,7 @@
private static final String BODY_TEXTURE_PREFIX = "bodyTexture-";
private MediaStore store = null;
+ private URI mediaURI;
public MediaService(URI mediaURI) throws IOException {
ArgumentUtils.assertNotNull(mediaURI);
@@ -50,8 +51,12 @@
} else {
throw new IllegalStateException("Could not create a store for " + mediaURI + " with scheme " + mediaURI.getScheme());
}
+ this.mediaURI=mediaURI;
}
+ public URI getMediaURI() {
+ return mediaURI;
+ }
public static String getTemplateScriptName(long templateID) {
return MediaService.TEMPLATE_SCRIPT_PREFIX + templateID + MediaService.TEMPLATE_SCRIPT_SUFFIX;
}
Added: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/StatusServlet.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/StatusServlet.java (rev 0)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/StatusServlet.java 2007-11-15 02:59:34 UTC (rev 582)
@@ -0,0 +1,615 @@
+package com.ogoglio.site;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.net.URI;
+import java.net.URL;
+import java.sql.Time;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import javax.servlet.ServletConfig;
+import javax.servlet.ServletException;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+
+import nanoxml.XMLElement;
+
+import com.ogoglio.appdev.persist.PersistException;
+import com.ogoglio.appdev.servlet.SiteResource;
+import com.ogoglio.persist.SimPersistTasks;
+import com.ogoglio.persist.SimRecord;
+import com.ogoglio.util.Log;
+import com.ogoglio.util.NetworkUtils;
+import com.ogoglio.util.StreamUtils;
+
+public class StatusServlet extends OgoglioServletBase {
+
+ private List recentChecks = new ArrayList();
+
+ private static final int MAX_RECENT_CHECKS = 10;
+
+ public SiteResource createBaseResource(ServletConfig servletConfig) {
+ return new StatusResource();
+ }
+
+ private class FSData {
+ public String root;
+
+ public double size;
+
+ public double used;
+
+ public double available;
+
+ public double percentAvailable() {
+ return available / size * 100.0;
+ }
+
+ public double percentUsed() {
+ return used / size * 100.0;
+ }
+
+ public FSData deepCopy() {
+ FSData result = new FSData();
+ result.size = size;
+ result.root = root;
+ result.used = used;
+ result.available = available;
+ return result;
+ }
+ }
+
+ private class StatusData {
+ public long timestamp;
+
+ public double load_1min;
+
+ public double load_5min;
+
+ public double load_15min;
+
+ public int totalMemory_kb;
+
+ public int freeMemory_kb;
+
+ public double memPercentAvail;
+
+ public FSData[] fs;
+
+ public double netIn_mb;
+
+ public double netOut_mb;
+
+ public int userCount;
+
+ public int simCount;
+
+ public StatusData deepCopy() {
+ StatusData result = new StatusData();
+ result.timestamp = timestamp;
+ result.load_1min = load_1min;
+ result.load_5min = load_5min;
+ result.load_15min = load_15min;
+ result.totalMemory_kb = totalMemory_kb;
+ result.freeMemory_kb = freeMemory_kb;
+ result.memPercentAvail = memPercentAvail;
+ result.fs = new FSData[fs.length];
+ result.netIn_mb = netIn_mb;
+ result.netOut_mb = netOut_mb;
+ result.userCount = userCount;
+ result.simCount = simCount;
+ for (int i = 0; i < fs.length; ++i) {
+ result.fs[i] = fs[i].deepCopy();
+ }
+ return result;
+ }
+ }
+
+ private String frontDoorGetText(String uri,String suffix) throws IOException {
+ InputStream s = new URL(uri + suffix).openConnection().getInputStream();
+ String result = StreamUtils.readInput(s);
+ s.close();
+ return result;
+ }
+
+ private XMLElement frontDoorGetXML(String uri,String suffix) throws IOException {
+ InputStream s = new URL(uri + suffix).openConnection().getInputStream();
+ XMLElement result = XMLElement.parseElementFromString(StreamUtils.readInput(s));
+ s.close();
+ return result;
+ }
+
+ private boolean shouldBeHumanReadable(HttpServletRequest request) {
+ String format = request.getParameter("format");
+ if ((format == null) || (format.equalsIgnoreCase("human"))) {
+ return true;
+ }
+ return false;
+ }
+
+ private class StatusResource extends SiteResource {
+
+ private static final String NETWORK_OUT_MB = "out";
+
+ private static final String NETWORK_IN_MB = "in";
+
+ public static final String NETWORK = "network";
+
+ public static final String AVAILABLE_FS_GB = "available";
+
+ public static final String PERCENT_USED_FS = "percentUsed";
+
+ public static final String USED_FS_GB = "used";
+
+ public static final String SIZE_FS_GB = "size";
+
+ public static final String ROOT_OF_FS = "root";
+
+ public static final String FILESYSTEM = "filesystem";
+
+ public static final String FILESYSTEMS = "filesystems";
+
+ public static final String FREE_MEM_KB = "free";
+
+ public static final String TOTAL_MEM_KB = "total";
+
+ public static final String MEMORY = "memory";
+
+ public static final String MIN_15 = "min15";
+
+ public static final String MIN_5 = "min5";
+
+ public static final String MIN_1 = "min1";
+
+ public static final String LOADAVERAGE = "loadaverage";
+
+ public static final String STATUSREPORT = "statusreport";
+
+ public static final String STATUSREPORTS = "statusreports";
+
+ private static final String PERCENT_AVAILABLE_MEM = "available";
+
+ public StatusResource() {
+ super("status");
+ addSubResource(new AllStatusResource());
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
+ if (!haveSlashProc()) {
+ response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
+ return;
+ }
+
+ //maybe trying to clear out the history?
+ if (request.getParameter("clear") != null) {
+ synchronized (recentChecks) {
+ recentChecks.clear();
+ }
+ response.setStatus(HttpServletResponse.SC_OK);
+ return;
+ }
+
+ try {
+ StatusData data = computeCurrentStatus();
+ List copy = new ArrayList();
+ addCurrentStatusToListAndCopy(data, copy);
+
+ StringBuffer buffer = new StringBuffer();
+ String type;
+ if (shouldBeHumanReadable(request)) {
+ formatForHuman(buffer, copy);
+ type = "text/plain";
+ } else {
+ formatXML(buffer, copy);
+ type = "text/xml";
+ }
+ sendStringResponse(buffer.toString(), type, response);
+ response.setStatus(HttpServletResponse.SC_OK);
+ } catch (IOException e) {
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ Log.error("Trying to read the load average!", e);
+ }
+
+ }
+
+ private void addCurrentStatusToListAndCopy(StatusData data, List copy) {
+ synchronized (recentChecks) {
+ if (recentChecks.size() == MAX_RECENT_CHECKS) {
+ recentChecks.remove(0);
+ }
+ recentChecks.add(data);
+ for (int i = 0; i < recentChecks.size(); ++i) {
+ copy.add(((StatusData) recentChecks.get(i)).deepCopy());
+ }
+ }
+ }
+
+ private StatusData computeCurrentStatus() throws IOException {
+ StatusData data = new StatusData();
+ data.timestamp = System.currentTimeMillis();
+
+ getLoadAvg(data);
+ getMemoryInfo(data);
+ getDiskAvailable(data);
+ getNetworkInfo(data);
+ addSpaceInfo(data);
+ return data;
+ }
+
+ private void addSpaceInfo(StatusData data) throws IOException {
+ XMLElement space = frontDoorGetXML(getBaseUrl(),"space");
+ data.simCount = space.getIntAttribute("simcount");
+ data.userCount = space.getIntAttribute("usercount");
+
+ }
+
+ private void formatXML(StringBuffer buffer, List copy) {
+ XMLElement root = new XMLElement();
+ root.setName(STATUSREPORTS);
+ for (int i = copy.size() - 1; i >= 0; --i) {
+ XMLElement status = new XMLElement();
+ status.setName(STATUSREPORT);
+ StatusData sd = (StatusData) copy.get(i);
+ status.setAttribute("time", sd.timestamp);
+
+ XMLElement load = new XMLElement();
+ load.setName(LOADAVERAGE);
+ load.setAttribute(MIN_1, sd.load_1min);
+ load.setAttribute(MIN_5, sd.load_5min);
+ load.setAttribute(MIN_15, sd.load_15min);
+ status.addChild(load);
+
+ XMLElement memory = new XMLElement();
+ memory.setName(MEMORY);
+ memory.setAttribute(TOTAL_MEM_KB, sd.totalMemory_kb);
+ memory.setAttribute(FREE_MEM_KB, sd.freeMemory_kb);
+ memory.setAttribute(PERCENT_AVAILABLE_MEM, sd.memPercentAvail);
+ status.addChild(memory);
+
+ XMLElement filesystems = new XMLElement();
+ filesystems.setName(FILESYSTEMS);
+ for (int j = 0; j < sd.fs.length; ++j) {
+ XMLElement fs = new XMLElement();
+ fs.setName(FILESYSTEM);
+ fs.setAttribute(ROOT_OF_FS, sd.fs[j].root);
+ fs.setAttribute(SIZE_FS_GB, sd.fs[j].size);
+ fs.setAttribute(AVAILABLE_FS_GB, sd.fs[j].available);
+ fs.setAttribute(USED_FS_GB, sd.fs[j].used);
+ fs.setAttribute(PERCENT_USED_FS, sd.fs[j].percentUsed());
+ filesystems.addChild(fs);
+ }
+ status.addChild(filesystems);
+
+ XMLElement network = new XMLElement();
+ network.setName(NETWORK);
+ network.setAttribute(NETWORK_IN_MB, sd.netIn_mb);
+ network.setAttribute(NETWORK_OUT_MB, sd.netIn_mb);
+ status.addChild(network);
+
+ root.addChild(status);
+ }
+ buffer.append(root.toString());
+ }
+
+ private void formatForHuman(StringBuffer buffer, List copy) {
+ for (int i = copy.size() - 1; i >= 0; --i) {
+ StatusData sd = (StatusData) copy.get(i);
+ buffer.append("Time:" + new Time(sd.timestamp).toString() + "\n");
+ buffer.append("load average 1 min:" + sd.load_1min + "\n");
+ buffer.append("load average 5 min:" + sd.load_5min + "\n");
+ buffer.append("load average 15 min:" + sd.load_15min + "\n");
+
+ String per = "" + sd.memPercentAvail;
+
+ buffer.append("Total memory (kB) :" + sd.totalMemory_kb + "\n");
+ buffer.append("Free memory (kB) :" + sd.freeMemory_kb + "\n");
+ buffer.append("Available :" + per.substring(0, 5) + "% (approximately free + cache)\n");
+ buffer.append("Network in (mB) :" + sd.netIn_mb + "\n");
+ buffer.append("Network out (mB) :" + sd.netOut_mb + "\n");
+ if (i > 0) {
+ StatusData prev = (StatusData) copy.get(i - 1);
+ double inDiff = sd.netIn_mb - prev.netIn_mb;
+ double outDiff = sd.netOut_mb - prev.netOut_mb;
+ double timeDiff = (sd.timestamp - prev.timestamp) / 1000.0;
+ double inAvg = inDiff / timeDiff;
+ double outAvg = outDiff / timeDiff;
+ if (inAvg < 0.001) {
+ inAvg = 0.0;
+ }
+ if (outAvg < 0.001) {
+ outAvg = 0.0;
+ }
+ buffer.append("Network in mB/s :" + inAvg + "\n");
+ buffer.append("Network out mB/s :" + outAvg + "\n");
+ }
+ int width = "load average 1 min".length();
+ for (int j = 0; j < sd.fs.length; ++j) {
+ double used = sd.fs[j].percentUsed();
+ if (used < 0.1) {
+ used = 0.0;
+ }
+ per = "" + used;
+ if (per.length() > 5) {
+ per = per.substring(0, 5);
+ }
+ if (sd.fs[j].root.length() < width) {
+ buffer.append(sd.fs[j].root);
+ for (int k = sd.fs[j].root.length(); k < width; ++k) {
+ buffer.append(" ");
+ }
+ buffer.append(":" + per + "% full\n");
+ } else {
+ buffer.append(sd.fs[j].root + ":" + per + "% full\n");
+ }
+ }
+ buffer.append("User count :" + sd.userCount + "\n");
+ buffer.append("Sim count :" + sd.simCount + "\n");
+ buffer.append("-----------------------------------------------\n");
+ }
+
+ }
+
+ private void getDiskAvailable(StatusData data) throws IOException {
+ String[] cmdarray = { "/bin/df" };
+ Process df = Runtime.getRuntime().exec(cmdarray);
+ InputStream is = df.getInputStream();
+ InputStreamReader reader = new InputStreamReader(is);
+ BufferedReader dfoutput = new BufferedReader(reader);
+ dfoutput.readLine(); //ignore first line
+ String line;
+ List all = new ArrayList();
+ do {
+ line = dfoutput.readLine();
+ if (line == null)
+ continue;
+
+ FSData fsData = new FSData();
+ StringTokenizer tokenizer = new StringTokenizer(line);
+ tokenizer.nextToken(); //ignore unix mount name
+ fsData.size = toFloatGigs(tokenizer.nextToken());
+ fsData.used = toFloatGigs(tokenizer.nextToken());
+ fsData.available = toFloatGigs(tokenizer.nextToken());
+ tokenizer.nextToken(); //ignore percent, don't need it
+ fsData.root = tokenizer.nextToken();
+ all.add(fsData);
+ } while (line != null);
+
+ dfoutput.close();
+
+ data.fs = new FSData[all.size()];
+ for (int i = 0; i < all.size(); ++i) {
+ data.fs[i] = (FSData) all.get(i);
+ }
+ }
+
+ private double toFloatGigs(String token) throws IOException {
+ try {
+ double result = Double.parseDouble(token);
+ return result / 1000000.0; //convert to gigs from k
+ } catch (NumberFormatException e) {
+ throw new IOException("Unable to parse result of df:" + token);
+ }
+ }
+
+ private void getLoadAvg(StatusData data) throws IOException {
+ File load = new File("/proc/loadavg");
+ BufferedReader reader = new BufferedReader(new FileReader(load));
+ String line = reader.readLine();
+ StringTokenizer tokenizer = new StringTokenizer(line, " ");
+ String oneMin = tokenizer.nextToken();
+ String fiveMin = tokenizer.nextToken();
+ String fifteenMin = tokenizer.nextToken();
+ try {
+ data.load_1min = Double.parseDouble(oneMin);
+ data.load_5min = Double.parseDouble(fiveMin);
+ data.load_15min = Double.parseDouble(fifteenMin);
+ reader.close();
+ } catch (NumberFormatException e) {
+ throw new IOException("Unable to understand the format of the /proc/loadavg file:" + e.getMessage());
+ }
+ }
+
+ private void getNetworkInfo(StatusData data) throws IOException {
+ File load = new File("/proc/net/dev");
+ BufferedReader reader = new BufferedReader(new FileReader(load));
+ reader.readLine();
+ reader.readLine();//drop first two lines, they are headings
+ String line;
+ StringTokenizer tokenizer;
+ do {
+ line = reader.readLine();
+ tokenizer = new StringTokenizer(line, " :");
+ } while (!tokenizer.nextToken().startsWith("eth"));
+ String rcvBytes = tokenizer.nextToken();
+ for (int i = 0; i < 7; ++i) {
+ tokenizer.nextToken();//ignore fields we don't need
+ }
+ String sentBytes = tokenizer.nextToken();
+ try {
+ data.netIn_mb = Double.parseDouble(rcvBytes) / 1000000.0;
+ data.netOut_mb = Double.parseDouble(sentBytes) / 1000000.0;
+ } catch (NumberFormatException e) {
+ throw new IOException("Can't understand format of network information!" + line);
+ }
+ }
+
+ private void getMemoryInfo(StatusData data) throws IOException {
+
+ File load = new File("/proc/meminfo");
+ BufferedReader reader = new BufferedReader(new FileReader(load));
+ String memTotal = reader.readLine();
+ String memFree = reader.readLine();
+ reader.readLine(); //buffers
+ String cached = reader.readLine();
+ reader.close();
+
+ try {
+ int total = Integer.parseInt(parseMemLine(memTotal, "MemTotal:"));
+ int free = Integer.parseInt(parseMemLine(memFree, "MemFree:"));
+ int cache = Integer.parseInt(parseMemLine(cached, "Cached:"));
+ int totalAvail = free + cache;
+ data.memPercentAvail = ((double) totalAvail) / ((double) total) * 100.0;
+ data.totalMemory_kb = total;
+ data.freeMemory_kb = free;
+
+ } catch (NumberFormatException e) {
+ throw new IOException("Unable to understand the format of the /proc/meminfo file:" + e.getMessage());
+ }
+ }
+
+ private String parseMemLine(String line, String expectedFirst) throws IOException {
+ StringTokenizer tokenizer = new StringTokenizer(line, " ");
+ String first = tokenizer.nextToken();
+ String second = tokenizer.nextToken();
+ if (!expectedFirst.equals(first)) {
+ throw new IOException("Whoa! Line wasn't what we expected from /proc/meminfo! Expected:" + expectedFirst + " but was " + first);
+ }
+ return second;
+ }
+
+ public boolean haveSlashProc() {
+ File load = new File("/proc/loadavg");
+ if (!load.exists()) {
+ return false;
+ }
+ if (!load.canRead()) {
+ return false;
+ }
+ return true;
+ }
+
+ }
+
+ private class AllStatusResource extends SiteResource {
+ private static final String STATUS_HUMAN = "status?format=human";
+
+ private static final String STATUS_XML = "status?format=xml";
+
+ public AllStatusResource() {
+ super("all");
+ }
+
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements) throws ServletException, IOException {
+ StringBuffer buffer = new StringBuffer();
+ String type;
+ if (shouldBeHumanReadable(request)) {
+ formatForHuman(buffer);
+ type = "text/plain";
+ } else {
+ try {
+ formatXML(buffer);
+ } catch (PersistException e) {
+ Log.error("Unable to do a status check!", e);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ } catch (IOException e) {
+ Log.error("Unable to do a status check!", e);
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+ return;
+ }
+ type = "text/xml";
+ }
+ sendStringResponse(buffer.toString(), type, response);
+ response.setStatus(HttpServletResponse.SC_OK);
+ }
+
+ private void formatXML(StringBuffer buffer) throws IOException, PersistException {
+ XMLElement cluster = new XMLElement();
+ cluster.setName("cluster");
+
+ XMLElement webapp = new XMLElement();
+ webapp.setName("webapp");
+ webapp.setAttribute("uri", getBaseUrl());
+ XMLElement statusReports = frontDoorGetXML(getBaseUrl(),STATUS_XML);
+ webapp.addChild(statusReports);
+ cluster.addChild(webapp);
+ SimRecord[] simRecord = SimPersistTasks.findSims(getSessionFactory());
+ for (int i = 0; i < simRecord.length; ++i) {
+ SimRecord sim = simRecord[i];
+ try {
+ XMLElement s=new XMLElement();
+ s.setName("sim");
+ s.setAttribute("uri", sim.getSimURI());
+ if (isOnLocalhost(sim)) {
+ s.setAttribute("ignored", true);
+ } else {
+ statusReports = frontDoorGetXML(dodgyConversionOfSimURI(sim.getSimURI().toString()),STATUS_XML);
+ s.addChild(statusReports);
+ }
+ cluster.addChild(s);
+ } catch (IOException e) {
+ Log.info("Unable to get XML from sim URI:"+sim.getSimURI(),e);
+ }
+ }
+ String mediaURI = getMediaService().getMediaURI().toString();
+ XMLElement media=new XMLElement();
+ media.setName("mediaserver");
+ media.setAttribute("uri", mediaURI);
+ if (!mediaURI.startsWith("file:")) {
+ statusReports = frontDoorGetXML(mediaURI,STATUS_XML);
+ media.addChild(statusReports);
+ } else {
+ media.setAttribute("ignored", true);
+ }
+ cluster.addChild(media);
+ buffer.append(cluster.toString());
+ }
+
+ private boolean isOnLocalhost(SimRecord sim) {
+ return sim.getSimURI().toString().indexOf("127.0.0.1")!=-1;
+ }
+
+ private String dodgyConversionOfSimURI(String simURI) {
+ String result;
+ String standardSIMSuffix="/og/sim/";
+ if (!simURI.endsWith(standardSIMSuffix)) {
+ Log.error("Don't understand the sim URI we got, so we can't convert to a status URI:"+simURI);
+ return simURI; //not a great answer, but it'll cause IOExceptions elsewhere
+ }
+ result=simURI.subst...
[truncated message content] |
|
From: <ian...@us...> - 2007-11-19 19:44:08
|
Revision: 591
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=591&view=rev
Author: iansmith
Date: 2007-11-19 11:44:11 -0800 (Mon, 19 Nov 2007)
Log Message:
-----------
Added better debug info during shutdown, added a flush that may solve the problem of zombie avatars on EC2.
Added support for an "out of service" filter, but it's not enabled yet.
Modified Paths:
--------------
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java
maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java
maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java
Added Paths:
-----------
maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OutOfServiceFilter.java
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/client/SpaceClient.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -692,8 +692,11 @@
}
public void cleanup() {
+ Log.info("About to try to clean up the message channel object");
messageChannel.cleanup();
+ Log.info("Clearing all waiting messages becuse we are doing cleanup:"+waitingMessages.size());
waitingMessages.clear();
+ Log.info("Done cleaning up SpaceClient.Messenger");
}
public void heartbeat() throws IOException {
@@ -749,13 +752,18 @@
public void cleanup() {
cleanedUp = true;
try {
+ Log.info("In space client cleanup, about to send logout message:"+accountDoc.getUsername());
messageChannel.sendMessage(new Message(messageChannel.getLocalLocator(), messageChannel.getRemoteLocator(), space.getSpaceID(), new PayloadFactory.LogoutPayload(accountDoc.getUsername())));
+ Log.info("Success sending logout message");
} catch (Exception e) {
+ Log.error("Problem sending logout message:"+e.getMessage());
}
if (heartbeatTimer!=null) { //there is a race condition at startup that makes this necessary
heartbeatTimer.cancel();
}
+ Log.info("Cleaning up messenger in spaceclient...");
messenger.cleanup();
+ Log.info("Done with all spaceclient cleanup.");
}
public InputStream getPageContentStream(long thingID, long pageID) {
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/SenderQueue.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -47,8 +47,10 @@
public void cleanup() {
cleaned = true;
+ Log.info("About to shut down the client proto of the sender queue...");
clientProto.shutdown();
if (messageQueue != null) {
+ Log.info("About to close the message queue associated with the SenderQueue");
messageQueue.close();
}
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/TCPChannel.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -91,19 +91,23 @@
public void cleanup() {
//cleaned = true;
try {
+ Log.info("Cleaning up the TCP channel "+getLocalLocator());
if (readerThread!=null) {
+ Log.info("Reader thread about to be cleaned up...");
readerThread.cleanup();
}
} catch (Exception e) {
- Log.info("TCPChannel: Trying to cleanup to readerThread:"+(e.getClass().getName()),e);
+ Log.error("TCPChannel: Trying to cleanup to readerThread:"+(e.getClass().getName()),e);
}
try {
if (senderQueue!=null) {
+ Log.info("Sender queue about to be cleaned up...");
senderQueue.cleanup();
}
} catch (Exception e) {
- Log.info("TCPChannel: Trying to cleanup to senderQueue:"+(e.getClass().getName()),e);
+ Log.error("TCPChannel: Trying to cleanup to senderQueue:"+(e.getClass().getName()),e);
}
+ Log.info("About to tell listener that the TCP channel is now closed.");
listener.channelClosed(this);
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometClient.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -136,6 +136,5 @@
}
}
-
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/message/proto/CometProto.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -92,11 +92,24 @@
}
public void shutdown() {
- //this isn't really what we'd like to do, but we would need a bunch of machinery to know
- //if it was safe to call "close" b/c that would break the comet servlet which reuses
- //these objects... the client side probably *should* call close.
-
- //how should we synchronize this?
+ Log.info("Shutting down Comet Proto, flushing...");
+ if (writer!=null) {
+ try {
+ writer.flush();
+ } catch (IOException e) {
+ Log.error("Problem attempting to flush comet proto buffers:"+e.getMessage());
+ }
+ }
+ //again, a horrible modularity break: we *know* that needs chunking implies we are on the
+ //client side
+ if (needsChunking) {
+ try {
+ Log.info("Closing client-side connection to server since we are shutting down.");
+ writer.close();
+ } catch (IOException e) {
+ Log.error("Unable to close connection to server:"+e.getMessage());
+ }
+ }
input=null;
writer=null;
}
Modified: maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java
===================================================================
--- maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-common/src/main/java/com/ogoglio/util/Log.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -118,9 +118,11 @@
}
private static void useLog4jOrSimple(Object msg,Method method) {
+ faultInLogger();
useLog4jOrSimple(msg, null,method);
}
private static void useLog4jOrSimple(Object msg, Object throwable, Method method) {
+ faultInLogger();
useLog4jOrSimple(msg, reallyALogger, throwable,method);
}
@@ -150,6 +152,7 @@
}
public static void info(Object msg, Throwable t) {
+ faultInLogger();
useLog4jOrSimple(msg, t, m_info_throw);
}
@@ -164,6 +167,7 @@
}
public static void error(Object msg, Throwable t) {
+ faultInLogger();
useLog4jOrSimple(msg, t, m_error_throw);
}
Modified: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/sim/SimMessageHandler.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -85,7 +85,9 @@
} else if (message.getPayload() instanceof PayloadFactory.LoggedOutPayload) {
PayloadFactory.LoggedOutPayload payload = (PayloadFactory.LoggedOutPayload) message.getPayload();
+ Log.info("Client "+payload.getUsername()+" sent logged out!");
spaceSim.userLoggedOut(payload.getUsername());
+ Log.info("Sim finished telling the spacesim about the logout.");
} else {
Log.error("Sim received unknown payload in this message: " + message);
}
Added: maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OutOfServiceFilter.java
===================================================================
--- maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OutOfServiceFilter.java (rev 0)
+++ maven/trunk/ogoglio-server/src/main/java/com/ogoglio/site/OutOfServiceFilter.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -0,0 +1,32 @@
+package com.ogoglio.site;
+
+import java.io.IOException;
+
+import javax.servlet.Filter;
+import javax.servlet.FilterChain;
+import javax.servlet.FilterConfig;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+
+public class OutOfServiceFilter implements Filter {
+
+ private long lastTimeCheck=0L;
+ private static final long FREQUENCY_IN_MS= 15000;
+
+ public void destroy() {
+ }
+
+ public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
+ long now=System.currentTimeMillis();
+ long diff=now - lastTimeCheck;
+ if (diff<FREQUENCY_IN_MS) {
+ chain.doFilter(request, response);
+ }
+ lastTimeCheck=now;
+ }
+
+ public void init(FilterConfig config) throws ServletException {
+ }
+
+}
Modified: maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java
===================================================================
--- maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java 2007-11-19 14:41:43 UTC (rev 590)
+++ maven/trunk/ogoglio-viewer-applet/src/main/java/com/ogoglio/viewer/applet/ViewerApplet.java 2007-11-19 19:44:11 UTC (rev 591)
@@ -134,31 +134,26 @@
}
public void destroy() {
- System.out.println("Destroying " + this + ": " + renderer + ", " + spaceClient);
+ performAShutdown("DESTROY");
+ }
+
+ private void performAShutdown(String method) {
+
+ Log.info("Destroying " + this + ": " + renderer + ", " + spaceClient+" b/c "+method+" called on applet");
if (renderer != null) {
renderer.stopRenderer();
}
if (spaceClient != null) {
+ Log.info("Trynig to run spaceclient cleanup.");
spaceClient.cleanup();
}
System.gc();
Runtime.getRuntime().runFinalization();
- System.out.println("Destroyed " + this + ": " + renderer + ", " + spaceClient);
+ Log.info("Destroyed " + this + ": " + renderer + ", " + spaceClient);
}
public void stop() {
- System.out.println("Stopping " + this + ": " + renderer + ", " + spaceClient);
- if (renderer != null) {
- renderer.stopRenderer();
- }
- if (spaceClient != null) {
- spaceClient.cleanup();
- }
- renderer = null;
- spaceClient = null;
- System.gc();
- Runtime.getRuntime().runFinalization();
- System.out.println("Stopped " + this + ": " + renderer + ", " + spaceClient);
+ performAShutdown("STOP");
}
public boolean completedInitialLoad() {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|