You are viewing a plain text version of this content. The canonical link for it is here.
Posted to server-dev@james.apache.org by jo...@apache.org on 2006/10/09 19:15:42 UTC

svn commit: r454432 [7/14] - in /james/server/sandbox/imap-integration: ./ lib/ src/java/ src/java/org/apache/james/imapserver/ src/java/org/apache/james/imapserver/commands/ src/java/org/apache/james/imapserver/debug/ src/java/org/apache/james/imapser...

Added: james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailbox.java
URL: http://svn.apache.org/viewvc/james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailbox.java?view=auto&rev=454432
==============================================================================
--- james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailbox.java (added)
+++ james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailbox.java Mon Oct  9 10:15:30 2006
@@ -0,0 +1,528 @@
+package org.apache.james.mailboxmanager.torque;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.sql.SQLException;
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+
+import javax.mail.Flags;
+import javax.mail.MessagingException;
+import javax.mail.internet.MimeMessage;
+import javax.mail.search.SearchTerm;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.impl.SimpleLog;
+import org.apache.james.mailboxmanager.GeneralMessageSet;
+import org.apache.james.mailboxmanager.MailboxListener;
+import org.apache.james.mailboxmanager.MailboxManagerException;
+import org.apache.james.mailboxmanager.MessageResult;
+import org.apache.james.mailboxmanager.impl.GeneralMessageSetImpl;
+import org.apache.james.mailboxmanager.impl.MailboxEventDispatcher;
+import org.apache.james.mailboxmanager.impl.MessageResultImpl;
+import org.apache.james.mailboxmanager.mailbox.ImapMailbox;
+import org.apache.james.mailboxmanager.torque.om.MailboxRow;
+import org.apache.james.mailboxmanager.torque.om.MailboxRowPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageBody;
+import org.apache.james.mailboxmanager.torque.om.MessageFlags;
+import org.apache.james.mailboxmanager.torque.om.MessageFlagsPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageHeader;
+import org.apache.james.mailboxmanager.torque.om.MessageRow;
+import org.apache.james.mailboxmanager.torque.om.MessageRowPeer;
+import org.apache.james.mailboxmanager.tracking.UidChangeTracker;
+import org.apache.james.mailboxmanager.tracking.UidRange;
+import org.apache.torque.NoRowsException;
+import org.apache.torque.TooManyRowsException;
+import org.apache.torque.TorqueException;
+import org.apache.torque.util.Criteria;
+
+import com.sun.mail.util.CRLFOutputStream;
+import com.workingdogs.village.DataSetException;
+
+public class TorqueMailbox implements ImapMailbox {
+
+    private boolean open = true;
+
+    private MailboxRow mailboxRow;
+
+    private Flags permanentFlags;
+
+    private UidChangeTracker tracker;
+
+    private MailboxEventDispatcher eventDispatcher = new MailboxEventDispatcher();
+    
+    protected Log log;
+
+    TorqueMailbox(MailboxRow mailboxRow, UidChangeTracker tracker, Log log) {
+        this.log=log;
+    	this.mailboxRow = mailboxRow;
+        this.tracker = tracker;
+        tracker.addMailboxListener(getEventDispatcher());
+    }
+
+    public int getMessageResultTypes() {
+        return MessageResult.FLAGS + MessageResult.INTERNAL_DATE
+                + MessageResult.KEY + MessageResult.MIME_MESSAGE
+                + MessageResult.SIZE + MessageResult.UID;
+    }
+
+    public int getMessageSetTypes() {
+        return GeneralMessageSet.TYPE_ALL + GeneralMessageSet.TYPE_KEY
+                + GeneralMessageSet.TYPE_UID + GeneralMessageSet.TYPE_MESSAGE;
+    }
+
+    public synchronized String getName() throws MailboxManagerException {
+    	checkAccess();
+        return getUidChangeTracker().getMailboxName();
+    }
+
+    public int getMessageCount() throws MailboxManagerException {
+    	checkAccess();
+        try {
+            return getMailboxRow().countMessages();
+        } catch (Exception e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+
+    public MessageResult appendMessage(MimeMessage message, Date internalDate,
+            int result) throws MailboxManagerException {
+    	checkAccess();
+		final MailboxRow myMailboxRow;
+		try {
+			myMailboxRow = getMailboxRow().consumeNextUid();
+		} catch (TorqueException e) {
+			throw new MailboxManagerException(e);
+		} catch (SQLException e) {
+			throw new MailboxManagerException(e);
+		}
+		if (myMailboxRow != null) {
+			try {
+				// To be thread safe, we first get our own copy and the
+				// exclusive
+				// Uid
+				// TODO create own message_id and assign uid later
+				// at the moment it could lead to the situation that uid 5 is
+				// insertet long before 4, when
+				// mail 4 is big and comes over a slow connection.
+				long uid = myMailboxRow.getLastUid();
+				this.mailboxRow = myMailboxRow;
+
+				MessageRow messageRow = new MessageRow();
+				messageRow.setMailboxId(getMailboxRow().getMailboxId());
+				messageRow.setUid(uid);
+				messageRow.setInternalDate(internalDate);
+
+				// TODO very ugly size mesurement
+				ByteArrayOutputStream sizeBos = new ByteArrayOutputStream();
+				message.writeTo(new CRLFOutputStream(sizeBos));
+				messageRow.setSize(sizeBos.size());
+				MessageFlags messageFlags = new MessageFlags();
+				messageFlags.setFlags(message.getFlags());
+				messageRow.addMessageFlags(messageFlags);
+
+				int line_number = 0;
+
+				for (Enumeration lines = message.getAllHeaderLines(); lines
+						.hasMoreElements();) {
+					String line = (String) lines.nextElement();
+					int colon = line.indexOf(": ");
+					if (colon > 0) {
+						line_number++;
+						MessageHeader mh = new MessageHeader();
+						mh.setLineNumber(line_number);
+						mh.setField(line.substring(0, colon));
+						// TODO avoid unlikely IOOB Exception
+						mh.setValue(line.substring(colon + 2));
+						messageRow.addMessageHeader(mh);
+					}
+				}
+
+				MessageBody mb = new MessageBody();
+
+				InputStream is = message.getInputStream();
+
+				ByteArrayOutputStream baos = new ByteArrayOutputStream();
+				byte[] buf = new byte[4096];
+				int read;
+				while ((read = is.read(buf)) > 0) {
+					baos.write(buf, 0, read);
+				}
+
+				mb.setBody(baos.toByteArray());
+				messageRow.addMessageBody(mb);
+
+				messageRow.save();
+				MessageResult messageResult = fillMessageResult(messageRow,
+						result | MessageResult.UID);
+				checkForScanGap(uid);
+				getUidChangeTracker().found(messageResult, null);
+				return messageResult;
+			} catch (Exception e) {
+				throw new MailboxManagerException(e);
+			}
+		} else {
+			// mailboxRow==null
+			getUidChangeTracker().mailboxNotFound();
+			throw new MailboxManagerException("Mailbox has been deleted");
+		}
+
+	}
+
+    private void checkForScanGap(long uid) throws MailboxManagerException, TorqueException, MessagingException {
+		synchronized (getUidChangeTracker()) {
+			long lastScannedUid=getUidChangeTracker().getLastScannedUid();
+			if (uid>(lastScannedUid+1)) {
+				GeneralMessageSet set=GeneralMessageSetImpl.uidRange(lastScannedUid+1, uid);
+				Criteria criteria=criteriaForMessageSet(set);
+				List messageRows=mailboxRow.getMessageRows(criteria);
+				MessageResult[] messageResults=fillMessageResult(messageRows, MessageResult.UID);
+				getUidChangeTracker().found(uidRangeForMessageSet(set), messageResults, null);
+			}
+		}
+		
+	}
+
+	public MessageResult updateMessage(GeneralMessageSet messageSet, MimeMessage message, int result) {
+        throw new RuntimeException("not yet implemented");
+    }
+
+    private Criteria criteriaForMessageSet(GeneralMessageSet set)
+            throws MailboxManagerException {
+        Criteria criteria = new Criteria();
+        criteria.addAscendingOrderByColumn(MessageRowPeer.UID);
+        if (set.getType() == GeneralMessageSet.TYPE_ALL) {
+        	// empty Criteria = everything
+        } else if (set.getType() == GeneralMessageSet.TYPE_UID) {
+            
+            if (set.getUidFrom() == set.getUidTo()) {
+                criteria.add(MessageRowPeer.UID, set.getUidFrom());
+            } else {
+                Criteria.Criterion criterion1=criteria.getNewCriterion(MessageRowPeer.UID, new Long(set.getUidFrom()),
+                        Criteria.GREATER_EQUAL);
+                if (set.getUidTo() > 0) {
+                    Criteria.Criterion criterion2=criteria.getNewCriterion(MessageRowPeer.UID, new Long(set.getUidTo()),
+                            Criteria.LESS_EQUAL);
+                    criterion1.and(criterion2);
+                }
+                criteria.add(criterion1);
+            }
+        } else {
+            throw new MailboxManagerException("unsupported MessageSet: "
+                    + set.getType());
+        }
+        return criteria;
+    }
+
+    public MessageResult[] getMessages(GeneralMessageSet set, int result)
+            throws MailboxManagerException {
+    	checkAccess();
+        if (!set.isValid()) {
+            return new MessageResult[0];
+        }
+        Criteria c = criteriaForMessageSet(set);
+        UidRange range = uidRangeForMessageSet(set);
+        try {
+            List l = getMailboxRow().getMessageRows(c);
+
+            MessageResult[] messageResults = fillMessageResult(l, result
+                    | MessageResult.UID | MessageResult.FLAGS);
+            checkForScanGap(range.getFromUid());
+            getUidChangeTracker().found(range, messageResults, null);
+            return messageResults;
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        } catch (MessagingException e) {
+            throw new MailboxManagerException(e);
+        }
+
+    }
+
+    private static UidRange uidRangeForMessageSet(GeneralMessageSet set)
+            throws MailboxManagerException {
+        if (set.getType() == GeneralMessageSet.TYPE_UID) {
+            return new UidRange(set.getUidFrom(), set.getUidTo());
+        } else if (set.getType() == GeneralMessageSet.TYPE_ALL) {
+            return new UidRange(1, -1);
+        } else {
+            throw new MailboxManagerException("unsupported MessageSet: "
+                    + set.getType());
+        }
+    }
+
+    private MessageResult[] fillMessageResult(List messageRows, int result)
+            throws TorqueException, MessagingException, MailboxManagerException {
+        MessageResult[] messageResults = new MessageResult[messageRows.size()];
+        int i = 0;
+        for (Iterator iter = messageRows.iterator(); iter.hasNext();) {
+            MessageRow messageRow = (MessageRow) iter.next();
+            messageResults[i] = fillMessageResult(messageRow, result);
+            i++;
+        }
+        return messageResults;
+    }
+
+    private MessageResult fillMessageResult(MessageRow messageRow, int result)
+            throws TorqueException, MessagingException, MailboxManagerException {
+        MessageResultImpl messageResult = new MessageResultImpl();
+        if ((result & MessageResult.MIME_MESSAGE) > 0) {
+            messageResult.setMimeMessage(TorqueMimeMessage.createMessage(messageRow,getLog()));
+            result -= MessageResult.MIME_MESSAGE;
+        }
+        if ((result & MessageResult.UID) > 0) {
+            messageResult.setUid(messageRow.getUid());
+            result -= MessageResult.UID;
+        }
+        if ((result & MessageResult.FLAGS) > 0) {
+        	MessageFlags messageFlags=messageRow.getMessageFlags();
+        	if (messageFlags!=null) {
+        		messageResult.setFlags(messageFlags.getFlagsObject());	
+        	}
+            result -= MessageResult.FLAGS;
+        }
+        if ((result & MessageResult.SIZE) > 0) {
+            messageResult.setSize(messageRow.getSize());
+            result -= MessageResult.SIZE;
+        }
+        if ((result & MessageResult.INTERNAL_DATE) > 0) {
+            messageResult.setInternalDate(messageRow.getInternalDate());
+            result -= MessageResult.INTERNAL_DATE;
+        }
+        if (result != 0) {
+            throw new RuntimeException("Unsupportet result: " + result);
+        }
+        
+        return messageResult;
+    }
+
+
+
+    public synchronized Flags getPermanentFlags() {
+        if (permanentFlags == null) {
+            permanentFlags = new Flags();
+            permanentFlags.add(Flags.Flag.ANSWERED);
+            permanentFlags.add(Flags.Flag.DELETED);
+            permanentFlags.add(Flags.Flag.DRAFT);
+            permanentFlags.add(Flags.Flag.FLAGGED);
+            permanentFlags.add(Flags.Flag.RECENT);
+            permanentFlags.add(Flags.Flag.SEEN);
+        }
+        return permanentFlags;
+    }
+
+    public int getRecentCount(boolean reset) throws MailboxManagerException {
+        checkAccess();
+        Flags flags = new Flags();
+        flags.add(Flags.Flag.RECENT);
+        try {
+            int count = getMailboxRow().countMessages(flags, true);
+            return count;
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        } catch (DataSetException e) {
+            throw new MailboxManagerException(e);
+        }
+
+    }
+
+    public MessageResult getFirstUnseen(int result)
+            throws MailboxManagerException {
+        checkAccess();
+        Criteria c = new Criteria();
+        c.addAscendingOrderByColumn(MessageRowPeer.UID);
+        c.setLimit(1);
+        c.setSingleRecord(true);
+        
+        c.addJoin(MessageFlagsPeer.MAILBOX_ID, MessageRowPeer.MAILBOX_ID);
+        c.addJoin(MessageRowPeer.UID, MessageFlagsPeer.UID);
+        
+        MessageFlagsPeer.addFlagsToCriteria(new Flags(Flags.Flag.SEEN), false,
+                c);
+        
+        try {
+            List messageRows = getMailboxRow().getMessageRows(c);
+            if (messageRows.size() > 0) {
+            	MessageResult messageResult=fillMessageResult((MessageRow) messageRows.get(0), result | MessageResult.UID);
+            	if (messageResult!=null) {
+            		checkForScanGap(messageResult.getUid());
+            		getUidChangeTracker().found(messageResult,null);
+            	}
+            	
+                return messageResult;
+            } else {
+                return null;
+            }
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        } catch (MessagingException e) {
+            throw new MailboxManagerException(e);
+        }
+
+    }
+
+    public int getUnseenCount() throws MailboxManagerException {
+        checkAccess();
+        try {
+            final int count = getMailboxRow().countMessages(new Flags(Flags.Flag.SEEN), false);
+            return count;
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        } catch (DataSetException e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+
+    public MessageResult[] expunge(GeneralMessageSet set, int result)
+            throws MailboxManagerException {
+        checkAccess();
+        try {
+            // TODO put this into a serializable transaction
+            final Criteria c = criteriaForMessageSet(set);
+            c.addJoin(MessageRowPeer.MAILBOX_ID, MessageFlagsPeer.MAILBOX_ID);
+            c.addJoin(MessageRowPeer.UID, MessageFlagsPeer.UID);
+            c.add(MessageRowPeer.MAILBOX_ID, getMailboxRow().getMailboxId());
+            c.add(MessageFlagsPeer.DELETED, true);
+
+            final List messageRows = getMailboxRow().getMessageRows(c);
+            final MessageResult[] messageResults = fillMessageResult(messageRows, result
+                    | MessageResult.UID | MessageResult.FLAGS);
+
+            for (Iterator iter = messageRows.iterator(); iter.hasNext();) {
+                MessageRow messageRow = (MessageRow) iter.next();
+                Criteria todelc=new Criteria();
+                todelc.add(MessageRowPeer.MAILBOX_ID,messageRow.getMailboxId());
+                todelc.add(MessageRowPeer.UID,messageRow.getUid());
+                MessageRowPeer.doDelete(todelc);
+            }
+            getUidChangeTracker().expunged(messageResults);
+            return messageResults;
+        } catch (Exception e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+
+    public void setFlags(Flags flags, boolean value, boolean replace,
+            GeneralMessageSet set, MailboxListener silentListener)
+            throws MailboxManagerException {
+        checkAccess();
+        try {
+        	// TODO put this into a serializeable transaction
+            final List messageRows = getMailboxRow()
+                    .getMessageRows(criteriaForMessageSet(set));
+            final MessageResult[] beforeResults = fillMessageResult(messageRows,
+                    MessageResult.UID | MessageResult.FLAGS);
+            UidRange uidRange=uidRangeForMessageSet(set);
+            checkForScanGap(uidRange.getFromUid());
+            getUidChangeTracker().found(uidRange, beforeResults, null);
+            for (Iterator iter = messageRows.iterator(); iter.hasNext();) {
+                final MessageRow messageRow = (MessageRow) iter.next();
+                final MessageFlags messageFlags = messageRow.getMessageFlags();
+                if (messageFlags != null) {
+					if (replace) {
+						messageFlags.setFlags(flags);
+					} else {
+						Flags current = messageFlags.getFlagsObject();
+						if (value) {
+							current.add(flags);
+						} else {
+							current.remove(flags);
+						}
+						messageFlags.setFlags(current);
+					}
+					messageFlags.save();
+				}
+            }
+            final MessageResult[] afterResults = fillMessageResult(messageRows,
+                    MessageResult.UID | MessageResult.FLAGS);
+            tracker.found(uidRange, afterResults, silentListener);
+        } catch (Exception e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+
+    public void addListener(MailboxListener listener, int result) throws MailboxManagerException {
+        getEventDispatcher().addMailboxListener(listener);
+        checkAccess();
+    }
+
+    public void removeListener(MailboxListener mailboxListener) {
+        if (!open || getEventDispatcher().size() == 0) {
+          throw new RuntimeException("mailbox not open");
+        }
+        getEventDispatcher().removeMailboxListener(mailboxListener);
+        if (getEventDispatcher().size() == 0) {
+            open = false;
+            getUidChangeTracker().removeMailboxListener(getEventDispatcher());
+        }
+    }
+
+    public synchronized long getUidValidity() throws MailboxManagerException {
+        checkAccess();
+        return getMailboxRow().getUidValidity();
+    }
+
+    public synchronized long getUidNext() throws MailboxManagerException {
+		checkAccess();
+		try {
+			MailboxRow myMailboxRow = MailboxRowPeer.retrieveByPK(mailboxRow.getLastUid());
+			if (myMailboxRow != null) {
+				getUidChangeTracker().foundLastUid(mailboxRow.getLastUid());
+				return getUidChangeTracker().getLastUid() + 1;
+			} else {
+				getUidChangeTracker().mailboxNotFound();
+				throw new MailboxManagerException("Mailbox has been deleted");
+			}
+		} catch (NoRowsException e) {
+			throw new MailboxManagerException(e);
+		} catch (TooManyRowsException e) {
+			throw new MailboxManagerException(e);
+		} catch (TorqueException e) {
+			throw new MailboxManagerException(e);
+		}
+	}
+
+    private void checkAccess() throws MailboxManagerException {
+        if (!open) {
+			throw new RuntimeException("mailbox is closed");
+		} else if (getEventDispatcher().size() == 0) {
+			throw new RuntimeException("mailbox has not been opened");
+		} else if (getUidChangeTracker().isExisting()) {
+			throw new MailboxManagerException("Mailbox is not existing");
+		}
+    }
+    
+
+	protected MailboxEventDispatcher getEventDispatcher() {
+    	if (eventDispatcher == null) {
+			eventDispatcher = new MailboxEventDispatcher();
+		}
+		return eventDispatcher;
+    }
+    
+    protected UidChangeTracker getUidChangeTracker() {
+    	return tracker;
+    }
+    
+    protected Log getLog() {
+    	if (log==null) {
+    		log=new SimpleLog("TorqueMailbox");
+    	}
+    	return log;
+    }
+
+	protected MailboxRow getMailboxRow() {
+		return mailboxRow;
+	}
+
+	protected void setMailboxRow(MailboxRow mailboxRow) {
+		this.mailboxRow = mailboxRow;
+	}
+
+	public MessageResult[] search(GeneralMessageSet set, SearchTerm searchTerm, int result) {
+		// TODO Auto-generated method stub
+		return null;
+	}
+
+}

Added: james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManager.java
URL: http://svn.apache.org/viewvc/james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManager.java?view=auto&rev=454432
==============================================================================
--- james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManager.java (added)
+++ james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManager.java Mon Oct  9 10:15:30 2006
@@ -0,0 +1,304 @@
+package org.apache.james.mailboxmanager.torque;
+
+import java.util.Iterator;
+import java.util.List;
+import java.util.Random;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.impl.SimpleLog;
+import org.apache.james.mailboxmanager.GeneralMessageSet;
+import org.apache.james.mailboxmanager.ListResult;
+import org.apache.james.mailboxmanager.MailboxManagerException;
+import org.apache.james.mailboxmanager.MessageResult;
+import org.apache.james.mailboxmanager.Namespace;
+import org.apache.james.mailboxmanager.Namespaces;
+import org.apache.james.mailboxmanager.impl.ListResultImpl;
+import org.apache.james.mailboxmanager.impl.NamespaceImpl;
+import org.apache.james.mailboxmanager.impl.NamespacesImpl;
+import org.apache.james.mailboxmanager.mailbox.GeneralMailbox;
+import org.apache.james.mailboxmanager.mailbox.GeneralMailboxSession;
+import org.apache.james.mailboxmanager.mailbox.ImapMailboxSession;
+import org.apache.james.mailboxmanager.mailbox.MailboxSession;
+import org.apache.james.mailboxmanager.manager.GeneralManager;
+import org.apache.james.mailboxmanager.torque.om.MailboxRow;
+import org.apache.james.mailboxmanager.torque.om.MailboxRowPeer;
+import org.apache.james.mailboxmanager.tracking.MailboxCache;
+import org.apache.james.mailboxmanager.tracking.UidChangeTracker;
+import org.apache.james.mailboxmanager.wrapper.ImapMailboxSessionWrapper;
+import org.apache.james.services.User;
+import org.apache.torque.TorqueException;
+import org.apache.torque.util.CountHelper;
+import org.apache.torque.util.Criteria;
+
+public class TorqueMailboxManager implements GeneralManager {
+    
+    public static final char HIERARCHY_DELIMITER='.';
+    
+    public static final String USER_NAMESPACE="#mail";
+
+    private static Random random;
+    private MailboxCache mailboxCache;
+
+    private User authUser;
+    
+    protected Log log;
+
+    public TorqueMailboxManager(User authUser, MailboxCache mailboxCache, Log log) {
+        this.mailboxCache=mailboxCache;
+        this.authUser=authUser;
+        this.log=log;
+    }
+    
+    public MailboxSession getMailboxSession(String mailboxName, Class neededInterface, int[] setTypes,int resultTypes)
+    throws MailboxManagerException {
+    	return getGenericImapMailboxSession(mailboxName);
+    }
+
+    public GeneralMailboxSession getGenericGeneralMailboxSession(String mailboxName)
+    throws MailboxManagerException {
+    	return getGenericImapMailboxSession(mailboxName);
+    }
+    
+    public ImapMailboxSession getGenericImapMailboxSession(String mailboxName)
+            throws MailboxManagerException {
+    	
+    	// prepare to auto-create users Inbox
+    	
+    	// TODO inbox-auto-creation for authUser is not optimal. Use a autocreate boolean in getSessionMailbox?
+        String userInbox=getPersonalDefaultNamespace(authUser).getName()+HIERARCHY_DELIMITER+"INBOX";
+        if (userInbox.length()==mailboxName.length()) {
+            int del=userInbox.length()-5;
+            if (userInbox.substring(0,del).equals(mailboxName.substring(0,del))) {
+                if (userInbox.substring(del).equalsIgnoreCase(mailboxName.substring(del))) {
+                    mailboxName=userInbox;
+                }
+            }
+        }
+
+        try {
+            synchronized (getMailboxCache()) {
+				MailboxRow mailboxRow = MailboxRowPeer
+						.retrieveByName(mailboxName);
+				if (mailboxRow == null) {
+					if (userInbox.equals(mailboxName)) {
+						// do auto creation
+						createMailbox(mailboxName);
+						mailboxRow = MailboxRowPeer.retrieveByName(mailboxName);
+						getLog().info("autocreated Inbox  " + mailboxName);
+					}
+				}
+
+				if (mailboxRow != null) {
+					UidChangeTracker tracker = (UidChangeTracker) getMailboxCache()
+							.getMailboxTracker(mailboxName,
+									UidChangeTracker.class);
+					if (tracker == null) {
+						tracker = new UidChangeTracker(getMailboxCache(),
+								mailboxName, mailboxRow.getLastUid());
+						getMailboxCache().add(mailboxName, tracker);
+					}
+					getLog().info("created ImapMailboxSession "+mailboxName);
+					return new ImapMailboxSessionWrapper(new TorqueMailbox(
+							mailboxRow, tracker,getLog()));
+				} else {
+					getLog().info("Mailbox '" + mailboxName + "' not found.");
+					getMailboxCache().notFound(mailboxName);
+					throw new MailboxManagerException("Mailbox '" + mailboxName
+							+ "' not found.");
+				}
+			}
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+    
+    private MailboxCache getMailboxCache() {
+       return mailboxCache;
+    }
+    
+    public Namespaces getNamespaces(User forUser) {
+    	NamespacesImpl nameSpaces=new NamespacesImpl();
+    	nameSpaces.setShared(new Namespace[0]);
+    	Namespace userNamespace=new NamespaceImpl(""+HIERARCHY_DELIMITER,USER_NAMESPACE);
+    	nameSpaces.setUser(new Namespace[] {userNamespace}); 
+    	Namespace personalDefault = getPersonalDefaultNamespace(forUser);
+    	nameSpaces.setPersonal(new Namespace[] {personalDefault}); 
+    	nameSpaces.setPersonalDefault(personalDefault);
+        return nameSpaces;
+    }
+
+    public Namespace getPersonalDefaultNamespace(User forUser) {
+        return new NamespaceImpl("" + HIERARCHY_DELIMITER,USER_NAMESPACE+HIERARCHY_DELIMITER+forUser.getUserName());
+    }
+
+    public void createMailbox(String namespaceName)
+			throws MailboxManagerException {
+    	getLog().info("createMailbox "+namespaceName);
+		synchronized (getMailboxCache()) {
+			MailboxRow mr = new MailboxRow();
+			mr.setName(namespaceName);
+			mr.setLastUid(0);
+			mr.setUidValidity(Math.abs(getRandom().nextInt()));
+			try {
+				mr.save();
+			} catch (Exception e) {
+				throw new MailboxManagerException(e);
+			}
+		}
+	}
+
+    public void deleteMailbox(String mailboxName)
+            throws MailboxManagerException {
+    	getLog().info("deleteMailbox "+mailboxName);
+    	synchronized (getMailboxCache()) {
+			try {
+				// TODO put this into a serilizable transaction
+				MailboxRow mr = MailboxRowPeer.retrieveByName(mailboxName);
+				if (mr == null) {
+					throw new MailboxManagerException("Mailbox not found");
+				}
+				MailboxRowPeer.doDelete(mr);
+				getMailboxCache().notFound(mailboxName);
+			} catch (TorqueException e) {
+				throw new MailboxManagerException(e);
+			}
+		}
+    }
+
+    public void renameMailbox(String from, String to)
+            throws MailboxManagerException {
+        try {
+        	getLog().info("renameMailbox "+from+" to "+to);
+        	synchronized (getMailboxCache()) {
+				// TODO put this into a serilizable transaction
+				MailboxRow mr = MailboxRowPeer.retrieveByName(from);
+				if (mr == null) {
+					throw new MailboxManagerException("Mailbox not found");
+				}
+				mr.setName(to);
+				mr.save();
+				
+				// rename submailbox
+				
+				Criteria c = new Criteria();
+				c.add(MailboxRowPeer.NAME,
+						(Object) (from + HIERARCHY_DELIMITER + "%"),
+						Criteria.LIKE);
+				List l = MailboxRowPeer.doSelect(c);
+				for (Iterator iter = l.iterator(); iter.hasNext();) {
+					MailboxRow sub = (MailboxRow) iter.next();
+					String subOrigName=sub.getName();
+					String subNewName=to + subOrigName.substring(from.length());
+					sub.setName(to + sub.getName().substring(from.length()));
+					sub.save();
+					getLog().info("renameMailbox sub-mailbox "+subOrigName+" to "+subNewName);
+					getMailboxCache().renamed(subOrigName,subNewName);
+				}
+			}
+        } catch (Exception e) {
+            throw new MailboxManagerException(e);
+        }
+
+    }
+
+    public void copyMessages(GeneralMailbox from, GeneralMessageSet set, String to) throws MailboxManagerException {
+        GeneralMailboxSession toMailbox=(GeneralMailboxSession)getMailboxSession(to,GeneralMailboxSession.class, new int[0],MessageResult.NOTHING);
+        
+        MessageResult[] mr=from.getMessages(set, MessageResult.MIME_MESSAGE | MessageResult.INTERNAL_DATE);
+        for (int i = 0; i < mr.length; i++) {
+            toMailbox.appendMessage(mr[i].getMimeMessage(), mr[i].getInternalDate(), MessageResult.NOTHING);
+        }
+       
+        toMailbox.close();
+    }
+
+    public ListResult[] list(String base, String expression, boolean subscribed) throws MailboxManagerException {
+        Criteria c=new Criteria();
+        if (base.length()>0) {
+            if (base.charAt(base.length()-1)==HIERARCHY_DELIMITER) {
+                base=base.substring(0, base.length()-1);
+            }
+            if (expression.length()>0) {
+                if (expression.charAt(0)==HIERARCHY_DELIMITER) {
+                    expression=base+expression;
+                } else {
+                    expression=base+HIERARCHY_DELIMITER+expression;
+                }
+            }
+        }
+        
+        // TODO handling of expressions is limited
+        
+        expression.replaceAll("\\*","%");
+        c.add(MailboxRowPeer.NAME,(Object)(expression),Criteria.LIKE);
+        try {
+            List mailboxRows=MailboxRowPeer.doSelect(c);
+            ListResult[] listResults=new ListResult[mailboxRows.size()];
+            int i=0;
+            for (Iterator iter = mailboxRows.iterator(); iter.hasNext();) {
+                MailboxRow mailboxRow = (MailboxRow) iter.next();
+                listResults[i++]=new ListResultImpl(mailboxRow.getName(),".");
+            }
+            return listResults;    
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        }
+        
+    }
+    
+    public void setSubscription(String mailboxName, boolean value) {
+    	// TODO implement subscriptions
+    }
+
+    protected static Random getRandom() {
+        if (random == null) {
+            random = new Random();
+        }
+        return random;
+    }
+
+    public boolean existsMailbox(String mailboxName) throws MailboxManagerException {
+        Criteria c=new Criteria();
+        c.add(MailboxRowPeer.NAME,mailboxName);
+        CountHelper countHelper=new CountHelper();
+        int count;
+        try {
+        	synchronized (getMailboxCache()) {
+				count = countHelper.count(c);
+				if (count == 0) {
+					getMailboxCache().notFound(mailboxName);
+					return false;
+				} else {
+					if (count == 1) {
+						return true;
+					} else {
+						throw new MailboxManagerException("found " + count
+								+ " mailboxes");
+					}
+				}
+			}
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+
+    public void close() {
+    }
+
+    public void deleteEverything() throws MailboxManagerException {
+        try {
+            MailboxRowPeer.doDelete(new Criteria().and(MailboxRowPeer.MAILBOX_ID,
+                    new Integer(-1), Criteria.GREATER_THAN));
+        } catch (TorqueException e) {
+            throw new MailboxManagerException(e);
+        }
+    }
+    
+    protected Log getLog() {
+    	if (log==null) {
+    		log=new SimpleLog("TorqueMailboxManager");
+    	}
+    	return log;
+    }
+
+}

Added: james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManagerProvider.java
URL: http://svn.apache.org/viewvc/james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManagerProvider.java?view=auto&rev=454432
==============================================================================
--- james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManagerProvider.java (added)
+++ james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMailboxManagerProvider.java Mon Oct  9 10:15:30 2006
@@ -0,0 +1,192 @@
+package org.apache.james.mailboxmanager.torque;
+
+import java.io.File;
+import java.sql.Connection;
+import java.sql.DatabaseMetaData;
+import java.sql.ResultSet;
+import java.sql.SQLException;
+import java.util.HashMap;
+import java.util.Locale;
+
+import org.apache.avalon.framework.activity.Initializable;
+import org.apache.avalon.framework.configuration.Configurable;
+import org.apache.avalon.framework.configuration.ConfigurationException;
+import org.apache.avalon.framework.logger.LogEnabled;
+import org.apache.avalon.framework.logger.Logger;
+import org.apache.commons.configuration.BaseConfiguration;
+import org.apache.commons.configuration.PropertiesConfiguration;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.impl.AvalonLogger;
+import org.apache.commons.logging.impl.SimpleLog;
+import org.apache.james.mailboxmanager.MailboxManagerException;
+import org.apache.james.mailboxmanager.manager.GeneralManager;
+import org.apache.james.mailboxmanager.manager.MailboxManager;
+import org.apache.james.mailboxmanager.manager.MailboxManagerProvider;
+import org.apache.james.mailboxmanager.torque.om.MailboxRowPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageBodyPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageFlagsPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageHeaderPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageRowPeer;
+import org.apache.james.mailboxmanager.tracking.MailboxCache;
+import org.apache.james.mailboxmanager.util.SqlResources;
+import org.apache.james.services.User;
+import org.apache.torque.Torque;
+import org.apache.torque.TorqueException;
+import org.apache.torque.util.BasePeer;
+import org.apache.torque.util.Transaction;
+
+public class TorqueMailboxManagerProvider implements MailboxManagerProvider, Initializable, Configurable, LogEnabled  {
+
+    private MailboxCache mailboxCache;
+
+    private BaseConfiguration torqueConf;
+    
+    private boolean initialized;
+
+	private Log log;
+
+    private static final String[] tableNames= new String[] {MailboxRowPeer.TABLE_NAME,MessageRowPeer.TABLE_NAME,MessageHeaderPeer.TABLE_NAME,MessageBodyPeer.TABLE_NAME,MessageFlagsPeer.TABLE_NAME};
+
+    public MailboxManager getMailboxManagerInstance(User user,Class neededClass)
+            throws MailboxManagerException {
+     return getGeneralManagerInstance(user);
+    }
+	public GeneralManager getGeneralManagerInstance(User user)             throws MailboxManagerException {
+        if (!initialized)  {
+            throw new MailboxManagerException("must be initialized first!");
+        }
+        return new TorqueMailboxManager(user, getMailboxCache(),getLog());
+	}
+    public void initialize() throws Exception {
+        if (!initialized) {
+            if (torqueConf==null) {
+                throw new RuntimeException("must be configured first!");
+            }
+            if (Torque.isInit()) {
+                throw new RuntimeException("Torque is already initialized!");
+            }
+            Connection conn= null;
+            try {
+                Torque.init(torqueConf);
+                conn=Transaction.begin(MailboxRowPeer.DATABASE_NAME);
+                SqlResources sqlResources=new SqlResources();
+                sqlResources.init(getClass().getResource("/mailboxManagerSql.xml"), getClass().getCanonicalName(), conn, new HashMap());
+
+                DatabaseMetaData dbMetaData=conn.getMetaData();
+                
+                for (int i = 0; i < tableNames.length; i++) {
+                    if (!tableExists(dbMetaData, tableNames[i])) {
+                        BasePeer.executeStatement(sqlResources.getSqlString("createTable_"+tableNames[i]),conn);
+                        System.out.println("Created table "+tableNames[i]);
+                        getLog().info("Created table "+tableNames[i]);
+                     }                    
+                }
+
+                Transaction.commit(conn);
+                initialized=true;
+                System.out.println("MailboxManager has been initialized");
+                getLog().info("MailboxManager has been initialized");
+            } catch (Exception e) {
+                Transaction.safeRollback(conn);
+                try {
+                    Torque.shutdown();
+                } catch (TorqueException e1) {
+                }  
+                throw new MailboxManagerException(e);
+            } 
+        }
+    }
+    
+    public void configureDefaults()
+			throws org.apache.commons.configuration.ConfigurationException {
+		File configFile = new File("torque.properties");
+		if (configFile.canRead()) {
+			torqueConf = new PropertiesConfiguration(configFile);
+		} else {
+			torqueConf = new BaseConfiguration();
+			torqueConf.addProperty("torque.database.default", "mailboxmanager");
+			torqueConf.addProperty("torque.database.mailboxmanager.adapter",
+					"derby");
+			torqueConf.addProperty("torque.dsfactory.mailboxmanager.factory",
+					"org.apache.torque.dsfactory.SharedPoolDataSourceFactory");
+			torqueConf.addProperty(
+					"torque.dsfactory.mailboxmanager.connection.driver",
+					"org.apache.derby.jdbc.EmbeddedDriver");
+			torqueConf.addProperty(
+					"torque.dsfactory.mailboxmanager.connection.url",
+					"jdbc:derby:derby;create=true");
+			torqueConf.addProperty(
+					"torque.dsfactory.mailboxmanager.connection.user", "app");
+			torqueConf.addProperty(
+					"torque.dsfactory.mailboxmanager.connection.password",
+					"app");
+			torqueConf.addProperty(
+					"torque.dsfactory.mailboxmanager.pool.maxActive", "100");
+		}
+	}
+
+    public void configure(org.apache.avalon.framework.configuration.Configuration conf) throws ConfigurationException {
+        torqueConf=new BaseConfiguration();
+        org.apache.avalon.framework.configuration.Configuration[] tps=conf.getChild("torque-properties").getChildren("property");
+        for (int i = 0; i < tps.length; i++) {
+            torqueConf.addProperty(tps[i].getAttribute("name"), tps[i].getAttribute("value"));
+        }
+    }
+
+
+    private boolean tableExists(DatabaseMetaData dbMetaData, String tableName)
+            throws SQLException {
+        return (tableExistsCaseSensitive(dbMetaData, tableName)
+                || tableExistsCaseSensitive(dbMetaData, tableName
+                        .toUpperCase(Locale.US)) || tableExistsCaseSensitive(
+                dbMetaData, tableName.toLowerCase(Locale.US)));
+    }
+
+    private boolean tableExistsCaseSensitive(DatabaseMetaData dbMetaData,
+            String tableName) throws SQLException {
+        ResultSet rsTables = dbMetaData.getTables(null, null, tableName, null);
+        try {
+            boolean found = rsTables.next();
+            return found;
+        } finally {
+            if (rsTables != null) {
+                rsTables.close();
+            }
+        }
+    }
+
+    private MailboxCache getMailboxCache() {
+        if (mailboxCache == null) {
+            mailboxCache = new MailboxCache();
+        }
+        return mailboxCache;
+    }
+
+    public void deleteEverything() throws MailboxManagerException {
+        ((TorqueMailboxManager) getMailboxManagerInstance(null,TorqueMailboxManager.class))
+                .deleteEverything();
+        mailboxCache=null;
+    }
+
+    public boolean isInitialized() {
+        return initialized;
+    }
+
+    public String toString() {
+    	return "TorqueMailboxManagerProvider";
+    }
+
+
+    protected Log getLog() {
+    	if (log == null) {
+			log = new SimpleLog("TorqueMailboxManagerProvider");
+		}
+		return log;
+    }
+	public void enableLogging(Logger logger) {
+		log=new AvalonLogger(logger);
+		
+	}
+    
+
+}

Added: james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMimeMessage.java
URL: http://svn.apache.org/viewvc/james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMimeMessage.java?view=auto&rev=454432
==============================================================================
--- james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMimeMessage.java (added)
+++ james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/TorqueMimeMessage.java Mon Oct  9 10:15:30 2006
@@ -0,0 +1,81 @@
+package org.apache.james.mailboxmanager.torque;
+
+import java.util.Iterator;
+import java.util.List;
+
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.commons.logging.Log;
+import org.apache.james.mailboxmanager.torque.om.MessageBody;
+import org.apache.james.mailboxmanager.torque.om.MessageFlags;
+import org.apache.james.mailboxmanager.torque.om.MessageHeader;
+import org.apache.james.mailboxmanager.torque.om.MessageHeaderPeer;
+import org.apache.james.mailboxmanager.torque.om.MessageRow;
+import org.apache.torque.TorqueException;
+import org.apache.torque.util.Criteria;
+
+public class TorqueMimeMessage extends MimeMessage {
+
+    private int size;
+
+    private TorqueMimeMessage() {
+        super((Session)null);
+
+    }
+    
+    public int getSize() throws MessagingException {
+        return size;
+    }
+    
+    
+    /**
+     * will not throw an exception when the message gets deleted in the meantime so result maybe incomplete. 
+     * 
+     * @param messageRow
+     * @param log
+     * @return
+     * @throws TorqueException
+     * @throws MessagingException
+     */
+    
+    public static TorqueMimeMessage createMessage(MessageRow messageRow, Log log) throws TorqueException, MessagingException {
+        
+        TorqueMimeMessage tmm=new TorqueMimeMessage();
+        
+        List headers=messageRow.getMessageHeaders(new Criteria().addAscendingOrderByColumn(MessageHeaderPeer.LINE_NUMBER));
+        tmm.content=((MessageBody)messageRow.getMessageBodys().get(0)).getBody();
+        tmm.size=messageRow.getSize();
+        
+        String messageIdName=null;
+        String messageIdValue=null;
+        for (Iterator iter = headers.iterator(); iter.hasNext();) {
+            MessageHeader header = (MessageHeader) iter.next();
+            if ("message-id".equals(header.getField().toLowerCase())) {
+                messageIdName=header.getField();
+                messageIdValue=header.getValue();
+            } else {
+                tmm.addHeader(header.getField(),header.getValue());    
+            }
+        }
+        
+        // null-safe flags setup
+        
+        MessageFlags messageFlags=messageRow.getMessageFlags();
+        if (messageFlags != null) {
+			tmm.setFlags(messageRow.getMessageFlags().getFlagsObject(), true);
+		}
+
+        
+        // save and reset the message-id
+        tmm.saveChanges();
+        if (messageIdName!=null) {
+            tmm.setHeader(messageIdName,messageIdValue);
+        }
+
+        return tmm;
+    }
+    
+    
+}

Added: james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/om/BaseMailboxRow.java
URL: http://svn.apache.org/viewvc/james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/om/BaseMailboxRow.java?view=auto&rev=454432
==============================================================================
--- james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/om/BaseMailboxRow.java (added)
+++ james/server/sandbox/imap-integration/src/java/org/apache/james/mailboxmanager/torque/om/BaseMailboxRow.java Mon Oct  9 10:15:30 2006
@@ -0,0 +1,787 @@
+package org.apache.james.mailboxmanager.torque.om;
+
+
+import java.math.BigDecimal;
+import java.sql.Connection;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+
+import org.apache.commons.lang.ObjectUtils;
+import org.apache.torque.TorqueException;
+import org.apache.torque.om.BaseObject;
+import org.apache.torque.om.ComboKey;
+import org.apache.torque.om.DateKey;
+import org.apache.torque.om.NumberKey;
+import org.apache.torque.om.ObjectKey;
+import org.apache.torque.om.SimpleKey;
+import org.apache.torque.om.StringKey;
+import org.apache.torque.om.Persistent;
+import org.apache.torque.util.Criteria;
+import org.apache.torque.util.Transaction;
+
+
+
+            
+
+/**
+ * This class was autogenerated by Torque on:
+ *
+ * [Tue Sep 19 10:06:28 CEST 2006]
+ *
+ * You should not use this class directly.  It should not even be
+ * extended all references should be to MailboxRow
+ */
+public abstract class BaseMailboxRow extends BaseObject
+{
+    /** The Peer class */
+    private static final MailboxRowPeer peer =
+        new MailboxRowPeer();
+
+        
+    /** The value for the mailboxId field */
+    private long mailboxId;
+      
+    /** The value for the name field */
+    private String name;
+      
+    /** The value for the uidValidity field */
+    private long uidValidity;
+      
+    /** The value for the lastUid field */
+    private long lastUid;
+                                          
+    /** The value for the messageCount field */
+    private int messageCount = 0;
+                                          
+    /** The value for the size field */
+    private long size = 0;
+  
+            
+    /**
+     * Get the MailboxId
+     *
+     * @return long
+     */
+    public long getMailboxId()
+    {
+        return mailboxId;
+    }
+
+                                              
+    /**
+     * Set the value of MailboxId
+     *
+     * @param v new value
+     */
+    public void setMailboxId(long v) throws TorqueException
+    {
+    
+                  if (this.mailboxId != v)
+              {
+            this.mailboxId = v;
+            setModified(true);
+        }
+    
+          
+                                  
+                  // update associated MessageRow
+        if (collMessageRows != null)
+        {
+            for (int i = 0; i < collMessageRows.size(); i++)
+            {
+                ((MessageRow) collMessageRows.get(i))
+                    .setMailboxId(v);
+            }
+        }
+                                }
+          
+    /**
+     * Get the Name
+     *
+     * @return String
+     */
+    public String getName()
+    {
+        return name;
+    }
+
+                        
+    /**
+     * Set the value of Name
+     *
+     * @param v new value
+     */
+    public void setName(String v) 
+    {
+    
+                  if (!ObjectUtils.equals(this.name, v))
+              {
+            this.name = v;
+            setModified(true);
+        }
+    
+          
+              }
+          
+    /**
+     * Get the UidValidity
+     *
+     * @return long
+     */
+    public long getUidValidity()
+    {
+        return uidValidity;
+    }
+
+                        
+    /**
+     * Set the value of UidValidity
+     *
+     * @param v new value
+     */
+    public void setUidValidity(long v) 
+    {
+    
+                  if (this.uidValidity != v)
+              {
+            this.uidValidity = v;
+            setModified(true);
+        }
+    
+          
+              }
+          
+    /**
+     * Get the LastUid
+     *
+     * @return long
+     */
+    public long getLastUid()
+    {
+        return lastUid;
+    }
+
+                        
+    /**
+     * Set the value of LastUid
+     *
+     * @param v new value
+     */
+    public void setLastUid(long v) 
+    {
+    
+                  if (this.lastUid != v)
+              {
+            this.lastUid = v;
+            setModified(true);
+        }
+    
+          
+              }
+          
+    /**
+     * Get the MessageCount
+     *
+     * @return int
+     */
+    public int getMessageCount()
+    {
+        return messageCount;
+    }
+
+                        
+    /**
+     * Set the value of MessageCount
+     *
+     * @param v new value
+     */
+    public void setMessageCount(int v) 
+    {
+    
+                  if (this.messageCount != v)
+              {
+            this.messageCount = v;
+            setModified(true);
+        }
+    
+          
+              }
+          
+    /**
+     * Get the Size
+     *
+     * @return long
+     */
+    public long getSize()
+    {
+        return size;
+    }
+
+                        
+    /**
+     * Set the value of Size
+     *
+     * @param v new value
+     */
+    public void setSize(long v) 
+    {
+    
+                  if (this.size != v)
+              {
+            this.size = v;
+            setModified(true);
+        }
+    
+          
+              }
+  
+         
+                                
+            
+          /**
+     * Collection to store aggregation of collMessageRows
+     */
+    protected List collMessageRows;
+
+    /**
+     * Temporary storage of collMessageRows to save a possible db hit in
+     * the event objects are add to the collection, but the
+     * complete collection is never requested.
+     */
+    protected void initMessageRows()
+    {
+        if (collMessageRows == null)
+        {
+            collMessageRows = new ArrayList();
+        }
+    }
+
+        
+    /**
+     * Method called to associate a MessageRow object to this object
+     * through the MessageRow foreign key attribute
+     *
+     * @param l MessageRow
+     * @throws TorqueException
+     */
+    public void addMessageRow(MessageRow l) throws TorqueException
+    {
+        getMessageRows().add(l);
+        l.setMailboxRow((MailboxRow) this);
+    }
+
+    /**
+     * The criteria used to select the current contents of collMessageRows
+     */
+    private Criteria lastMessageRowsCriteria = null;
+      
+    /**
+                   * If this collection has already been initialized, returns
+     * the collection. Otherwise returns the results of
+     * getMessageRows(new Criteria())
+                   *
+     * @return the collection of associated objects
+           * @throws TorqueException
+           */
+    public List getMessageRows()
+              throws TorqueException
+          {
+                      if (collMessageRows == null)
+        {
+            collMessageRows = getMessageRows(new Criteria(10));
+        }
+                return collMessageRows;
+          }
+
+    /**
+           * If this collection has already been initialized with
+     * an identical criteria, it returns the collection.
+     * Otherwise if this MailboxRow has previously
+           * been saved, it will retrieve related MessageRows from storage.
+     * If this MailboxRow is new, it will return
+     * an empty collection or the current collection, the criteria
+     * is ignored on a new object.
+     *
+     * @throws TorqueException
+     */
+    public List getMessageRows(Criteria criteria) throws TorqueException
+    {
+              if (collMessageRows == null)
+        {
+            if (isNew())
+            {
+               collMessageRows = new ArrayList();
+            }
+            else
+            {
+                        criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId() );
+                        collMessageRows = MessageRowPeer.doSelect(criteria);
+            }
+        }
+        else
+        {
+            // criteria has no effect for a new object
+            if (!isNew())
+            {
+                // the following code is to determine if a new query is
+                // called for.  If the criteria is the same as the last
+                // one, just return the collection.
+                            criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId());
+                            if (!lastMessageRowsCriteria.equals(criteria))
+                {
+                    collMessageRows = MessageRowPeer.doSelect(criteria);
+                }
+            }
+        }
+        lastMessageRowsCriteria = criteria;
+
+        return collMessageRows;
+          }
+
+    /**
+           * If this collection has already been initialized, returns
+     * the collection. Otherwise returns the results of
+     * getMessageRows(new Criteria(),Connection)
+           * This method takes in the Connection also as input so that
+     * referenced objects can also be obtained using a Connection
+     * that is taken as input
+     */
+    public List getMessageRows(Connection con) throws TorqueException
+    {
+              if (collMessageRows == null)
+        {
+            collMessageRows = getMessageRows(new Criteria(10), con);
+        }
+        return collMessageRows;
+          }
+
+    /**
+           * If this collection has already been initialized with
+     * an identical criteria, it returns the collection.
+     * Otherwise if this MailboxRow has previously
+           * been saved, it will retrieve related MessageRows from storage.
+     * If this MailboxRow is new, it will return
+     * an empty collection or the current collection, the criteria
+     * is ignored on a new object.
+     * This method takes in the Connection also as input so that
+     * referenced objects can also be obtained using a Connection
+     * that is taken as input
+     */
+    public List getMessageRows(Criteria criteria, Connection con)
+            throws TorqueException
+    {
+              if (collMessageRows == null)
+        {
+            if (isNew())
+            {
+               collMessageRows = new ArrayList();
+            }
+            else
+            {
+                         criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId());
+                         collMessageRows = MessageRowPeer.doSelect(criteria, con);
+             }
+         }
+         else
+         {
+             // criteria has no effect for a new object
+             if (!isNew())
+             {
+                 // the following code is to determine if a new query is
+                 // called for.  If the criteria is the same as the last
+                 // one, just return the collection.
+                             criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId());
+                             if (!lastMessageRowsCriteria.equals(criteria))
+                 {
+                     collMessageRows = MessageRowPeer.doSelect(criteria, con);
+                 }
+             }
+         }
+         lastMessageRowsCriteria = criteria;
+
+         return collMessageRows;
+           }
+
+                  
+              
+                    
+                              
+                                
+                                                              
+                                        
+                    
+                    
+          
+    /**
+                 * If this collection has already been initialized with
+     * an identical criteria, it returns the collection.
+     * Otherwise if this MailboxRow is new, it will return
+                 * an empty collection; or if this MailboxRow has previously
+     * been saved, it will retrieve related MessageRows from storage.
+     *
+     * This method is protected by default in order to keep the public
+     * api reasonable.  You can provide public methods for those you
+     * actually need in MailboxRow.
+     */
+    protected List getMessageRowsJoinMailboxRow(Criteria criteria)
+        throws TorqueException
+    {
+                    if (collMessageRows == null)
+        {
+            if (isNew())
+            {
+               collMessageRows = new ArrayList();
+            }
+            else
+            {
+                              criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId());
+                              collMessageRows = MessageRowPeer.doSelectJoinMailboxRow(criteria);
+            }
+        }
+        else
+        {
+            // the following code is to determine if a new query is
+            // called for.  If the criteria is the same as the last
+            // one, just return the collection.
+                                    criteria.add(MessageRowPeer.MAILBOX_ID, getMailboxId());
+                                    if (!lastMessageRowsCriteria.equals(criteria))
+            {
+                collMessageRows = MessageRowPeer.doSelectJoinMailboxRow(criteria);
+            }
+        }
+        lastMessageRowsCriteria = criteria;
+
+        return collMessageRows;
+                }
+                            
+
+
+          
+    private static List fieldNames = null;
+
+    /**
+     * Generate a list of field names.
+     *
+     * @return a list of field names
+     */
+    public static synchronized List getFieldNames()
+    {
+        if (fieldNames == null)
+        {
+            fieldNames = new ArrayList();
+              fieldNames.add("MailboxId");
+              fieldNames.add("Name");
+              fieldNames.add("UidValidity");
+              fieldNames.add("LastUid");
+              fieldNames.add("MessageCount");
+              fieldNames.add("Size");
+              fieldNames = Collections.unmodifiableList(fieldNames);
+        }
+        return fieldNames;
+    }
+
+    /**
+     * Retrieves a field from the object by name passed in as a String.
+     *
+     * @param name field name
+     * @return value
+     */
+    public Object getByName(String name)
+    {
+          if (name.equals("MailboxId"))
+        {
+                return new Long(getMailboxId());
+            }
+          if (name.equals("Name"))
+        {
+                return getName();
+            }
+          if (name.equals("UidValidity"))
+        {
+                return new Long(getUidValidity());
+            }
+          if (name.equals("LastUid"))
+        {
+                return new Long(getLastUid());
+            }
+          if (name.equals("MessageCount"))
+        {
+                return new Integer(getMessageCount());
+            }
+          if (name.equals("Size"))
+        {
+                return new Long(getSize());
+            }
+          return null;
+    }
+
+    /**
+     * Retrieves a field from the object by name passed in
+     * as a String.  The String must be one of the static
+     * Strings defined in this Class' Peer.
+     *
+     * @param name peer name
+     * @return value
+     */
+    public Object getByPeerName(String name)
+    {
+          if (name.equals(MailboxRowPeer.MAILBOX_ID))
+        {
+                return new Long(getMailboxId());
+            }
+          if (name.equals(MailboxRowPeer.NAME))
+        {
+                return getName();
+            }
+          if (name.equals(MailboxRowPeer.UID_VALIDITY))
+        {
+                return new Long(getUidValidity());
+            }
+          if (name.equals(MailboxRowPeer.LAST_UID))
+        {
+                return new Long(getLastUid());
+            }
+          if (name.equals(MailboxRowPeer.MESSAGE_COUNT))
+        {
+                return new Integer(getMessageCount());
+            }
+          if (name.equals(MailboxRowPeer.SIZE))
+        {
+                return new Long(getSize());
+            }
+          return null;
+    }
+
+    /**
+     * Retrieves a field from the object by Position as specified
+     * in the xml schema.  Zero-based.
+     *
+     * @param pos position in xml schema
+     * @return value
+     */
+    public Object getByPosition(int pos)
+    {
+            if (pos == 0)
+        {
+                return new Long(getMailboxId());
+            }
+              if (pos == 1)
+        {
+                return getName();
+            }
+              if (pos == 2)
+        {
+                return new Long(getUidValidity());
+            }
+              if (pos == 3)
+        {
+                return new Long(getLastUid());
+            }
+              if (pos == 4)
+        {
+                return new Integer(getMessageCount());
+            }
+              if (pos == 5)
+        {
+                return new Long(getSize());
+            }
+              return null;
+    }
+     
+    /**
+     * Stores the object in the database.  If the object is new,
+     * it inserts it; otherwise an update is performed.
+     *
+     * @throws Exception
+     */
+    public void save() throws Exception
+    {
+          save(MailboxRowPeer.getMapBuilder()
+                .getDatabaseMap().getName());
+      }
+
+    /**
+     * Stores the object in the database.  If the object is new,
+     * it inserts it; otherwise an update is performed.
+       * Note: this code is here because the method body is
+     * auto-generated conditionally and therefore needs to be
+     * in this file instead of in the super class, BaseObject.
+       *
+     * @param dbName
+     * @throws TorqueException
+     */
+    public void save(String dbName) throws TorqueException
+    {
+        Connection con = null;
+          try
+        {
+            con = Transaction.begin(dbName);
+            save(con);
+            Transaction.commit(con);
+        }
+        catch(TorqueException e)
+        {
+            Transaction.safeRollback(con);
+            throw e;
+        }
+      }
+
+      /** flag to prevent endless save loop, if this object is referenced
+        by another object which falls in this transaction. */
+    private boolean alreadyInSave = false;
+      /**
+     * Stores the object in the database.  If the object is new,
+     * it inserts it; otherwise an update is performed.  This method
+     * is meant to be used as part of a transaction, otherwise use
+     * the save() method and the connection details will be handled
+     * internally
+     *
+     * @param con
+     * @throws TorqueException
+     */
+    public void save(Connection con) throws TorqueException
+    {
+          if (!alreadyInSave)
+        {
+            alreadyInSave = true;
+
+
+  
+            // If this object has been modified, then save it to the database.
+            if (isModified())
+            {
+                if (isNew())
+                {
+                    MailboxRowPeer.doInsert((MailboxRow) this, con);
+                    setNew(false);
+                }
+                else
+                {
+                    MailboxRowPeer.doUpdate((MailboxRow) this, con);
+                }
+                }
+
+                                      
+                                    if (collMessageRows != null)
+            {
+                for (int i = 0; i < collMessageRows.size(); i++)
+                {
+                    ((MessageRow) collMessageRows.get(i)).save(con);
+                }
+            }
+                                  alreadyInSave = false;
+        }
+      }
+
+                        
+      /**
+     * Set the PrimaryKey using ObjectKey.
+     *
+     * @param key mailboxId ObjectKey
+     */
+    public void setPrimaryKey(ObjectKey key)
+        throws TorqueException
+    {
+            setMailboxId(((NumberKey) key).longValue());
+        }
+
+    /**
+     * Set the PrimaryKey using a String.
+     *
+     * @param key
+     */
+    public void setPrimaryKey(String key) throws TorqueException
+    {
+            setMailboxId(Long.parseLong(key));
+        }
+
+  
+    /**
+     * returns an id that differentiates this object from others
+     * of its class.
+     */
+    public ObjectKey getPrimaryKey()
+    {
+          return SimpleKey.keyFor(getMailboxId());
+      }
+ 
+
+    /**
+     * Makes a copy of this object.
+     * It creates a new object filling in the simple attributes.
+       * It then fills all the association collections and sets the
+     * related objects to isNew=true.
+       */
+      public MailboxRow copy() throws TorqueException
+    {
+        return copyInto(new MailboxRow());
+    }
+  
+    protected MailboxRow copyInto(MailboxRow copyObj) throws TorqueException
+    {
+          copyObj.setMailboxId(mailboxId);
+          copyObj.setName(name);
+          copyObj.setUidValidity(uidValidity);
+          copyObj.setLastUid(lastUid);
+          copyObj.setMessageCount(messageCount);
+          copyObj.setSize(size);
+  
+                            copyObj.setMailboxId( 0);
+                                          
+                                      
+                            
+        List v = getMessageRows();
+                            if (v != null)
+        {
+            for (int i = 0; i < v.size(); i++)
+            {
+                MessageRow obj = (MessageRow) v.get(i);
+                copyObj.addMessageRow(obj.copy());
+            }
+        }
+        else
+        {
+            copyObj.collMessageRows = null;
+        }
+                            return copyObj;
+    }
+
+    /**
+     * returns a peer instance associated with this om.  Since Peer classes
+     * are not to have any instance attributes, this method returns the
+     * same instance for all member of this class. The method could therefore
+     * be static, but this would prevent one from overriding the behavior.
+     */
+    public MailboxRowPeer getPeer()
+    {
+        return peer;
+    }
+
+
+    public String toString()
+    {
+        StringBuffer str = new StringBuffer();
+        str.append("MailboxRow:\n");
+        str.append("MailboxId = ")
+               .append(getMailboxId())
+             .append("\n");
+        str.append("Name = ")
+               .append(getName())
+             .append("\n");
+        str.append("UidValidity = ")
+               .append(getUidValidity())
+             .append("\n");
+        str.append("LastUid = ")
+               .append(getLastUid())
+             .append("\n");
+        str.append("MessageCount = ")
+               .append(getMessageCount())
+             .append("\n");
+        str.append("Size = ")
+               .append(getSize())
+             .append("\n");
+        return(str.toString());
+    }
+}



---------------------------------------------------------------------
To unsubscribe, e-mail: server-dev-unsubscribe@james.apache.org
For additional commands, e-mail: server-dev-help@james.apache.org