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 no...@apache.org on 2010/08/16 19:55:28 UTC

svn commit: r986076 [1/3] - in /james/imap/trunk: ./ maildir/ maildir/src/ maildir/src/main/ maildir/src/main/java/ maildir/src/main/java/org/ maildir/src/main/java/org/apache/ maildir/src/main/java/org/apache/james/ maildir/src/main/java/org/apache/ja...

Author: norman
Date: Mon Aug 16 17:55:26 2010
New Revision: 986076

URL: http://svn.apache.org/viewvc?rev=986076&view=rev
Log:
Import maildir store which was written by Tim-Christian Mundt during Google Summer of Code. Thx again Tim for all your hard work (IMAP-101)

Added:
    james/imap/trunk/maildir/LICENSE.txt
    james/imap/trunk/maildir/NOTICE.txt
    james/imap/trunk/maildir/pom.xml
    james/imap/trunk/maildir/src/
    james/imap/trunk/maildir/src/main/
    james/imap/trunk/maildir/src/main/java/
    james/imap/trunk/maildir/src/main/java/org/
    james/imap/trunk/maildir/src/main/java/org/apache/
    james/imap/trunk/maildir/src/main/java/org/apache/james/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/FileLock.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirFolder.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxManager.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxSessionMapperFactory.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageManager.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageName.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirStore.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirSubscriptionManager.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/UidConstraint.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/MaildirMailboxMapper.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/MaildirMessageMapper.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/model/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/model/MaildirHeader.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/model/MaildirMailbox.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/model/MaildirMessage.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/mail/model/MaildirProperty.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/user/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/user/MaildirSubscriptionMapper.java
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/user/model/
    james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/user/model/MaildirSubscription.java
    james/imap/trunk/maildir/src/test/
    james/imap/trunk/maildir/src/test/java/
    james/imap/trunk/maildir/src/test/java/org/
    james/imap/trunk/maildir/src/test/java/org/apache/
    james/imap/trunk/maildir/src/test/java/org/apache/james/
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/AuthenticatedStateTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/ConcurrentSessionsTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/EventTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/ExpungeTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/FetchBodySectionTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/FetchBodyStructureTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/FetchHeadersTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/FetchTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/ListingTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/MaildirHostSystem.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/MaildirStressTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/NonAuthenticatedStateTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/PartialFetchTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/RenameTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/SecurityTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/SelectTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/SelectedInboxTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/SelectedStateTest.java
    james/imap/trunk/maildir/src/test/java/org/apache/james/imap/functional/maildir/UidSearchTest.java
Modified:
    james/imap/trunk/parent/pom.xml
    james/imap/trunk/pom.xml

Added: james/imap/trunk/maildir/LICENSE.txt
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/LICENSE.txt?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/LICENSE.txt (added)
+++ james/imap/trunk/maildir/LICENSE.txt Mon Aug 16 17:55:26 2010
@@ -0,0 +1,176 @@
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
\ No newline at end of file

Added: james/imap/trunk/maildir/NOTICE.txt
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/NOTICE.txt?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/NOTICE.txt (added)
+++ james/imap/trunk/maildir/NOTICE.txt Mon Aug 16 17:55:26 2010
@@ -0,0 +1,11 @@
+
+=========================================================================
+==      NOTICE file for use with the Apache License, Version 2.0,      ==
+=========================================================================
+
+Apache JAMES 
+Copyright 2007-2008 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
+            
\ No newline at end of file

Added: james/imap/trunk/maildir/pom.xml
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/pom.xml?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/pom.xml (added)
+++ james/imap/trunk/maildir/pom.xml Mon Aug 16 17:55:26 2010
@@ -0,0 +1,123 @@
+<?xml version="1.0" encoding="ISO-8859-15"?>
+<!--
+  Licensed to the Apache Software Foundation (ASF) under one
+  or more contributor license agreements.  See the NOTICE file
+  distributed with this work for additional information
+  regarding copyright ownership.  The ASF licenses this file
+  to you under the Apache License, Version 2.0 (the
+  "License"); you may not use this file except in compliance
+  with the License.  You may obtain a copy of the License at
+
+    http://www.apache.org/licenses/LICENSE-2.0
+
+  Unless required by applicable law or agreed to in writing,
+  software distributed under the License is distributed on an
+  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+  KIND, either express or implied.  See the License for the
+  specific language governing permissions and limitations
+  under the License.    
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+  <parent>
+    <artifactId>apache-james-imap-parent</artifactId>
+    <groupId>org.apache.james</groupId>
+    <version>0.1-M2-SNAPSHOT</version>
+    <relativePath>../parent/pom.xml</relativePath>
+  </parent>
+  <modelVersion>4.0.0</modelVersion>
+  <groupId>org.apache.james</groupId>
+  <artifactId>apache-james-imap-maildir</artifactId>
+  <name>Apache James IMAP Maildir Mailbox Manager</name>
+  
+  <build>
+    <plugins>
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-compiler-plugin</artifactId>
+        <version>2.1</version>
+        <configuration>
+          <source>1.5</source>
+          <target>1.5</target>
+        </configuration>
+      </plugin>
+    </plugins>
+  </build>
+  
+  <dependencies>
+    <dependency>
+      <groupId>${javax.mail.groupId}</groupId>
+      <artifactId>${javax.mail.artifactId}</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>${javax.activation.groupId}</groupId>
+      <artifactId>${javax.activation.artifactId}</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-api</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-mailbox</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-store</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-mime4j</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>commons-logging</groupId>
+      <artifactId>commons-logging</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>commons-lang</groupId>
+      <artifactId>commons-lang</artifactId>
+    </dependency>
+    
+    <dependency>
+      <groupId>commons-collections</groupId>
+      <artifactId>commons-collections</artifactId>
+    </dependency>
+
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-processor</artifactId>
+      <scope>test</scope>
+    </dependency>    
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-seda</artifactId>
+      <scope>test</scope>
+    </dependency>
+  <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-seda</artifactId>
+      <type>test-jar</type>
+      <scope>test</scope>
+    </dependency>
+	<dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-protocol-tester</artifactId>
+      <scope>test</scope>
+    </dependency>
+    <dependency>
+      <groupId>org.apache.james</groupId>
+      <artifactId>apache-james-imap-deployment</artifactId>
+      <version>${pom.version}</version>
+      <type>test-jar</type>
+    </dependency>
+    <dependency>
+      <groupId>commons-io</groupId>
+      <artifactId>commons-io</artifactId>
+    </dependency>
+    <dependency>
+      <groupId>junit</groupId>
+      <artifactId>junit</artifactId>
+      <scope>test</scope>
+    </dependency>
+  </dependencies>
+</project>

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/FileLock.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/FileLock.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/FileLock.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/FileLock.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,98 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import java.io.File;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.ReentrantLock;
+
+/**
+ * Built-in file locks (e.g. FileChannel.lock()) are not thread-safe
+ * meaning that the files are only locked against access outside of the
+ * vm, not against other threads.
+ * This class can synchronize access to the same files using one
+ * {@link ReentrantLock} per file.
+ * 
+ * Its very important to call the {@link #unlock(MailboxPath)} method
+ * in a finally block to not risk a dead lock.
+ *
+ */
+public final class FileLock {
+
+    private static final Map<String, Lock> fileLocks = new HashMap<String, Lock>();
+    
+    /**
+     * Obtains a {@link Lock} for the given file. It will block if the lock for the file is
+     * already held by some other thread.
+     * @param file The file to lock
+     */
+    public static void lock(File file) {
+        Lock lock;
+        synchronized (fileLocks) {
+            lock = fileLocks.get(file.getAbsoluteFile().getAbsolutePath());
+            if (lock == null) {
+                lock = new Lock();
+                fileLocks.put(file.getAbsoluteFile().getAbsolutePath(), lock);
+            }
+        }
+        lock.increaseCount();
+        lock.lock();
+    }
+    
+    /**
+     * Unlock the previous obtained {@link Lock} for the given file.
+     * @param file The file to unlock
+     */
+    public static void unlock(File file) {
+        Lock lock;
+        synchronized (fileLocks) {
+            lock = fileLocks.get(file.getAbsoluteFile().getAbsolutePath());
+        }
+        if (lock != null) {
+            lock.unlock();
+            if (lock.decreaseCount() == 0)
+                fileLocks.remove(file.getAbsoluteFile().getAbsolutePath());
+        }
+    }
+    
+    /**
+     * This adds a counter to the ReentrantLock which counts the threads
+     * that are waiting for or owning the lock.
+     */
+    static class Lock extends ReentrantLock {
+
+        private static final long serialVersionUID = 1373469372404809079L;
+        private AtomicInteger counter;
+        
+        public Lock() {
+            this.counter = new AtomicInteger(0);
+        }
+        
+        public int increaseCount() {
+            return this.counter.incrementAndGet();
+        }
+        
+        public int decreaseCount() {
+            return this.counter.decrementAndGet();
+        }
+        
+    }
+}

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirFolder.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirFolder.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirFolder.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirFolder.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,727 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileNotFoundException;
+import java.io.FileOutputStream;
+import java.io.FileReader;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.io.PrintWriter;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.LinkedList;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.SortedMap;
+import java.util.TreeMap;
+import java.util.Map.Entry;
+
+import org.apache.commons.lang.ArrayUtils;
+
+public class MaildirFolder {
+
+    public static final String VALIDITY_FILE = "james-uidvalidity";
+    public static final String UIDLIST_FILE = "james-uidlist";
+    public static final String CUR = "cur";
+    public static final String NEW = "new";
+    public static final String TMP = "tmp";
+    
+    private File rootFolder;
+    private File curFolder;
+    private File newFolder;
+    private File tmpFolder;
+    private File uidFile;
+    
+    private long lastUid = -1;
+    private int messageCount = 0;
+    private long uidValidity = -1;
+    
+    /**
+     * Representation of a maildir folder containing the message folders
+     * and some special files
+     * @param absPath The absolute path of the mailbox folder
+     */
+    public MaildirFolder(String absPath) {
+        this.rootFolder = new File(absPath);
+        this.curFolder = new File(rootFolder, CUR);
+        this.newFolder = new File(rootFolder, NEW);
+        this.tmpFolder = new File(rootFolder, TMP);
+        this.uidFile = new File(rootFolder, UIDLIST_FILE);
+    }
+    
+    /**
+     * Returns the {@link File} of this Maildir folder.
+     * @return
+     */
+    public File getRootFile() {
+        return rootFolder;
+    }
+    
+    /**
+     * Locks the uidList file and if it has retrieved the lock, returns it.
+     * Make sure to call unlockUidList() in a finally block afterwards.
+     * @return The locked uidList
+     */
+    public File lockUidList() {
+        FileLock.lock(uidFile);
+        return uidFile;
+    }
+    
+    /**
+     * Unlocks the uidList file if it has been locked before.
+     */
+    public void unlockUidList() {
+        FileLock.unlock(uidFile);
+    }
+    
+    /**
+     * Tests whether the directory belonging to this {@link MaildirFolder} exists 
+     * @return true if the directory belonging to this {@link MaildirFolder} exists ; false otherwise 
+     */
+    public boolean exists() {
+        return rootFolder.isDirectory();
+    }
+    
+    /**
+     * Checks whether the folder's contents have been changed after
+     * the uidfile has been created.
+     * @return true if the contents have been changed.
+     */
+    private boolean isModified() {
+        long uidListModified = uidFile.lastModified();
+        long curModified = curFolder.lastModified();
+        long newModified = newFolder.lastModified();
+        // because of bad time resolution of file systems we also check "equals"
+        if (curModified >= uidListModified || newModified >= uidListModified) {
+            return true;
+        }
+        return false;
+    }
+    
+    /**
+     * Returns the ./cur folder of this Maildir folder.
+     * @return
+     */
+    public File getCurFolder() {
+        return curFolder;
+    }
+    
+    /**
+     * Returns the ./new folder of this Maildir folder.
+     * @return
+     */
+    public File getNewFolder() {
+        return newFolder;
+    }
+    
+    /**
+     * Returns the ./tmp folder of this Maildir folder.
+     * @return
+     */
+    public File getTmpFolder() {
+        return tmpFolder;
+    }
+    
+    /**
+     * Returns the nextUid value and increases it.
+     * @return nextUid
+     */
+    private long getNextUid() {
+        return ++lastUid;
+    }
+    
+    /**
+     * Returns the last uid used in this mailbox
+     * @return lastUid
+     * @throws IOException
+     */
+    public long getLastUid() throws IOException {
+        if (lastUid == -1) {
+            readLastUid();
+        }
+        return lastUid;
+    }
+
+    /**
+     * Read the lastUid of the given mailbox from the file system.
+     * @throws IOException if there are problems with the uidList file
+     */
+    private void readLastUid() throws IOException {
+        File uidList = lockUidList();
+        try {
+            if (!uidList.exists())
+                createUidFile();
+            FileReader fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            String line = reader.readLine();
+            reader.close();
+            fileReader.close();
+            if (line != null)
+                readUidListHeader(line);
+        }
+        finally {
+            unlockUidList();
+        }
+    }
+    
+    /**
+     * Returns the uidValidity of this mailbox
+     * @return
+     * @throws IOException
+     */
+    public long getUidValidity() throws IOException {
+        if (uidValidity == -1)
+            uidValidity = readUidValidity();
+        return uidValidity;
+    }
+    
+    /**
+     * Sets the uidValidity for this mailbox and writes it to the file system
+     * @param uidValidity
+     * @throws IOException
+     */
+    public void setUidValidity(long uidValidity) throws IOException {
+        saveUidValidity(uidValidity);
+        this.uidValidity = uidValidity;
+    }
+
+    /**
+     * Read the uidValidity of the given mailbox from the file system.
+     * If the respective file is not yet there, it gets created and
+     * filled with a brand new uidValidity.
+     * @return The uidValidity
+     * @throws IOException if there are problems with the validity file
+     */
+    private long readUidValidity() throws IOException {
+        File validityFile = new File(rootFolder, VALIDITY_FILE);
+        if (!validityFile.exists()) {
+            return resetUidValidity();
+        }
+        FileInputStream fis = new FileInputStream(validityFile);
+        InputStreamReader isr = new InputStreamReader(fis);
+        char[] uidValidity = new char[20];
+        int len = isr.read(uidValidity);
+        isr.close();
+        fis.close();
+        return Long.parseLong(String.valueOf(uidValidity, 0, len).trim());
+    }
+
+    /**
+     * Save the given uidValidity to the file system
+     * @param uidValidity
+     * @throws IOException
+     */
+    private void saveUidValidity(long uidValidity) throws IOException {
+        File validityFile = new File(rootFolder, VALIDITY_FILE);
+        validityFile.createNewFile();
+        FileOutputStream fos = new FileOutputStream(validityFile);
+        fos.write(String.valueOf(uidValidity).getBytes());
+        fos.close();
+    }
+    
+    /**
+     * Sets and returns a new uidValidity for this folder.
+     * @return the new uidValidity
+     * @throws IOException
+     */
+    private long resetUidValidity() throws IOException {
+        // using the timestamp as uidValidity
+        long timestamp = System.currentTimeMillis();
+        setUidValidity(timestamp);
+        return timestamp;
+    }
+    
+    /**
+     * Searches the uid list for a certain uid and returns the according {@link MaildirMessageName}
+     * @param uid The uid to search for
+     * @return The {@link MaildirMessageName} that belongs to the uid
+     * @throws IOException If the uidlist file cannot be found or read
+     */
+    public MaildirMessageName getMessageNameByUid(Long uid) throws IOException, FileNotFoundException {
+        File uidList = lockUidList();
+        MaildirMessageName messageName = null;
+        try {
+            FileReader fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            String uidString = String.valueOf(uid);
+            String line = reader.readLine(); // the header
+            while ((line = reader.readLine()) != null) {
+                if (!line.equals("")) {
+                    int gap = line.indexOf(" ");
+                    if (line.substring(0, gap).equals(uidString)) {
+                        fileReader.close();
+                        messageName = new MaildirMessageName(this, line.substring(gap + 1));
+                        break;
+                    }
+                }
+            }
+            fileReader.close();
+        } finally {
+            unlockUidList();
+        }
+        return messageName;
+    }
+    
+    /**
+     * Reads all uids between the two boundaries from the folder and returns them as
+     * a sorted map together with their corresponding {@link MaildirMessageName}s.
+     * @param from The lower uid limit
+     * @param to The upper uid limit. <code>-1</code> disables the upper limit
+     * @return a {@link Map} whith all uids in the given range and associated {@link MaildirMessageName}s
+     * @throws IOException if there is a problem with the uid list file
+     */
+    public SortedMap<Long, MaildirMessageName> getUidMap(long from, long to)
+    throws IOException, FileNotFoundException {
+        SortedMap<Long, MaildirMessageName> uidMap = null;
+        File uidList = lockUidList();
+        try {
+            if (uidList.isFile()) {
+                if (isModified()) {
+                    try {
+                        uidMap = truncateMap(updateUidFile(), from, to);
+                    } catch (FileNotFoundException e) {
+                        // weird case if someone deleted the uidlist after checking its
+                        // existence and before trying to update it.
+                        uidMap = truncateMap(createUidFile(), from, to);
+                    }
+                }
+                else {
+                    // the uidList is up to date
+                    uidMap = new TreeMap<Long, MaildirMessageName>(readUidFile(from, to));
+                }
+            }
+            else {
+                // the uidList does not exist
+                uidMap = truncateMap(createUidFile(), from, to);
+            }
+        } finally {
+            unlockUidList();
+        }
+        return uidMap;
+    }
+    
+    public SortedMap<Long, MaildirMessageName> getUidMap(FilenameFilter filter, long from, long to)
+    throws FileNotFoundException, IOException {
+        SortedMap<Long, MaildirMessageName> allUids = getUidMap(from, to);
+        SortedMap<Long, MaildirMessageName> filteredUids = new TreeMap<Long, MaildirMessageName>();
+        for (Entry<Long, MaildirMessageName> entry : allUids.entrySet()) {
+            if (filter.accept(null, entry.getValue().getFullName()))
+                filteredUids.put(entry.getKey(), entry.getValue());
+        }
+        return filteredUids;
+    }
+    
+    /**
+     * Reads all uids from the uid list file which match the given filter
+     * and returns as many of them as a sorted map as the limit specifies.
+     * @param filter The file names of all returned items match the filter. 
+     * The dir argument to {@link FilenameFilter}.accept(dir, name) will always be null.
+     * @param limit The number of items; a limit smaller then 1 disables the limit
+     * @return A {@link Map} with all uids and associated {@link MaildirMessageName}s
+     * @throws IOException if there is a problem with the uid list file
+     */
+    public SortedMap<Long, MaildirMessageName> getUidMap(FilenameFilter filter, int limit) throws IOException {
+        SortedMap<Long, MaildirMessageName> allUids = getUidMap(0, -1);
+        SortedMap<Long, MaildirMessageName> filteredUids = new TreeMap<Long, MaildirMessageName>();
+        int theLimit = limit;
+        if (limit < 1)
+            theLimit = allUids.size();
+        int counter = 0;
+        for (Entry<Long, MaildirMessageName> entry : allUids.entrySet()) {
+            if (counter >= theLimit)
+                break;
+            if (filter.accept(null, entry.getValue().getFullName())) {
+                filteredUids.put(entry.getKey(), entry.getValue());
+                counter++;
+            }
+        }
+        return filteredUids;
+    }
+    
+    /**
+     * Creates a map of recent messages.
+     * @param limit The number of items; a limit smaller then 1 disables the limit
+     * @return A {@link Map} with all uids and associated {@link MaildirMessageName}s of recent messages
+     * @throws IOException If there is a problem with the uid list file
+     */
+    public SortedMap<Long, MaildirMessageName> getRecentMessages(int limit) throws IOException {
+        String[] recentFiles = getNewFolder().list();
+        LinkedList<String> lines = new LinkedList<String>();
+        int theLimit = limit;
+        if (limit < 1 || limit > recentFiles.length)
+            theLimit = recentFiles.length;
+        SortedMap<Long, MaildirMessageName> recentMessages = new TreeMap<Long, MaildirMessageName>();
+        File uidList = lockUidList();
+        try {
+            if (!uidList.isFile()) {
+                uidList.createNewFile();
+                String[] curFiles = curFolder.list();
+                String[] newFiles = newFolder.list();
+                messageCount = curFiles.length + newFiles.length;
+                String[] allFiles = (String[]) ArrayUtils.addAll(curFiles, newFiles);
+                for (String file : allFiles)
+                    lines.add(String.valueOf(getNextUid()) + " " + file);
+                PrintWriter pw = new PrintWriter(uidList);
+                pw.println(createUidListHeader());
+                for (String line : lines)
+                    pw.println(line);
+                pw.close();
+            }
+            else {
+                FileReader fileReader = new FileReader(uidList);
+                BufferedReader reader = new BufferedReader(fileReader);
+                String line = reader.readLine();
+                // the first line in the file contains the next uid and message count
+                while ((line = reader.readLine()) != null)
+                    lines.add(line);
+            }
+            int counter = 0;
+            String line;
+            while (counter < theLimit) {
+                // walk backwards as recent files are supposedly recent
+                try {
+                    line = lines.removeLast();
+                } catch (NoSuchElementException e) {
+                    break; // the list is empty
+                }
+                if (!line.equals("")) {
+                    int gap = line.indexOf(" ");
+                    Long uid = Long.valueOf(line.substring(0, gap));
+                    String name = line.substring(gap + 1, line.length());
+                    for (String recentFile : recentFiles) {
+                        if (recentFile.equals(name)) {
+                            recentMessages.put(uid, new MaildirMessageName(this, recentFile));
+                            counter++;
+                            break;
+                        }
+                    }
+                }
+            }
+        } finally {
+            unlockUidList();
+        }
+        return recentMessages;
+    }
+    
+    
+    /**
+     * Creates and returns a uid map (uid -> {@link MaildirMessageName}) and writes it to the disk
+     * @return The uid map
+     * @throws IOException
+     */
+    private Map<Long, MaildirMessageName> createUidFile() throws IOException {
+        Map<Long, MaildirMessageName> uidMap = null;
+        File uidList = lockUidList();
+        try {
+            uidList.createNewFile();
+            lastUid = 0;
+            String[] curFiles = curFolder.list();
+            String[] newFiles = newFolder.list();
+            messageCount = curFiles.length + newFiles.length;
+            uidMap = new HashMap<Long, MaildirMessageName>(messageCount);
+            String[] allFiles = (String[]) ArrayUtils.addAll(curFiles, newFiles);
+            for (String file : allFiles)
+                uidMap.put(getNextUid(), new MaildirMessageName(this, file));
+            uidMap = new TreeMap<Long, MaildirMessageName>(uidMap);
+            PrintWriter pw = new PrintWriter(uidList);
+            pw.println(createUidListHeader());
+            for (Entry<Long, MaildirMessageName> entry : uidMap.entrySet())
+                pw.println(String.valueOf(entry.getKey()) + " " + entry.getValue().getFullName());
+            pw.close();
+        } finally {
+            unlockUidList();
+        }
+        return uidMap;
+    }
+    
+    private Map<Long, MaildirMessageName> updateUidFile() throws FileNotFoundException, IOException {
+        Map<Long, MaildirMessageName> uidMap = null;
+        File uidList = lockUidList();
+        String[] curFiles = curFolder.list();
+        String[] newFiles = newFolder.list();
+        messageCount = curFiles.length + newFiles.length;
+        uidMap = new HashMap<Long, MaildirMessageName>(messageCount);
+        HashMap<String, Long> reverseUidMap = new HashMap<String, Long>(messageCount);
+        FileReader fileReader = null;
+        try {
+            fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            String line = reader.readLine();
+            // the first line in the file contains the next uid and message count
+            if (line != null)
+                readUidListHeader(line);
+            while ((line = reader.readLine()) != null) {
+                if (!line.equals("")) {
+                    int gap = line.indexOf(" ");
+                    Long uid = Long.valueOf(line.substring(0, gap));
+                    String name = line.substring(gap + 1, line.length());
+                    reverseUidMap.put(stripMetaFromName(name), uid);
+                }
+            }
+            fileReader.close();
+            String[] allFiles = (String[]) ArrayUtils.addAll(curFiles, newFiles);
+            for (String file : allFiles) {
+                MaildirMessageName messageName = new MaildirMessageName(this, file);
+                Long uid = reverseUidMap.get(messageName.getBaseName());
+                if (uid == null)
+                    uid = getNextUid();
+                uidMap.put(uid, messageName);
+            }
+            uidMap = new TreeMap<Long, MaildirMessageName>(uidMap);
+            PrintWriter pw = new PrintWriter(uidList);
+            pw.println(createUidListHeader());
+            for (Entry<Long, MaildirMessageName> entry : uidMap.entrySet())
+                pw.println(String.valueOf(entry.getKey()) + " " + entry.getValue().getFullName());
+            pw.close();
+        } finally {
+            unlockUidList();
+        }
+        return uidMap;
+    }
+    
+    private Map<Long, MaildirMessageName> readUidFile(long from, long to) throws IOException, FileNotFoundException {
+        Map<Long, MaildirMessageName> uidMap = null; 
+        File uidList = lockUidList();
+        try {
+            FileReader fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            String line = reader.readLine();
+            // the first line in the file contains the next uid and message count
+            if (line != null)
+                readUidListHeader(line);
+            uidMap = new HashMap<Long, MaildirMessageName>(messageCount);
+            while ((line = reader.readLine()) != null) {
+                if (!line.equals("")) {
+                    int gap = line.indexOf(" ");
+                    Long uid = Long.valueOf(line.substring(0, gap));
+                    if (uid >= from) {
+                        if (to != -1 && uid > to)
+                            break;
+                        String name = line.substring(gap + 1, line.length());
+                        uidMap.put(uid, new MaildirMessageName(this, name));
+                    }
+                }
+            }
+            fileReader.close();
+        } finally {
+            unlockUidList();
+        }
+        messageCount = uidMap.size();
+        return uidMap;
+    }
+    
+    /**
+     * Sorts the given map and returns a subset which is constricted by a lower and an upper limit.
+     * @param source The source map
+     * @param from The lower limit
+     * @param to The upper limit; <code>-1</code> disables the upper limit.
+     * @return The sorted subset
+     */
+    private SortedMap<Long, MaildirMessageName> truncateMap(Map<Long, MaildirMessageName> source, long from, long to) {
+        TreeMap<Long, MaildirMessageName> sortedMap;
+        if (source instanceof TreeMap<?, ?>) sortedMap = (TreeMap<Long, MaildirMessageName>) source;
+        else sortedMap = new TreeMap<Long, MaildirMessageName>(source);
+        if (to != -1)
+            return sortedMap.subMap(from, to + 1);
+        return sortedMap.tailMap(from);
+    }
+    
+    /**
+     * Parses the header line in uid list files.
+     * The format is: version lastUid messageCount (e.g. 1 615 273)
+     * @param line The raw header line
+     * @throws IOException
+     */
+    private void readUidListHeader(String line) throws IOException {
+        int gap1 = line.indexOf(" ");
+        int version = Integer.valueOf(line.substring(0, gap1));
+        if (version != 1)
+            throw new IOException("Cannot read uidlists with versions other than 1.");
+        int gap2 = line.indexOf(" ", gap1 + 1);
+        lastUid = Long.valueOf(line.substring(gap1 + 1, gap2));
+        messageCount = Integer.valueOf(line.substring(gap2 + 1, line.length()));
+    }
+    
+    /**
+     * Creates a line to put as a header in the uid list file.
+     * @return the line which ought to be the header
+     */
+    private String createUidListHeader() {
+        return "1 " + String.valueOf(lastUid) + " " + String.valueOf(messageCount);
+    }
+    
+    /**
+     * Takes the name of a message file and returns only the base name.
+     * @param fileName The name of the message file
+     * @return the file name without meta data, the unmodified name if it doesn't have meta data
+     */
+    public static String stripMetaFromName(String fileName) {
+        int end = fileName.indexOf(",S="); // the size
+        if (end == -1)
+            end = fileName.indexOf(":2,"); // the flags
+        if (end == -1)
+            return fileName; // there is no meta data to strip
+        return fileName.substring(0, end);
+    }
+
+    /**
+     * Appends a message to the uidlist and returns its uid.
+     * @param name The name of the message's file
+     * @return The uid of the message
+     * @throws IOException
+     */
+    public long appendMessage(String name) throws IOException {
+        File uidList = lockUidList();
+        long uid = -1;
+        try {
+            if (uidList.isFile()) {
+                FileReader fileReader = new FileReader(uidList);
+                BufferedReader reader = new BufferedReader(fileReader);
+                String line = reader.readLine();
+                // the first line in the file contains the next uid and message count
+                if (line != null)
+                    readUidListHeader(line);
+                ArrayList<String> lines = new ArrayList<String>(messageCount);
+                while ((line = reader.readLine()) != null)
+                    lines.add(line);
+                uid = getNextUid();
+                lines.add(String.valueOf(uid) + " " + name);
+                messageCount++;
+                fileReader.close();
+                PrintWriter writer = new PrintWriter(uidList);
+                writer.println(createUidListHeader());
+                for (String entry : lines)
+                    writer.println(entry);
+                writer.close();
+            }
+            else {
+                // create the file
+                uidList.createNewFile();
+                String[] curFiles = curFolder.list();
+                String[] newFiles = newFolder.list();
+                messageCount = curFiles.length + newFiles.length;
+                ArrayList<String> lines = new ArrayList<String>(messageCount);
+                String[] allFiles = (String[]) ArrayUtils.addAll(curFiles, newFiles);
+                for (String file : allFiles) {
+                    long theUid = getNextUid();
+                    lines.add(String.valueOf(theUid) + " " + file);
+                    // the listed names already include the message to append
+                    if (file.equals(name))
+                        uid = theUid;
+                }
+                PrintWriter pw = new PrintWriter(uidList);
+                pw.println(createUidListHeader());
+                for (String line : lines)
+                    pw.println(line);
+                pw.close();
+            }
+        } finally {
+            unlockUidList();
+        }
+        if (uid == -1)
+            throw new FileNotFoundException(name);
+        return uid;
+    }
+
+    /**
+     * Updates an entry in the uid list.
+     * @param uid
+     * @param messageName
+     * @throws IOException
+     */
+    public void update(long uid, String messageName) throws IOException {
+        File uidList = lockUidList();
+        try {
+            FileReader fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            String line = reader.readLine();
+            readUidListHeader(line);
+            ArrayList<String> lines = new ArrayList<String>(messageCount);
+            while ((line = reader.readLine()) != null) {
+                if (uid == Long.valueOf(line.substring(0, line.indexOf(" "))))
+                    line = String.valueOf(uid) + " " + messageName;
+                lines.add(line);
+            }
+            fileReader.close();
+            PrintWriter writer = new PrintWriter(uidList);
+            writer.println(createUidListHeader());
+            for (String entry : lines)
+                writer.println(entry);
+            writer.close();
+        } finally {
+            unlockUidList();
+        }
+    }
+    
+    /**
+     * Retrieves the file belonging to the given uid, deletes it and updates
+     * the uid list.
+     * @param uid The uid of the message to delete
+     * @return The {@link MaildirMessageName} of the deleted message
+     * @throws IOException If the file cannot be deleted of there is a problem with the uid list
+     */
+    public MaildirMessageName delete(long uid) throws IOException {
+        MaildirMessageName deletedMessage = null;
+        File uidList = lockUidList();
+        try {
+            FileReader fileReader = new FileReader(uidList);
+            BufferedReader reader = new BufferedReader(fileReader);
+            readUidListHeader(reader.readLine());
+            ArrayList<String> lines = new ArrayList<String>(messageCount-1);
+            String line;
+            while ((line = reader.readLine()) != null) {
+                int gap = line.indexOf(" ");
+                if (uid == Long.valueOf(line.substring(0, line.indexOf(" ")))) {
+                    deletedMessage = new MaildirMessageName(this, line.substring(gap + 1, line.length()));
+                    messageCount--;
+                }
+                else {
+                    lines.add(line);
+                }
+            }
+            fileReader.close();
+            if (deletedMessage != null) {
+                if (!deletedMessage.getFile().delete())
+                    throw new IOException("Cannot delete file " + deletedMessage.getFile().getAbsolutePath());
+                PrintWriter writer = new PrintWriter(uidList);
+                writer.println(createUidListHeader());
+                for (String entry : lines)
+                    writer.println(entry);
+                writer.close();
+            }
+        } finally {
+            unlockUidList();
+        }
+        return deletedMessage;
+    }
+    
+    /** 
+     * The absolute path of this folder.
+     */
+    @Override
+    public String toString() {
+        return getRootFile().getAbsolutePath();
+    }
+    
+}

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxManager.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxManager.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxManager.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxManager.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,56 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import org.apache.james.imap.api.MailboxPath;
+import org.apache.james.imap.mailbox.MailboxException;
+import org.apache.james.imap.mailbox.MailboxSession;
+import org.apache.james.imap.mailbox.util.MailboxEventDispatcher;
+import org.apache.james.imap.maildir.mail.model.MaildirMailbox;
+import org.apache.james.imap.store.Authenticator;
+import org.apache.james.imap.store.MailboxSessionMapperFactory;
+import org.apache.james.imap.store.StoreMailboxManager;
+import org.apache.james.imap.store.StoreMessageManager;
+import org.apache.james.imap.store.Subscriber;
+import org.apache.james.imap.store.mail.MailboxMapper;
+import org.apache.james.imap.store.mail.model.Mailbox;
+
+public class MaildirMailboxManager extends StoreMailboxManager<Integer> {
+
+    public MaildirMailboxManager(
+            MailboxSessionMapperFactory<Integer> mailboxSessionMapperFactory,
+            Authenticator authenticator, Subscriber subscriber) {
+        super(mailboxSessionMapperFactory, authenticator, subscriber);
+    }
+
+    @Override
+    protected StoreMessageManager<Integer> createMessageManager(MailboxEventDispatcher dispatcher,
+            Mailbox<Integer> mailboxEntiy, MailboxSession session) throws MailboxException {
+        return new MaildirMessageManager(mailboxSessionMapperFactory, dispatcher, mailboxEntiy, session);
+    }
+
+    @Override
+    protected void doCreateMailbox(MailboxPath mailboxPath, MailboxSession session)
+            throws MailboxException {
+        final Mailbox<Integer> mailbox = new MaildirMailbox(mailboxPath, randomUidValidity(), 0);
+        final MailboxMapper<Integer> mapper = mailboxSessionMapperFactory.getMailboxMapper(session);
+        mapper.save(mailbox);
+    }
+
+}

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxSessionMapperFactory.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxSessionMapperFactory.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxSessionMapperFactory.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMailboxSessionMapperFactory.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,59 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import org.apache.james.imap.mailbox.MailboxException;
+import org.apache.james.imap.mailbox.MailboxSession;
+import org.apache.james.imap.mailbox.SubscriptionException;
+import org.apache.james.imap.maildir.mail.MaildirMailboxMapper;
+import org.apache.james.imap.maildir.mail.MaildirMessageMapper;
+import org.apache.james.imap.maildir.user.MaildirSubscriptionMapper;
+import org.apache.james.imap.store.MailboxSessionMapperFactory;
+import org.apache.james.imap.store.mail.MailboxMapper;
+import org.apache.james.imap.store.mail.MessageMapper;
+import org.apache.james.imap.store.user.SubscriptionMapper;
+
+public class MaildirMailboxSessionMapperFactory extends
+        MailboxSessionMapperFactory<Integer> {
+
+    private final String root;
+    
+    public MaildirMailboxSessionMapperFactory(String root) {
+        this.root = root;
+    }
+    
+    @Override
+    protected MailboxMapper<Integer> createMailboxMapper(MailboxSession session)
+            throws MailboxException {
+        return new MaildirMailboxMapper(root);
+    }
+
+    @Override
+    protected MessageMapper<Integer> createMessageMapper(MailboxSession session)
+            throws MailboxException {
+        return new MaildirMessageMapper(root);
+    }
+
+    @Override
+    protected SubscriptionMapper createSubscriptionMapper(MailboxSession session)
+            throws SubscriptionException {
+        return new MaildirSubscriptionMapper(root);
+    }
+
+}

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageManager.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageManager.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageManager.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageManager.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,67 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+
+import javax.mail.Flags;
+
+import org.apache.james.imap.mailbox.MailboxException;
+import org.apache.james.imap.mailbox.MailboxSession;
+import org.apache.james.imap.mailbox.util.MailboxEventDispatcher;
+import org.apache.james.imap.maildir.mail.model.MaildirHeader;
+import org.apache.james.imap.maildir.mail.model.MaildirMessage;
+import org.apache.james.imap.store.MailboxSessionMapperFactory;
+import org.apache.james.imap.store.StoreMessageManager;
+import org.apache.james.imap.store.mail.model.Header;
+import org.apache.james.imap.store.mail.model.Mailbox;
+import org.apache.james.imap.store.mail.model.MailboxMembership;
+import org.apache.james.imap.store.mail.model.PropertyBuilder;
+
+public class MaildirMessageManager extends StoreMessageManager<Integer> {
+
+    public MaildirMessageManager(MailboxSessionMapperFactory<Integer> mapperFactory,
+            MailboxEventDispatcher dispatcher, Mailbox<Integer> mailboxEntiy, MailboxSession session)
+    throws MailboxException {
+        super(mapperFactory, dispatcher, mailboxEntiy, session);
+    }
+
+    @Override
+    protected Header createHeader(int lineNumber, String name, String value) {
+        return new MaildirHeader(lineNumber, name, value);
+    }
+
+    @Override
+    protected MailboxMembership<Integer> createMessage(Date internalDate,
+            int size, int bodyStartOctet, InputStream documentIn, Flags flags,
+            List<Header> headers, PropertyBuilder propertyBuilder)
+            throws MailboxException {
+        final List<MaildirHeader> maildirHeaders = new ArrayList<MaildirHeader>(headers.size());
+        for (Header header: headers) {
+            maildirHeaders.add((MaildirHeader) header);
+        }
+        final MailboxMembership<Integer> message = new MaildirMessage(mailbox, internalDate, 
+                size, flags, documentIn, bodyStartOctet, maildirHeaders, propertyBuilder);
+        return message;
+    }
+
+}

Added: james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageName.java
URL: http://svn.apache.org/viewvc/james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageName.java?rev=986076&view=auto
==============================================================================
--- james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageName.java (added)
+++ james/imap/trunk/maildir/src/main/java/org/apache/james/imap/maildir/MaildirMessageName.java Mon Aug 16 17:55:26 2010
@@ -0,0 +1,441 @@
+/****************************************************************
+ * Licensed to the Apache Software Foundation (ASF) under one   *
+ * or more contributor license agreements.  See the NOTICE file *
+ * distributed with this work for additional information        *
+ * regarding copyright ownership.  The ASF licenses this file   *
+ * to you under the Apache License, Version 2.0 (the            *
+ * "License"); you may not use this file except in compliance   *
+ * with the License.  You may obtain a copy of the License at   *
+ *                                                              *
+ *   http://www.apache.org/licenses/LICENSE-2.0                 *
+ *                                                              *
+ * Unless required by applicable law or agreed to in writing,   *
+ * software distributed under the License is distributed on an  *
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY       *
+ * KIND, either express or implied.  See the License for the    *
+ * specific language governing permissions and limitations      *
+ * under the License.                                           *
+ ****************************************************************/
+package org.apache.james.imap.maildir;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.FilenameFilter;
+import java.lang.management.ManagementFactory;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.Date;
+import java.util.Random;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.mail.Flags;
+
+public class MaildirMessageName {
+
+    // the flags in Maildir message names
+    public static final String FLAG_DRAFT = "D";
+    public static final String FLAG_FLAGGED = "F";
+    public static final String FLAG_ANSWERD = "R";
+    public static final String FLAG_SEEN = "S";
+    public static final String FLAG_DELETED = "T";
+
+    // patterns
+    public static final String PATTERN_STRING_MESSAGE_NAME = "\\d*\\.\\w*\\.\\w*";
+    public static final String PATTERN_STRING_FLAGS = ":2,[DFRST]*";
+    public static final String PATTERN_STRING_SIZE = ",S=\\d+";
+    public static final Pattern PATTERN_MESSAGE =
+        Pattern.compile(PATTERN_STRING_MESSAGE_NAME + optional(PATTERN_STRING_SIZE) + optional(PATTERN_STRING_FLAGS));
+    
+    public static final Pattern PATTERN_UNSEEN_MESSAGES =
+        Pattern.compile(PATTERN_STRING_MESSAGE_NAME + PATTERN_STRING_SIZE + optional(":2,[^S]*"));
+    
+    public static final FilenameFilter FILTER_UNSEEN_MESSAGES = createRegexFilter(PATTERN_UNSEEN_MESSAGES);
+    
+    public static final Pattern PATTERN_DELETED_MESSAGES =
+        Pattern.compile(PATTERN_STRING_MESSAGE_NAME + PATTERN_STRING_SIZE + ":2,.*" + FLAG_DELETED);
+    
+    public static final FilenameFilter FILTER_DELETED_MESSAGES = createRegexFilter(PATTERN_DELETED_MESSAGES);
+    
+    /**
+     * The number of deliveries done by the server since its last start
+     */
+    private static AtomicInteger deliveries = new AtomicInteger(0);
+    
+    /**
+     * A random generator for the random part in the unique message names
+     */
+    private static Random random = new Random();
+
+    /**
+     * The process id of the server process
+     */
+    private static String processName = ManagementFactory.getRuntimeMXBean().getName();
+    static {
+        String[] parts = processName.split("@");
+        if (parts.length > 1)
+            processName = parts[0];
+    }
+    
+    /**
+     * The host name of the machine the server is running on
+     */
+    private static String currentHostname;
+    static {
+        try {
+            currentHostname = InetAddress.getLocalHost().getHostName();
+        } catch (UnknownHostException e) {
+            currentHostname = "localhost";
+        }
+    }
+
+    private String fullName;
+    private File file;
+    private MaildirFolder parentFolder;
+    private String timestamp;
+    private String uniqueString;
+    private String hostnameAndMeta; // tim-erwin.de,S=1000:2,RS
+    private String hostname;
+    private String sizeString;
+    private String flagsString;
+    private boolean isSplit;
+    private Date internalDate;
+    private Long size;
+    private Flags flags;
+    
+    public MaildirMessageName(MaildirFolder parentFolder, String fullName) {
+        this.parentFolder = parentFolder;
+        setFullName(fullName);
+    }
+
+    /**
+     * Tests whether the file or directory belonging to this {@link MaildirFolder} exists.
+     * If the file exists, its absolute path is written to absPath.
+     * TODO: If the flags have changed or the file doesn't exist any more, the uidlist should be updated
+     * @return true if the file or directory belonging to this {@link MaildirFolder} exists ; false otherwise 
+     */
+    public boolean exists() {
+        if (file != null && file.isFile())
+            return true;
+        File assumedFile1 = new File(parentFolder.getCurFolder(), fullName);
+        if (assumedFile1.isFile()) {
+            file = assumedFile1;
+            return true;
+        }
+        File assumedFile2 = new File(parentFolder.getNewFolder(), fullName);
+        if (assumedFile2.isFile()) {
+            file = assumedFile2;
+            return true;
+        }
+        // check if maybe the flags have changed which means
+        // list the files in the cur and new folder and check if the message is there
+        FilenameFilter filter = getFilenameFilter();
+        File[] matchingFiles1 = parentFolder.getCurFolder().listFiles(filter);
+        if (matchingFiles1.length == 1) {
+            setFullName(matchingFiles1[0].getName());
+            file = matchingFiles1[0];
+            return true;
+        }
+        File[] matchingFiles2 = parentFolder.getNewFolder().listFiles(filter);
+        if (matchingFiles2.length == 1) {
+            setFullName(matchingFiles2[0].getName());
+            file = matchingFiles2[0];
+            return true;
+        }
+        return false;
+    }
+    
+    /**
+     * Sets the fullName of this {@link MaildirMessageName} if different from the current one.
+     * As this invalidates the parsed elements, they are being reset.
+     * @param fullName A name of a message file in the correct Maildir format
+     */
+    public void setFullName(String fullName) {
+        if (this.fullName != fullName) {
+            this.fullName = fullName;
+            this.file = null;
+            this.isSplit = false;
+            this.internalDate = null;
+            this.size = null;
+            this.flags = null;
+        }
+    }
+    
+    /**
+     * Returns the full name of this message including size and flags if available.
+     * @return
+     */
+    public String getFullName() {
+        if (this.fullName == null) {
+            StringBuffer fullBuffer = new StringBuffer();
+            fullBuffer.append(timestamp);
+            fullBuffer.append(".");
+            fullBuffer.append(uniqueString);
+            fullBuffer.append(".");
+            fullBuffer.append(hostname);
+            if (sizeString != null)
+                fullBuffer.append(sizeString);
+            if (flagsString != null)
+                fullBuffer.append(flagsString);
+            fullName = fullBuffer.toString();
+        }
+        return fullName;
+    }
+    
+    /**
+     * Returns a {@link File} object of the message denoted by this {@link MaildirMessageName}.
+     * Also checks for different flags if it cannot be found directly.
+     * @return A {@link File} object
+     * @throws FileNotFoundException If there is no file for the given name
+     */
+    public File getFile() throws FileNotFoundException {
+        if (exists())
+            return file;
+        else
+            throw new FileNotFoundException("There is no file for message name " + fullName
+                    + " in mailbox " + parentFolder.getRootFile().getAbsolutePath());
+    }
+    
+    /**
+     * Creates a filter which matches the message file even if the flags have changed 
+     * @return
+     */
+    public FilenameFilter getFilenameFilter() {
+        split();
+        StringBuffer pattern = new StringBuffer();
+        pattern.append(timestamp);
+        pattern.append("\\.");
+        pattern.append(uniqueString);
+        pattern.append("\\.");
+        pattern.append(hostname);
+        pattern.append(".*");
+        return createRegexFilter(Pattern.compile(pattern.toString()));
+    }
+    
+    /**
+     * Splits up the full file name if necessary.
+     */
+    private void split() {
+        if (!isSplit) {
+            splitFullName();
+            splitHostNameAndMeta();
+            isSplit = true;
+        }
+    }
+    
+    /**
+     * Splits up the full file name into its main components timestamp,
+     * uniqueString and hostNameAndMeta and fills the respective variables.
+     */
+    private void splitFullName() {
+        int firstEnd = fullName.indexOf('.');
+        int secondEnd = fullName.indexOf('.', firstEnd + 1);
+        timestamp = fullName.substring(0, firstEnd);
+        uniqueString = fullName.substring(firstEnd + 1, secondEnd);
+        hostnameAndMeta = fullName.substring(secondEnd + 1, fullName.length());
+    }
+    
+    /**
+     * Splits up the third part of the file name (e.g. tim-erwin.de,S=1000:2,RS)
+     * into its components hostname, size and flags and fills the respective variables.
+     */
+    private void splitHostNameAndMeta() {
+        int firstEnd = hostnameAndMeta.indexOf(',');
+        int secondEnd = hostnameAndMeta.indexOf(':', firstEnd + 1);
+        hostname = hostnameAndMeta.substring(0, firstEnd);
+        // there are flags
+        if (secondEnd != -1) {
+            sizeString = hostnameAndMeta.substring(firstEnd, secondEnd);
+            flagsString = hostnameAndMeta.substring(secondEnd, hostnameAndMeta.length());
+        }
+        else {
+            sizeString = hostnameAndMeta.substring(firstEnd, hostnameAndMeta.length());
+        }
+    }
+    
+    /**
+     * Sets new flags for this message name.
+     * @param flags
+     */
+    public void setFlags(Flags flags) {
+        if (this.flags != flags) {
+            split(); // save all parts
+            this.flags = flags;
+            this.flagsString = encodeFlags(flags);
+            this.fullName = null; // invalidate the fullName
+        }
+    }
+    
+    /**
+     * Decodes the flags part of the file name if necessary and returns the appropriate Flags object.
+     * @return The {@link Flags} of this message
+     */
+    public Flags getFlags() {
+        if (flags == null) {
+            split();
+            if (flagsString == null)
+                return null;
+            flags = decodeFlags(flagsString.substring(3)); // skip the ":2," part
+        }
+        return flags;
+    }
+    
+    /**
+     * Decodes the size part of the file name if necessary and returns the appropriate Long.
+     * @return The size of this message as a {@link Long}
+     */
+    public Long getSize() {
+        if (size == null) {
+            split();
+            if (sizeString == null)
+                return null;
+            size = Long.valueOf(sizeString.substring(3)); // skip the ",S=" part
+        }
+        return size;
+    }
+    
+    /**
+     * Decodes the time part of the file name if necessary and returns the appropriate Date.
+     * @return The time of this message as a {@link Date}
+     */
+    public Date getInternalDate() {
+        if (internalDate == null) {
+            split();
+            if (timestamp == null)
+                return null;
+            internalDate = new Date(Long.valueOf(timestamp) * 1000);
+        }
+        return internalDate;
+    }
+    
+    /**
+     * Composes the base name consisting of timestamp, unique string and host name
+     * witout the size and flags.
+     * @return The base name
+     */
+    public String getBaseName() {
+        split();
+        StringBuffer baseName = new StringBuffer();
+        baseName.append(timestamp);
+        baseName.append(".");
+        baseName.append(uniqueString);
+        baseName.append(".");
+        baseName.append(hostname);
+        return baseName.toString();
+    }
+    
+    /**
+     * Creates a String that represents the provided Flags  
+     * @param flags The flags to encode
+     * @return A String valid for Maildir
+     */
+    public String encodeFlags(Flags flags) {
+        StringBuffer flagsString = new StringBuffer(":2,");
+        if (flags.contains(Flags.Flag.DRAFT))
+            flagsString.append(FLAG_DRAFT);
+        if (flags.contains(Flags.Flag.FLAGGED))
+            flagsString.append(FLAG_FLAGGED);
+        if (flags.contains(Flags.Flag.ANSWERED))
+            flagsString.append(FLAG_ANSWERD);
+        if (flags.contains(Flags.Flag.SEEN))
+            flagsString.append(FLAG_SEEN);
+        if (flags.contains(Flags.Flag.DELETED))
+            flagsString.append(FLAG_DELETED);
+        return flagsString.toString();
+    }
+    
+    /**
+     * Takes a String which is "Maildir encoded" and translates it
+     * into a {@link Flags} object.
+     * @param flagsString The String with the flags
+     * @return A Flags object containing the flags read form the String
+     */
+    public Flags decodeFlags(String flagsString) {
+        Flags flags = new Flags();
+        if (flagsString.contains(FLAG_DRAFT))
+            flags.add(Flags.Flag.DRAFT);
+        if (flagsString.contains(FLAG_FLAGGED))
+            flags.add(Flags.Flag.FLAGGED);
+        if (flagsString.contains(FLAG_ANSWERD))
+            flags.add(Flags.Flag.ANSWERED);
+        if (flagsString.contains(FLAG_SEEN))
+            flags.add(Flags.Flag.SEEN);
+        if (flagsString.contains(FLAG_DELETED))
+            flags.add(Flags.Flag.DELETED);
+        return flags;
+    }
+    
+    /**
+     * Returns and increases a global counter for the number
+     * of deliveries done since the server has been started.
+     * This is used for the creation of message names.
+     * @return The number of (attempted) deliveries until now
+     */
+    static private long getNextDeliveryNumber() {
+        return deliveries.getAndIncrement();
+    }
+    
+    /**
+     * Create a name for a message according to
+     * http://cr.yp.to/proto/maildir.html<br/>
+     * The following elements are used:
+     * <br><br/>
+     * "A unique name has three pieces, separated by dots. On the left is the result of time()
+     * or the second counter from gettimeofday(). On the right is the result of gethostname().
+     * (To deal with invalid host names, replace / with \057 and : with \072.)
+     * In the middle is a delivery identifier, discussed below.
+     * <br/><br/>
+     * Modern delivery identifiers are created by concatenating enough of the following strings
+     * to guarantee uniqueness:
+     * <br/><br/>
+     * [...]<br/>
+     * * Rn, where n is (in hexadecimal) the output of the operating system's unix_cryptorandomnumber() system call, or an equivalent source such as /dev/urandom. Unfortunately, some operating systems don't include cryptographic random number generators.<br/>
+     * [...]<br/>
+     * * Mn, where n is (in decimal) the microsecond counter from the same gettimeofday() used for the left part of the unique name.<br/>
+     * * Pn, where n is (in decimal) the process ID.<br/>
+     * * Qn, where n is (in decimal) the number of deliveries made by this process.<br/>
+     * <br/>
+     * [...]"
+     * 
+     * @return
+     */
+    public static MaildirMessageName createUniqueName(MaildirFolder parentFolder, long size) {
+        String timestamp = String.valueOf(System.currentTimeMillis());
+        timestamp = timestamp.substring(0, timestamp.length()-3); // time in seconds
+        StringBuffer uniquePart = new StringBuffer();
+        uniquePart.append(Integer.toHexString(random.nextInt())); // random number as hex
+        uniquePart.append(timestamp.substring(timestamp.length()-3)); // milliseconds
+        uniquePart.append(processName); // process name
+        uniquePart.append(getNextDeliveryNumber()); // delivery number
+        String sizeString = ",S=" + String.valueOf(size);
+        String fullName = timestamp + "." + uniquePart.toString() + "." + currentHostname + sizeString;
+        MaildirMessageName uniqueName = new MaildirMessageName(parentFolder, fullName);
+        uniqueName.timestamp = timestamp;
+        uniqueName.uniqueString = uniquePart.toString();
+        uniqueName.hostname = currentHostname;
+        uniqueName.sizeString = sizeString;
+        uniqueName.isSplit = true;
+        uniqueName.size = size;
+        return uniqueName;
+    }
+    
+    public static FilenameFilter createRegexFilter(final Pattern pattern) {
+        return new FilenameFilter() {
+            public boolean accept(File dir, String name) {
+                Matcher matcher = pattern.matcher(name);
+                return matcher.matches();
+            }
+        };
+    }
+    
+    public static String optional(String pattern) {
+        return "(" + pattern + ")?";
+    }
+    
+    @Override
+    public String toString() {
+        return getFullName();
+    }
+    
+}



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