|
From: <tre...@us...> - 2007-08-20 23:09:51
|
Revision: 248
http://ogoglio.svn.sourceforge.net/ogoglio/?rev=248&view=rev
Author: trevorolio
Date: 2007-08-20 16:09:52 -0700 (Mon, 20 Aug 2007)
Log Message:
-----------
Added a fetal email toolset, which means we need mail and activation jars in ${TOMCAT_HOME}/common/lib/ and JNDI entries for mail sessions.
Modified Paths:
--------------
spaces/trunk/.classpath
spaces/trunk/src/com/ogoglio/OgoglioTestSuite.java
spaces/trunk/src/com/ogoglio/persist/AccountPersistTasks.java
spaces/trunk/src/com/ogoglio/persist/Persist.hbm.xml
spaces/trunk/src/com/ogoglio/persist/PersistTests.java
spaces/trunk/src/com/ogoglio/site/AccountServlet.java
spaces/trunk/src/com/ogoglio/util/ArgumentUtils.java
spaces/trunk/src/com/ogoglio/util/StreamUtils.java
Added Paths:
-----------
spaces/trunk/common-lib/
spaces/trunk/common-lib/activation.jar
spaces/trunk/common-lib/mail.jar
spaces/trunk/src/com/ogoglio/mail/
spaces/trunk/src/com/ogoglio/mail/MailClient.java
spaces/trunk/src/com/ogoglio/mail/MailFormatter.java
spaces/trunk/src/com/ogoglio/mail/MailSendException.java
spaces/trunk/src/com/ogoglio/mail/MailTests.java
spaces/trunk/src/com/ogoglio/mail/TestTemplate1.txt
spaces/trunk/src/com/ogoglio/persist/PendingEmailValidationRecord.java
Modified: spaces/trunk/.classpath
===================================================================
--- spaces/trunk/.classpath 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/.classpath 2007-08-20 23:09:52 UTC (rev 248)
@@ -30,5 +30,7 @@
<classpathentry kind="lib" path="shared-lib/commons-fileupload-1.1.1.jar"/>
<classpathentry kind="lib" path="shared-lib/commons-codec-1.3.jar"/>
<classpathentry kind="lib" path="shared-lib/antlr-2.7.5H3.jar"/>
+ <classpathentry kind="var" path="TOMCAT_HOME/common/lib/mail.jar"/>
+ <classpathentry kind="var" path="TOMCAT_HOME/common/lib/activation.jar"/>
<classpathentry kind="output" path="war/WEB-INF/classes"/>
</classpath>
Added: spaces/trunk/common-lib/activation.jar
===================================================================
(Binary files differ)
Property changes on: spaces/trunk/common-lib/activation.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Added: spaces/trunk/common-lib/mail.jar
===================================================================
(Binary files differ)
Property changes on: spaces/trunk/common-lib/mail.jar
___________________________________________________________________
Name: svn:mime-type
+ application/octet-stream
Modified: spaces/trunk/src/com/ogoglio/OgoglioTestSuite.java
===================================================================
--- spaces/trunk/src/com/ogoglio/OgoglioTestSuite.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/OgoglioTestSuite.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -18,6 +18,7 @@
import com.ogoglio.client.ClientTests;
import com.ogoglio.client.WebAPITests;
+import com.ogoglio.mail.MailTests;
import com.ogoglio.persist.PersistTests;
import com.ogoglio.sim.script.ScriptTests;
import com.ogoglio.templatesync.TemplateSyncTestSuite;
@@ -34,6 +35,7 @@
suite.addTestSuite(ClientTests.class);
suite.addTestSuite(ScriptTests.class);
suite.addTest(TemplateSyncTestSuite.suite());
+ suite.addTestSuite(MailTests.class);
return suite;
}
Added: spaces/trunk/src/com/ogoglio/mail/MailClient.java
===================================================================
--- spaces/trunk/src/com/ogoglio/mail/MailClient.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/mail/MailClient.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,92 @@
+package com.ogoglio.mail;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+import javax.naming.Context;
+import javax.naming.InitialContext;
+import javax.naming.NamingException;
+
+import com.ogoglio.util.ArgumentUtils;
+
+public class MailClient {
+
+ private boolean writeToDisk = false;
+
+ private File outputDir = null;
+
+ /**
+ * Sends all mail to individual files in outputDir
+ */
+ public MailClient(File outputDir) {
+ ArgumentUtils.assertReadableDir(outputDir, true);
+ this.outputDir = outputDir;
+ writeToDisk = true;
+ }
+
+ /**
+ * Sends all mail via JNDI:java:comp/env session at mail/Session
+ */
+ public MailClient() {
+ writeToDisk = false;
+ }
+
+ public void sendEmail(String to, String from, String subject, String body) throws MailSendException {
+ try {
+ if (writeToDisk) {
+ sendToDisk(to, from, subject, body);
+ } else {
+ sendViaContextSession(to, from, subject, body);
+ }
+ } catch (NamingException e) {
+ throw new MailSendException(e);
+ } catch (AddressException e) {
+ throw new MailSendException(e);
+ } catch (MessagingException e) {
+ throw new MailSendException(e);
+ } catch (IOException e) {
+ throw new MailSendException(e);
+ }
+ }
+
+ private void sendToDisk(String to, String from, String subject, String body) throws IOException {
+ FileOutputStream output = new FileOutputStream(new File(outputDir, "Mail-Message-" + System.currentTimeMillis()));
+ output.write(("to: " + to + "\n").getBytes());
+ output.write(("from: " + from + "\n").getBytes());
+ output.write(("subject: " + subject + "\n").getBytes());
+ output.write(("\n").getBytes());
+ output.write(body.getBytes());
+ output.flush();
+ output.close();
+ }
+
+ private void sendViaContextSession(String to, String from, String subject, String body) throws NamingException, AddressException, MessagingException {
+ Context initCtx = new InitialContext();
+ Context envCtx = (Context) initCtx.lookup("java:comp/env");
+ Session session = (Session) envCtx.lookup("mail/Session");
+
+ Message message = new MimeMessage(session);
+ message.setFrom(new InternetAddress(from));
+ InternetAddress toAddress[] = new InternetAddress[1];
+ toAddress[0] = new InternetAddress(to);
+ message.setRecipients(Message.RecipientType.TO, toAddress);
+ message.setSubject(subject);
+ message.setContent(body, "text/plain");
+ Transport.send(message);
+ }
+
+ /**
+ * @return null if this client is using the JNDI mail session instead of writing to disk
+ */
+ public File getOutputDir() {
+ return outputDir;
+ }
+}
Added: spaces/trunk/src/com/ogoglio/mail/MailFormatter.java
===================================================================
--- spaces/trunk/src/com/ogoglio/mail/MailFormatter.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/mail/MailFormatter.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,29 @@
+package com.ogoglio.mail;
+
+import java.util.Map;
+import java.util.regex.Pattern;
+
+import com.ogoglio.util.ArgumentUtils;
+
+public class MailFormatter {
+
+ public String format(Map map, String template) {
+ ArgumentUtils.assertNotNull(map);
+ ArgumentUtils.assertNotEmpty(template);
+ return stupidMerge(map, template);
+ }
+
+ private String stupidMerge(Map map, String template) {
+ String result = new String(template);
+ String[] keys = (String[])map.keySet().toArray(new String[0]);
+ for (int i = 0; i < keys.length; i++) {
+ String replacement = (String)map.get(keys[i]);
+ result = result.replaceAll(Pattern.quote(createVariableString((keys[i]))), replacement);
+ }
+ return result;
+ }
+
+ public String createVariableString(String variableName) {
+ return "${" + variableName + "}";
+ }
+}
Added: spaces/trunk/src/com/ogoglio/mail/MailSendException.java
===================================================================
--- spaces/trunk/src/com/ogoglio/mail/MailSendException.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/mail/MailSendException.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,7 @@
+package com.ogoglio.mail;
+
+public class MailSendException extends Exception {
+ public MailSendException(Exception e) {
+ super(e);
+ }
+}
Added: spaces/trunk/src/com/ogoglio/mail/MailTests.java
===================================================================
--- spaces/trunk/src/com/ogoglio/mail/MailTests.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/mail/MailTests.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,104 @@
+package com.ogoglio.mail;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.util.HashMap;
+
+import junit.framework.TestCase;
+
+import com.ogoglio.util.ArgumentUtils;
+import com.ogoglio.util.StreamUtils;
+
+public class MailTests extends TestCase {
+
+ private static final String TEST_DIR_PATH = "mailTestFiles";
+
+ private static final String TEST_TEMPLATE_RESOURCE_PATH = "com/ogoglio/mail/";
+
+ private static final String TEST_TEMPLATE_1_NAME = "TestTemplate1.txt";
+
+ private File mailOutputDir = null;
+
+ private MailClient mailClient1 = null;
+
+ private MailFormatter mailFormatter1 = null;
+
+ private String testTemplate1 = null;
+
+ private HashMap testMap1 = null;
+
+ public void setUp() throws IOException {
+ mailOutputDir = new File(TEST_DIR_PATH);
+ if (mailOutputDir.exists()) {
+ delete(mailOutputDir);
+ }
+ assertTrue(mailOutputDir.mkdir());
+
+ mailClient1 = new MailClient(mailOutputDir);
+
+ mailFormatter1 = new MailFormatter();
+
+ testTemplate1 = StreamUtils.readResource(TEST_TEMPLATE_RESOURCE_PATH + TEST_TEMPLATE_1_NAME);
+ assertNotNull(testTemplate1);
+
+ testMap1 = new HashMap();
+ testMap1.put("username", "susan");
+ testMap1.put("url", "http://example.com/og/");
+ testMap1.put("moon.unit", "zappa");
+ testMap1.put("Kurt", "Vonnegut.");
+ }
+
+ private void delete(File dir) {
+ File[] children = dir.listFiles();
+ for (int i = 0; i < children.length; i++) {
+ assertTrue(children[i].delete());
+ }
+ assertTrue(dir.delete());
+ }
+
+ public void tearDown() {
+ if (mailOutputDir != null && mailOutputDir.exists()) {
+ delete(mailOutputDir);
+ }
+ }
+
+ public void testClientFileOutput() throws MailSendException, FileNotFoundException, IOException {
+ String body = "This is the body.";
+ String to = "to...@ex...";
+ String from = "ha...@ex...";
+ String subject = "OWLs 'n Stuff";
+ mailClient1.sendEmail(to, from, subject, body);
+ File[] files = mailClient1.getOutputDir().listFiles();
+ assertNotNull(files);
+ assertEquals(1, files.length);
+ assertFalse(files[0].length() == 0);
+ String fileContents = StreamUtils.readInput(new FileInputStream(files[0]));
+ assertTrue(fileContents.endsWith(body));
+ }
+
+ public void testFormat() {
+ String result = mailFormatter1.format(testMap1, testTemplate1);
+ assertNotNull(result);
+ assertTrue(result.length() > 1);
+ assertExactlyOne(result, (String) testMap1.get("username"));
+ assertMultiple(result, (String) testMap1.get("url"));
+ assertExactlyOne(result, (String) testMap1.get("moon.unit"));
+ assertExactlyOne(result, (String) testMap1.get("Kurt"));
+ }
+
+ private void assertExactlyOne(String data, String target) {
+ ArgumentUtils.assertNotEmpty(data);
+ ArgumentUtils.assertNotEmpty(target);
+ assertFalse(data.indexOf(target) == -1);
+ assertTrue(data.indexOf(target) == data.lastIndexOf(target));
+ }
+
+ private void assertMultiple(String data, String target) {
+ ArgumentUtils.assertNotEmpty(data);
+ ArgumentUtils.assertNotEmpty(target);
+ assertFalse(data.indexOf(target) == -1);
+ assertFalse(data.indexOf(target) == data.lastIndexOf(target));
+ }
+}
Added: spaces/trunk/src/com/ogoglio/mail/TestTemplate1.txt
===================================================================
--- spaces/trunk/src/com/ogoglio/mail/TestTemplate1.txt (rev 0)
+++ spaces/trunk/src/com/ogoglio/mail/TestTemplate1.txt 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,6 @@
+Replace this with username: ${username}
+Replace this with url: ${url}
+Also replace this with url: ${url}
+Replace this with moon.unit: ${moon.unit}
+Don't replace this with it, though: ${moonAunit}
+Replace this with Kurt: ${Kurt}
\ No newline at end of file
Modified: spaces/trunk/src/com/ogoglio/persist/AccountPersistTasks.java
===================================================================
--- spaces/trunk/src/com/ogoglio/persist/AccountPersistTasks.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/persist/AccountPersistTasks.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -21,193 +21,160 @@
public class AccountPersistTasks {
- public static final String ACCOUNT_BY_USERNAME = "com.ogoglio.persist.accountByUsername";
- public static final String ACCOUNT_BY_EMAIL = "com.ogoglio.persist.accountByEmail";
+ public static final String ACCOUNT_BY_USERNAME = "com.ogoglio.persist.accountByUsername";
- public static final String ACCOUNT_BY_COOKIE = "com.ogoglio.persist.accountByCookie";
+ public static final String ACCOUNT_BY_EMAIL = "com.ogoglio.persist.accountByEmail";
- public static boolean update(final AccountRecord record,
- final AccountDocument document, SessionFactory sessionFactory)
- throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- boolean dirty = false;
- if (document.getAccountLevel() != null
- && !equals(record.getAccountlevel(), document
- .getAccountLevel())) {
- dirty = true;
- record.setAccountlevel(document.getAccountLevel());
- }
+ public static final String ACCOUNT_BY_COOKIE = "com.ogoglio.persist.accountByCookie";
- if (document.getHomepage() != null
- && !equals(record.getHomepage(), document.getHomepage())) {
- dirty = true;
- record.setHomepage(document.getHomepage());
- }
+ public static boolean update(final AccountRecord record, final AccountDocument document, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ boolean dirty = false;
+ if (document.getAccountLevel() != null && !equals(record.getAccountlevel(), document.getAccountLevel())) {
+ dirty = true;
+ record.setAccountlevel(document.getAccountLevel());
+ }
- if (document.getFirstName() != null
- && !equals(record.getFirstName(), document
- .getFirstName())) {
- dirty = true;
- record.setFirstName(document.getFirstName());
- }
+ if (document.getHomepage() != null && !equals(record.getHomepage(), document.getHomepage())) {
+ dirty = true;
+ record.setHomepage(document.getHomepage());
+ }
- if (document.getLastName() != null
- && !equals(record.getLastName(), document.getLastName())) {
- dirty = true;
- record.setLastName(document.getLastName());
- }
+ if (document.getFirstName() != null && !equals(record.getFirstName(), document.getFirstName())) {
+ dirty = true;
+ record.setFirstName(document.getFirstName());
+ }
- if (document.getPassword() != null
- && !equals(record.getPassword(), document.getPassword())) {
- if (AccountRecord.cleanPassword(document.getPassword()) != null) {
- dirty = true;
- record.setPassword(document.getPassword());
- }
- }
+ if (document.getLastName() != null && !equals(record.getLastName(), document.getLastName())) {
+ dirty = true;
+ record.setLastName(document.getLastName());
+ }
- if (document.getDefaultBodyID() != -1) {
- Query bodyQuery = hibernateSession
- .getNamedQuery(BodyPersistTasks.BODY_BY_ID);
- bodyQuery.setLong("bodyID", document.getDefaultBodyID());
- BodyRecord bodyRec = (BodyRecord) bodyQuery.uniqueResult();
- if (bodyRec != null
- && bodyRec.getOwnerUsername().equals(
- record.getUsername())) {
- dirty = true;
- record.setDefaultBodyID(document.getDefaultBodyID());
- }
- }
+ if (document.getPassword() != null && !equals(record.getPassword(), document.getPassword())) {
+ if (AccountRecord.cleanPassword(document.getPassword()) != null) {
+ dirty = true;
+ record.setPassword(document.getPassword());
+ }
+ }
-
- if (document.getFrozenUntil() != null) {
- if (record.getFrozenUntil()!=document.getFrozenUntil().getTime()) {
- dirty = true;
- if (document.getFrozenUntil().getTime() < System.currentTimeMillis()) {
- record.setNotFrozen();
- } else {
- record.setFrozenUntil(document.getFrozenUntil().getTime());
- }
- }
- }
- if (dirty) {
- hibernateSession.update(record);
- return Boolean.TRUE;
- }
- return Boolean.FALSE;
- }
- };
- task.setSessionFactory(sessionFactory);
- return "true".equals(task.execute().toString());
- }
+ if (document.getDefaultBodyID() != -1) {
+ Query bodyQuery = hibernateSession.getNamedQuery(BodyPersistTasks.BODY_BY_ID);
+ bodyQuery.setLong("bodyID", document.getDefaultBodyID());
+ BodyRecord bodyRec = (BodyRecord) bodyQuery.uniqueResult();
+ if (bodyRec != null && bodyRec.getOwnerUsername().equals(record.getUsername())) {
+ dirty = true;
+ record.setDefaultBodyID(document.getDefaultBodyID());
+ }
+ }
- public static void update(final AccountRecord record,
- SessionFactory sessionFactory) throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- hibernateSession.update(record);
- return null;
- }
- };
- task.setSessionFactory(sessionFactory);
- task.execute();
- }
+ if (document.getFrozenUntil() != null) {
+ if (record.getFrozenUntil() != document.getFrozenUntil().getTime()) {
+ dirty = true;
+ if (document.getFrozenUntil().getTime() < System.currentTimeMillis()) {
+ record.setNotFrozen();
+ } else {
+ record.setFrozenUntil(document.getFrozenUntil().getTime());
+ }
+ }
+ }
+ if (dirty) {
+ hibernateSession.update(record);
+ return Boolean.TRUE;
+ }
+ return Boolean.FALSE;
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return "true".equals(task.execute().toString());
+ }
- public static AccountRecord findAccountByCookie(final String cookie,
- SessionFactory sessionFactory) throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- Query query = hibernateSession.getNamedQuery(ACCOUNT_BY_COOKIE);
- query.setParameter("cookie", cookie);
- AccountRecord rec = (AccountRecord) query.uniqueResult();
- return rec;
- }
- };
- task.setSessionFactory(sessionFactory);
- return (AccountRecord) task.execute();
- }
+ public static void update(final AccountRecord record, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ hibernateSession.update(record);
+ return null;
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ task.execute();
+ }
- public static AccountRecord[] findAllAccounts(SessionFactory sessionFactory)
- throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- Query query = hibernateSession
- .getNamedQuery("com.ogoglio.persist.accounts");
- return query.list().toArray(new AccountRecord[0]);
- }
- };
- task.setSessionFactory(sessionFactory);
- return (AccountRecord[]) task.execute();
- }
+ public static AccountRecord findAccountByCookie(final String cookie, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ Query query = hibernateSession.getNamedQuery(ACCOUNT_BY_COOKIE);
+ query.setParameter("cookie", cookie);
+ AccountRecord rec = (AccountRecord) query.uniqueResult();
+ return rec;
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (AccountRecord) task.execute();
+ }
- public static AccountRecord createAccount(final String username,
- final String accountlevel, final String email,
- SessionFactory sessionFactory) throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- final String cleanedUsername = AccountRecord
- .cleanUsername(username);
- Query query = hibernateSession
- .getNamedQuery(ACCOUNT_BY_USERNAME);
- query.setParameter("username", cleanedUsername);
+ public static AccountRecord[] findAllAccounts(SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ Query query = hibernateSession.getNamedQuery("com.ogoglio.persist.accounts");
+ return query.list().toArray(new AccountRecord[0]);
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (AccountRecord[]) task.execute();
+ }
- AccountRecord record = (AccountRecord) query.uniqueResult();
- if (record != null) {
- return null; // XXX really weird semantic: try to create something and get null because it's there?
- }
+ public static AccountRecord createAccount(final String username, final String accountlevel, final String email, SessionFactory sessionFactory) throws PersistException {
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ final String cleanedUsername = AccountRecord.cleanUsername(username);
+ Query query = hibernateSession.getNamedQuery(ACCOUNT_BY_USERNAME);
+ query.setParameter("username", cleanedUsername);
- //IES:debug because unique constraint on this field!
- final String cleanedEmail = AccountRecord.cleanEmail(email);
- query = hibernateSession.getNamedQuery(ACCOUNT_BY_EMAIL);
- query.setParameter("email", email);
- record = (AccountRecord) query.uniqueResult();
- if (record != null) {
- System.err.println("Whoa! Bad email value!" + email);
- }
+ AccountRecord record = (AccountRecord) query.uniqueResult();
+ if (record != null) {
+ return null;
+ }
- record = new AccountRecord(username, accountlevel, email);
- hibernateSession.save(record);
- BodyRecord bodyRec = new BodyRecord("Body", record
- .getUsername());
- hibernateSession.save(bodyRec);
+ String cleanedEmail = AccountRecord.cleanEmail(email);
+ query = hibernateSession.getNamedQuery(ACCOUNT_BY_EMAIL);
+ query.setParameter("email", cleanedEmail);
+ record = (AccountRecord) query.uniqueResult();
+ if (record != null) {
+ System.err.println("Whoa! Bad email value!" + cleanedEmail);
+ }
- record.setDefaultBodyID(bodyRec.getBodyID());
- hibernateSession.update(record);
- return record;
- }
- };
- task.setSessionFactory(sessionFactory);
- return (AccountRecord) task.execute();
- }
+ record = new AccountRecord(username, accountlevel, cleanedEmail);
+ hibernateSession.save(record);
+ BodyRecord bodyRec = new BodyRecord("Body", record.getUsername());
+ hibernateSession.save(bodyRec);
- public static AccountRecord findAccountByUsername(String username,
- SessionFactory sessionFactory) throws PersistException {
- final String cleanedUsername = AccountRecord.cleanUsername(username);
- if (cleanedUsername == null) {
- return null;
- }
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- Query query = hibernateSession
- .getNamedQuery(ACCOUNT_BY_USERNAME);
- query.setParameter("username", cleanedUsername);
- return query.uniqueResult();
- }
- };
- task.setSessionFactory(sessionFactory);
- return (AccountRecord) task.execute();
- }
+ record.setDefaultBodyID(bodyRec.getBodyID());
+ hibernateSession.update(record);
+
+ PendingEmailValidationRecord validationRecord = new PendingEmailValidationRecord(username, cleanedEmail);
+ hibernateSession.save(validationRecord);
+
+ return record;
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (AccountRecord) task.execute();
+ }
- public static void delete(final AccountRecord accRec,
- SessionFactory sessionFactory) throws PersistException {
- HibernateTask task = new HibernateTask() {
- public Object run(Session hibernateSession) {
- hibernateSession.delete(accRec);
- return null;
- }
- };
- task.setSessionFactory(sessionFactory);
- task.execute();
-
- }
+ public static AccountRecord findAccountByUsername(String username, SessionFactory sessionFactory) throws PersistException {
+ final String cleanedUsername = AccountRecord.cleanUsername(username);
+ if (cleanedUsername == null) {
+ return null;
+ }
+ HibernateTask task = new HibernateTask() {
+ public Object run(Session hibernateSession) {
+ Query query = hibernateSession.getNamedQuery(ACCOUNT_BY_USERNAME);
+ query.setParameter("username", cleanedUsername);
+ return query.uniqueResult();
+ }
+ };
+ task.setSessionFactory(sessionFactory);
+ return (AccountRecord) task.execute();
+ }
}
Added: spaces/trunk/src/com/ogoglio/persist/PendingEmailValidationRecord.java
===================================================================
--- spaces/trunk/src/com/ogoglio/persist/PendingEmailValidationRecord.java (rev 0)
+++ spaces/trunk/src/com/ogoglio/persist/PendingEmailValidationRecord.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -0,0 +1,73 @@
+package com.ogoglio.persist;
+
+import java.util.Random;
+
+import com.ogoglio.util.ArgumentUtils;
+
+public class PendingEmailValidationRecord {
+
+ private static Random RANDOM = new Random();
+
+ private String username = null;
+
+ private String email = null;
+
+ private String secret = null;
+
+ private long creationDate = AccountRecord.NO_TIME_VALUE;
+
+ public PendingEmailValidationRecord() {
+ }
+
+ public PendingEmailValidationRecord(String username, String email) {
+ ArgumentUtils.assertNotEmpty(username);
+ ArgumentUtils.assertIsEmail(email);
+ this.username = username;
+ this.email = email;
+ this.secret = generateSecret();
+ creationDate = System.currentTimeMillis();
+ }
+
+ private static final String SECRET_SOURCE = "abcdefghijklmnopqrstuvwxyz1234567890";
+
+ private String generateSecret() {
+ StringBuffer result = new StringBuffer();
+ for (int i = 0; i < 25; i++) {
+ result.append(SECRET_SOURCE.charAt(Math.abs(RANDOM.nextInt()) % SECRET_SOURCE.length()));
+ }
+ return result.toString();
+ }
+
+ public long getCreationDate() {
+ return creationDate;
+ }
+
+ public void setCreationDate(long creationDate) {
+ this.creationDate = creationDate;
+ }
+
+ public String getEmail() {
+ return email;
+ }
+
+ public void setEmail(String email) {
+ ArgumentUtils.assertIsEmail(email);
+ this.email = email;
+ }
+
+ public String getSecret() {
+ return secret;
+ }
+
+ public void setSecret(String secret) {
+ this.secret = secret;
+ }
+
+ public String getUsername() {
+ return username;
+ }
+
+ public void setUsername(String username) {
+ this.username = username;
+ }
+}
Modified: spaces/trunk/src/com/ogoglio/persist/Persist.hbm.xml
===================================================================
--- spaces/trunk/src/com/ogoglio/persist/Persist.hbm.xml 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/persist/Persist.hbm.xml 2007-08-20 23:09:52 UTC (rev 248)
@@ -89,6 +89,13 @@
<property name="defaultBodyID" />
</class>
+ <class name="com.ogoglio.persist.PendingEmailValidationRecord" table="PendingEmailValidationRecords">
+ <id name="email"><generator class="assigned"/></id>
+ <property name="username" not-null="true" />
+ <property name="secret" not-null="true" />
+ <property name="creationDate" />
+ </class>
+
<class name="com.ogoglio.persist.TemplateRecord" table="TemplateRecords">
<id name="templateID">
<generator class="increment"/>
Modified: spaces/trunk/src/com/ogoglio/persist/PersistTests.java
===================================================================
--- spaces/trunk/src/com/ogoglio/persist/PersistTests.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/persist/PersistTests.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -15,11 +15,6 @@
import java.net.URI;
-import junit.framework.TestCase;
-
-import org.hibernate.SessionFactory;
-import org.hibernate.cfg.Configuration;
-
public class PersistTests extends HibernateTests {
private String displayName1 = "Breakfast of Sim";
@@ -31,23 +26,23 @@
String username1 = null;
String email1 = null;
-
+
String level1 = null;
String username2 = null;
String email2 = null;
-
+
String level2 = null;
public void setUp() {
try {
- super.setUp();
-
+ super.setUp();
+
username1 = AccountRecord.cleanUsername("MoonUnitZappa");
email1 = AccountRecord.cleanEmail("mu...@ex...");
level1 = "basic";
-
+
username2 = AccountRecord.cleanUsername("KurtVonnegut");
email2 = AccountRecord.cleanEmail("kv...@ex...");
level2 = "pro";
@@ -59,42 +54,40 @@
}
}
-
public void testRecords() {
try {
- String ONE_TWO="1234";
-
- AccountRecord accRec1= AccountPersistTasks.findAccountByUsername(username1, sessionFactory);
- if (accRec1!=null) {
- System.out.println("Destroying leftover account test state:"+username1);
- AccountPersistTasks.delete(accRec1,sessionFactory);
+ String ONE_TWO = "1234";
+
+ AccountRecord accRec1 = AccountPersistTasks.findAccountByUsername(username1, sessionFactory);
+ if (accRec1 == null) {
+ accRec1 = AccountPersistTasks.createAccount(username1, level1, email1, sessionFactory);
}
- accRec1 = AccountPersistTasks.createAccount(username1, level1, email1, sessionFactory);
- verifyAccountProps(accRec1,username1, email1, level1, null);
-
+ assertNotNull(accRec1);
+
+ verifyAccountProps(accRec1, username1, email1, level1, null);
+
accRec1.setPassword("1234");
AccountPersistTasks.update(accRec1, sessionFactory);
AccountRecord accRec2 = AccountPersistTasks.findAccountByUsername(username1, sessionFactory);
assertNotNull(accRec2);
verifyAccountProps(accRec2, username1, email1, level1, ONE_TWO);
-
+
String templateName1 = "Plate of Raw Oysters";
- TemplateRecord templateRec1 = TemplatePersistTasks.createTemplate(templateName1 , username1, sessionFactory);
+ TemplateRecord templateRec1 = TemplatePersistTasks.createTemplate(templateName1, username1, sessionFactory);
verifyTemplateProps(templateName1, templateRec1);
-
+
templateRec1 = TemplatePersistTasks.findTemplateByTemplateID(templateRec1.getTemplateID(), sessionFactory);
verifyTemplateProps(templateName1, templateRec1);
- SimRecord simRecord1=SimPersistTasks.findSimsBySimURI(simURI1, sessionFactory);
- if (simRecord1!=null) {
- System.out.println("Destroying leftover sim record test state:"+
- simRecord1.getDisplayName());
- SimPersistTasks.delete(simRecord1,sessionFactory);
+ SimRecord simRecord1 = SimPersistTasks.findSimsBySimURI(simURI1, sessionFactory);
+ if (simRecord1 != null) {
+ System.out.println("Destroying leftover sim record test state:" + simRecord1.getDisplayName());
+ SimPersistTasks.delete(simRecord1, sessionFactory);
}
- //ok to create sim now on that URI
+ //ok to create sim now on that URI
simRecord1 = SimPersistTasks.createSim(displayName1, simURI1, 2048, true, sessionFactory);
- verifySimProps(simRecord1,displayName1,simURI1,-1,2048);
+ verifySimProps(simRecord1, displayName1, simURI1, -1, 2048);
String displayName2 = "moon unit";
simRecord1.setDisplayName(displayName2);
@@ -118,30 +111,29 @@
SpaceRecord spaceRecord2 = SpacePersistTasks.findSpaceBySpaceID(spaceRecord1.getSpaceID(), sessionFactory);
assertEquals(spaceRecord1, spaceRecord2);
-
+
SimRecord assignedSimRecord = SpacePersistTasks.findOrAssignSim(spaceRecord2, sessionFactory);
assertNotNull(assignedSimRecord);
- System.out.println("XXX ASSIGNED TO SIM:"+assignedSimRecord.getSimID()+","+assignedSimRecord.getSimURI()+" -->\n"+
- "space was "+spaceRecord2.getSpaceID()+" now on "+spaceRecord2.getSimID()+","+spaceRecord2.getDisplayName());
+ System.out.println("XXX ASSIGNED TO SIM:" + assignedSimRecord.getSimID() + "," + assignedSimRecord.getSimURI() + " -->\n" + "space was " + spaceRecord2.getSpaceID() + " now on " + spaceRecord2.getSimID() + "," + spaceRecord2.getDisplayName());
/*
* IES: I spent a lot of time looking at this and could not see any way to test this given that
* IES: that assigned sim is random. Apparently, before we were depending on a random number
* IES: sequence doing something we expected.
- assertEquals(simRecord1.getSimURI(), assignedSimRecord.getSimURI());
- assertEquals(simRecord1.getDisplayName(), assignedSimRecord.getDisplayName());
- assertEquals(simRecord1.getSimID(), assignedSimRecord.getSimID());
- assertEquals(simRecord1, assignedSimRecord);
+ assertEquals(simRecord1.getSimURI(), assignedSimRecord.getSimURI());
+ assertEquals(simRecord1.getDisplayName(), assignedSimRecord.getDisplayName());
+ assertEquals(simRecord1.getSimID(), assignedSimRecord.getSimID());
+ assertEquals(simRecord1, assignedSimRecord);
*/
-
+
BodyRecord bodyRec1 = BodyPersistTasks.createBody(displayName1, "bogosity", sessionFactory);
assertNull("created body with bogus username", bodyRec1);
bodyRec1 = BodyPersistTasks.createBody(displayName1, username1, sessionFactory);
assertNotNull(bodyRec1);
-
+
BodyRecord bodyRec2 = BodyPersistTasks.findBodyByID(bodyRec1.getBodyID(), sessionFactory);
assertNotNull(bodyRec2);
assertEquals(bodyRec1, bodyRec2);
-
+
PossessionRecord possRecord = PossessionPersistTasks.createPossession(username1, templateRec1.getTemplateID(), sessionFactory);
assertNotNull(possRecord);
assertEquals(username1, possRecord.getOwnerUsername());
@@ -154,7 +146,7 @@
assertEquals(12, possRecord.getThingID());
PossessionRecord[] possRecs1 = PossessionPersistTasks.findPossessionsByOwnerUsername(username1, sessionFactory);
- assertNotNull(possRecs1);
+ assertNotNull(possRecs1);
assertEquals(username1, possRecs1[0].getOwnerUsername());
} catch (PersistException e) {
@@ -170,32 +162,29 @@
}
}
-
private void verifySimProps(SimRecord rec, String name, URI uri, int not_id, int port) {
assertNotNull(rec);
assertEquals(name, rec.getDisplayName());
assertEquals(uri, rec.getSimURI());
assertFalse(not_id == rec.getSimID());
- assertEquals(port, rec.getEventPort());
+ assertEquals(port, rec.getEventPort());
}
-
private void verifyTemplateProps(String templateName1, TemplateRecord templateRec1) {
assertNotNull(templateRec1);
assertEquals(templateName1, templateRec1.getDisplayName());
assertEquals(username1, templateRec1.getOwnerUsername());
}
-
private void verifyAccountProps(AccountRecord rec, String user, String mail, String level, String pwd) {
assertNotNull(rec);
assertEquals(user, rec.getUsername());
assertEquals(mail, rec.getEmail());
assertEquals(level, rec.getAccountlevel());
- if (pwd==null) {
+ if (pwd == null) {
assertNull(rec.getPassword());
} else {
- assertEquals(pwd,rec.getPassword());
+ assertEquals(pwd, rec.getPassword());
}
}
}
\ No newline at end of file
Modified: spaces/trunk/src/com/ogoglio/site/AccountServlet.java
===================================================================
--- spaces/trunk/src/com/ogoglio/site/AccountServlet.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/site/AccountServlet.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -17,7 +17,6 @@
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
-import java.util.Date;
import javax.media.j3d.Transform3D;
import javax.servlet.ServletConfig;
@@ -27,7 +26,6 @@
import nanoxml.XMLElement;
-import com.ogoglio.client.WebAPIClient;
import com.ogoglio.client.WebAPIClientWire;
import com.ogoglio.client.WebAPIUtil;
import com.ogoglio.media.MediaService;
@@ -130,6 +128,14 @@
newAccountRec.setLastName(newAccountDoc.getLastName());
newAccountRec.setHomepage(newAccountDoc.getHomepage());
AccountPersistTasks.update(newAccountRec, sessionFactory);
+
+ /*
+ * Email templates: velocity?
+ * Site (or app?) specific validation email template
+ *
+ */
+ System.out.println("TODO: This is where we would send the validation email");
+
sendStringResponse(createAccountDocument(newAccountRec, true).toElement().toString(), "text/xml", response);
}
}
@@ -196,12 +202,12 @@
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
- if (requestedAccount.getFrozenUntil() != AccountRecord.NO_TIME_VALUE && requestedAccount.getFrozenUntil()!=updatedDocument.getFrozenUntil().getTime()) {
+ if (requestedAccount.getFrozenUntil() != AccountRecord.NO_TIME_VALUE && requestedAccount.getFrozenUntil() != updatedDocument.getFrozenUntil().getTime()) {
System.err.println("User tried to update own freeze: " + requestedAccount.getUsername());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
- if (requestedAccount.getFrozenUntil() !=AccountRecord.NO_TIME_VALUE && updatedDocument.getFrozenUntil() != null) {
+ if (requestedAccount.getFrozenUntil() != AccountRecord.NO_TIME_VALUE && updatedDocument.getFrozenUntil() != null) {
System.err.println("User tried to freeze themselves: " + requestedAccount.getUsername());
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
@@ -211,9 +217,9 @@
//TODO if this returns false we really should reflect that in the response
if (!AccountPersistTasks.update(requestedAccount, updatedDocument, getSessionFactory())) {
- System.out.println("Warning: ACCOUNT update failed:"+requestedAccount.getUsername());
+ System.out.println("Warning: ACCOUNT update failed:" + requestedAccount.getUsername());
}
- //AccountPersistTasks.findAccountByUsername(usernameParam, getSessionFactory());
+
AccountDocument result = createAccountDocument(requestedAccount, true);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType("text/xml");
@@ -262,7 +268,7 @@
public class TemplatesResource extends AuthenticatedSiteResource {
public TemplatesResource() {
super("template", true, getSessionFactory());
- addSubResource(new TemplateResource(getSessionFactory(),getMediaService()));
+ addSubResource(new TemplateResource(getSessionFactory(), getMediaService()));
}
public void doPost(HttpServletRequest request, HttpServletResponse response, String[] pathElements, AccountRecord authedAccount) throws PersistException, ServletException, IOException {
@@ -279,14 +285,13 @@
response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
return;
}
-
+
TemplateDocument result = new TemplateDocument(rec);
sendStringResponse(result.toString(), "text/xml", response);
}
- public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements,
- AccountRecord authedAccount) throws PersistException, ServletException, IOException {
+ public void doGet(HttpServletRequest request, HttpServletResponse response, String[] pathElements, AccountRecord authedAccount) throws PersistException, ServletException, IOException {
String usernameParam = pathElements[pathElements.length - 2];
AccountRecord requestedAccount = AccountPersistTasks.findAccountByUsername(usernameParam, getSessionFactory());
if (requestedAccount == null) {
Modified: spaces/trunk/src/com/ogoglio/util/ArgumentUtils.java
===================================================================
--- spaces/trunk/src/com/ogoglio/util/ArgumentUtils.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/util/ArgumentUtils.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -100,5 +100,17 @@
}
}
+ public static void assertIsEmail(String email) {
+ if(email == null || email.trim().length() == 0) {
+ throw new IllegalArgumentException("Bad email: " + email);
+ }
+ if(email.indexOf("@") == -1 || email.indexOf("@") == 0) {
+ throw new IllegalArgumentException("Bad email: " + email);
+ }
+ if(email.indexOf(".", email.indexOf("@")) == -1 && email.indexOf("localhost") != email.indexOf("@") + 1) {
+ throw new IllegalArgumentException("Bad email: " + email);
+ }
+ }
+
}
Modified: spaces/trunk/src/com/ogoglio/util/StreamUtils.java
===================================================================
--- spaces/trunk/src/com/ogoglio/util/StreamUtils.java 2007-08-20 03:43:05 UTC (rev 247)
+++ spaces/trunk/src/com/ogoglio/util/StreamUtils.java 2007-08-20 23:09:52 UTC (rev 248)
@@ -58,6 +58,14 @@
output.close();
}
+ public static String readResource(String resourceName) throws IOException {
+ InputStream resourceStream = StreamUtils.class.getClassLoader().getResourceAsStream(resourceName);
+ if (resourceStream == null) {
+ return null;
+ }
+ return readInput(resourceStream);
+ }
+
public static void copyResource(String resourceName, File destinationDir) throws IOException {
InputStream resourceStream = StreamUtils.class.getClassLoader().getResourceAsStream(resourceName);
if (resourceStream == null) {
This was sent by the SourceForge.net collaborative development platform, the world's largest Open Source development site.
|