james-server-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From e...@apache.org
Subject svn commit: r995669 - in /james/server/trunk: spring-deployment/src/main/config/james/ spring-deployment/src/main/config/james/META-INF/ user-function/ user-function/src/main/java/org/apache/james/vut/ user-function/src/main/java/org/apache/james/vut/m...
Date Fri, 10 Sep 2010 04:57:44 GMT
Author: eric
Date: Fri Sep 10 04:57:44 2010
New Revision: 995669

URL: http://svn.apache.org/viewvc?rev=995669&view=rev
Log:
Implement JPAVirtualUserTable + Code format (JAMES-1037)

Added:
    james/server/trunk/user-function/src/main/java/org/apache/james/vut/JPAVirtualUserTable.java
    james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/
    james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/JPAVirtualUser.java
    james/server/trunk/user-function/src/test/java/org/apache/james/vut/JPAVirtualUserTableTest.java
Modified:
    james/server/trunk/spring-deployment/src/main/config/james/META-INF/persistence.xml
    james/server/trunk/spring-deployment/src/main/config/james/virtualusertable-store.xml
    james/server/trunk/user-function/pom.xml
    james/server/trunk/user-function/src/main/java/org/apache/james/vut/JDBCVirtualUserTable.java
    james/server/trunk/user-function/src/main/java/org/apache/james/vut/XMLVirtualUserTable.java
    james/server/trunk/user-function/src/test/java/org/apache/james/vut/JDBCVirtualUserTableTest.java
    james/server/trunk/user-function/src/test/java/org/apache/james/vut/XMLVirtualUserTableTest.java
    james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/AbstractVirtualUserTable.java
    james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/VirtualUserTableUtil.java
    james/server/trunk/user-library/src/test/java/org/apache/james/vut/AbstractVirtualUserTableTest.java

Modified: james/server/trunk/spring-deployment/src/main/config/james/META-INF/persistence.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/spring-deployment/src/main/config/james/META-INF/persistence.xml?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/spring-deployment/src/main/config/james/META-INF/persistence.xml (original)
+++ james/server/trunk/spring-deployment/src/main/config/james/META-INF/persistence.xml Fri Sep 10 04:57:44 2010
@@ -30,10 +30,12 @@
         <!-- UsersRepository -->
         <class>org.apache.james.userrepository.JPAUser</class>
 
-
         <!-- DomainList -->
         <class>org.apache.james.domain.JPADomain</class>
 
+        <!-- VirtualUser -->
+        <class>org.apache.james.vut.model.JPAVirtualUser</class>
+
         <properties>
             <!--  Create tables on startup -->
             <property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)"/>

Modified: james/server/trunk/spring-deployment/src/main/config/james/virtualusertable-store.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/spring-deployment/src/main/config/james/virtualusertable-store.xml?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/spring-deployment/src/main/config/james/virtualusertable-store.xml (original)
+++ james/server/trunk/spring-deployment/src/main/config/james/virtualusertable-store.xml Fri Sep 10 04:57:44 2010
@@ -41,9 +41,16 @@
     <!-- Use these configurations to store the VirtualUserTable in a database. -->
 
     <!-- The DefaultVirtualUserTable  for storing James' VirtualUserTable mappings. -->
+    <!-- 
     <table name="DefaultVirtualUserTable" class="org.apache.james.vut.JDBCVirtualUserTable" destinationURL="db://maildb/VirtualUserTable">
         <recursiveMapping> true </recursiveMapping>
         <mappingLimit> 10 </mappingLimit>
         <sqlFile>file://conf/sqlResources.xml</sqlFile>
     </table>
-</virtualusertable-store>
\ No newline at end of file
+    -->
+    <!-- The DefaultVirtualUserTable  for storing James' VirtualUserTable mappings. -->
+    <table name="DefaultVirtualUserTable" class="org.apache.james.vut.JPAVirtualUserTable" destinationURL="db://maildb/VirtualUserTable">
+        <recursiveMapping> true </recursiveMapping>
+        <mappingLimit> 10 </mappingLimit>
+    </table>
+</virtualusertable-store>

Modified: james/server/trunk/user-function/pom.xml
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/pom.xml?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-function/pom.xml (original)
+++ james/server/trunk/user-function/pom.xml Fri Sep 10 04:57:44 2010
@@ -36,7 +36,7 @@
         <artifactId>openjpa-maven-plugin</artifactId>
         <version>1.0</version>
         <configuration>
-          <includes>org/apache/james/userrepository/JPAUser.class</includes>
+          <includes>org/apache/james/userrepository/JPAUser.class,org/apache/james/vut/model/JPAVirtualUser.class</includes>
           <addDefaultConstructor>true</addDefaultConstructor>
           <enforcePropertyRestrictions>true</enforcePropertyRestrictions>
           <toolProperties>
@@ -46,7 +46,7 @@
             </property>   
             <property>
               <name>metaDataFactory</name>
-              <value>jpa(Types=org.apache.james.userrepository.JPAUser)</value>
+              <value>jpa(Types=org.apache.james.userrepository.JPAUser;org.apache.james.vut.model.JPAVirtualUser)</value>
             </property>           
           </toolProperties>
         </configuration>  

Modified: james/server/trunk/user-function/src/main/java/org/apache/james/vut/JDBCVirtualUserTable.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/main/java/org/apache/james/vut/JDBCVirtualUserTable.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-function/src/main/java/org/apache/james/vut/JDBCVirtualUserTable.java (original)
+++ james/server/trunk/user-function/src/main/java/org/apache/james/vut/JDBCVirtualUserTable.java Fri Sep 10 04:57:44 2010
@@ -45,8 +45,11 @@ import org.apache.james.util.sql.JDBCUti
 import org.apache.james.util.sql.SqlResources;
 
 /**
+ * Class responsible to implement the Virtual User Table in database with JDBC access.
  * 
+ * @deprecated use JPAVirtualUserTable
  */
+@Deprecated
 public class JDBCVirtualUserTable extends AbstractVirtualUserTable {
 
     private DataSourceSelector datasources = null;
@@ -58,7 +61,7 @@ public class JDBCVirtualUserTable extend
     /**
      * Contains all of the sql strings for this component.
      */
-    protected SqlResources sqlQueries;
+    private SqlResources sqlQueries;
     
     /**
      * The name of the SQL configuration file to be used to configure this repository.
@@ -67,61 +70,14 @@ public class JDBCVirtualUserTable extend
     
     private FileSystem fileSystem;
 
-    public void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException {
-        
-        String destination = conf.getString("[@destinationURL]",null);
-    
-        if (destination == null) {
-            throw new ConfigurationException("destinationURL must configured");
-        }
-
-        // normalize the destination, to simplify processing.
-        if ( ! destination.endsWith("/") ) {
-            destination += "/";
-        }
-        // Parse the DestinationURL for the name of the datasource,
-        // the table to use, and the (optional) repository Key.
-        // Split on "/", starting after "db://"
-        List<String> urlParams = new ArrayList<String>();
-        int start = 5;
-        
-        int end = destination.indexOf('/', start);
-        while ( end > -1 ) {
-            urlParams.add(destination.substring(start, end));
-            start = end + 1;
-            end = destination.indexOf('/', start);
-        }
-
-        // Build SqlParameters and get datasource name from URL parameters
-        if (urlParams.size() == 0) {
-            StringBuffer exceptionBuffer =
-                new StringBuffer(256)
-                        .append("Malformed destinationURL - Must be of the format '")
-                        .append("db://<data-source>'.  Was passed ")
-                        .append(conf.getString("[@destinationURL]"));
-            throw new ConfigurationException(exceptionBuffer.toString());
-        }
-        
-        if (urlParams.size() >= 1) {
-            dataSourceName = (String)urlParams.get(0);
-        }
-        
-        if (urlParams.size() >= 2) {
-            tableName = (String)urlParams.get(1);
-        }
-
-        if (getLogger().isDebugEnabled()) {
-            StringBuffer logBuffer =
-                new StringBuffer(128)
-                        .append("Parsed URL: table = '")
-                        .append(tableName)
-                        .append("'");
-            getLogger().debug(logBuffer.toString());
+    /**
+     * The JDBCUtil helper class
+     */
+    private final JDBCUtil theJDBCUtil = new JDBCUtil() {
+        protected void delegatedLog(String logString) {
+            getLogger().debug("JDBCVirtualUserTable: " + logString);
         }
-    
-        sqlFileName = conf.getString("sqlFile");
-        
-    }
+    };
 
     @PostConstruct
     public void init() throws Exception {
@@ -199,14 +155,10 @@ public class JDBCVirtualUserTable extend
         }
     }
     
-    /**
-     * The JDBCUtil helper class
-     */
-    private final JDBCUtil theJDBCUtil = new JDBCUtil() {
-        protected void delegatedLog(String logString) {
-            getLogger().debug("JDBCVirtualUserTable: " + logString);
-        }
-    };
+    @Resource(name="filesystem")
+    public void setFileSystem(FileSystem fileSystem) {
+        this.fileSystem = fileSystem;
+    }
     
     public void setDataSource(DataSource dataSourceComponent) {
         this.dataSourceComponent = dataSourceComponent;
@@ -217,9 +169,78 @@ public class JDBCVirtualUserTable extend
         this.datasources = datasources;
     }
 
-    @Resource(name="filesystem")
-    public void setFileSystem(FileSystem fileSystem) {
-        this.fileSystem = fileSystem;
+    protected void doConfigure(HierarchicalConfiguration conf) throws ConfigurationException {
+        
+        String destination = conf.getString("[@destinationURL]",null);
+    
+        if (destination == null) {
+            throw new ConfigurationException("destinationURL must configured");
+        }
+    
+        // normalize the destination, to simplify processing.
+        if ( ! destination.endsWith("/") ) {
+            destination += "/";
+        }
+        // Parse the DestinationURL for the name of the datasource,
+        // the table to use, and the (optional) repository Key.
+        // Split on "/", starting after "db://"
+        List<String> urlParams = new ArrayList<String>();
+        int start = 5;
+        
+        int end = destination.indexOf('/', start);
+        while ( end > -1 ) {
+            urlParams.add(destination.substring(start, end));
+            start = end + 1;
+            end = destination.indexOf('/', start);
+        }
+    
+        // Build SqlParameters and get datasource name from URL parameters
+        if (urlParams.size() == 0) {
+            StringBuffer exceptionBuffer =
+                new StringBuffer(256)
+                        .append("Malformed destinationURL - Must be of the format '")
+                        .append("db://<data-source>'.  Was passed ")
+                        .append(conf.getString("[@destinationURL]"));
+            throw new ConfigurationException(exceptionBuffer.toString());
+        }
+        
+        if (urlParams.size() >= 1) {
+            dataSourceName = (String)urlParams.get(0);
+        }
+        
+        if (urlParams.size() >= 2) {
+            tableName = (String)urlParams.get(1);
+        }
+    
+        if (getLogger().isDebugEnabled()) {
+            StringBuffer logBuffer =
+                new StringBuffer(128)
+                        .append("Parsed URL: table = '")
+                        .append(tableName)
+                        .append("'");
+            getLogger().debug(logBuffer.toString());
+        }
+    
+        sqlFileName = conf.getString("sqlFile");
+        
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#addMappingInternal(String, String, String)
+     */
+    protected boolean addMappingInternal(String user, String domain, String regex) throws InvalidMappingException {
+
+        String newUser = getUserString(user);
+        String newDomain = getDomainString(domain);
+        Collection<String> map =  getUserDomainMappings(newUser,newDomain);
+
+        if (map != null && map.size() != 0) {
+            map.add(regex);
+            return updateMapping(newUser,newDomain,VirtualUserTableUtil.CollectionToMapping(map));
+        }
+    
+        return addRawMapping(newUser,newDomain,regex);
+    
     }
     
     /**
@@ -254,13 +275,74 @@ public class JDBCVirtualUserTable extend
     }
     
     /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#mapAddress(java.lang.String, java.lang.String)
+     */
+    protected Collection<String> getUserDomainMappingsInternal(String user, String domain) {
+        Connection conn = null;
+        PreparedStatement mappingStmt = null;
+        try {
+            conn = dataSourceComponent.getConnection();
+            mappingStmt = conn.prepareStatement(sqlQueries.getSqlString("selectUserDomainMapping", true));
+            ResultSet mappingRS = null;
+            try {
+                mappingStmt.setString(1, user);
+                mappingStmt.setString(2, domain);
+                mappingRS = mappingStmt.executeQuery();
+                if (mappingRS.next()) {
+                    return VirtualUserTableUtil.mappingToCollection(mappingRS.getString(1));
+                }
+            } finally {
+                theJDBCUtil.closeJDBCResultSet(mappingRS);
+            }
+        } catch (SQLException sqle) {
+            getLogger().error("Error accessing database", sqle);
+        } finally {
+            theJDBCUtil.closeJDBCStatement(mappingStmt);
+            theJDBCUtil.closeJDBCConnection(conn);
+        }
+        return null;
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#getAllMappingsInternal()
+     */
+    protected Map<String,Collection<String>> getAllMappingsInternal() {
+        Connection conn = null;
+        PreparedStatement mappingStmt = null;
+        Map<String,Collection<String>> mapping = new HashMap<String,Collection<String>>();
+        try {
+            conn = dataSourceComponent.getConnection();
+            mappingStmt = conn.prepareStatement(sqlQueries.getSqlString("selectAllMappings", true));
+            ResultSet mappingRS = null;
+            try {
+                mappingRS = mappingStmt.executeQuery();
+                while(mappingRS.next()) {
+                    String user = mappingRS.getString(1);
+                    String domain = mappingRS.getString(2);
+                    String map = mappingRS.getString(3);
+                    mapping.put(user + "@" + domain, VirtualUserTableUtil.mappingToCollection(map));
+                }
+                if (mapping.size() > 0 ) return mapping;
+            } finally {
+                theJDBCUtil.closeJDBCResultSet(mappingRS);
+            }
+            
+        } catch (SQLException sqle) {
+            getLogger().error("Error accessing database", sqle);
+        } finally {
+            theJDBCUtil.closeJDBCStatement(mappingStmt);
+            theJDBCUtil.closeJDBCConnection(conn);
+        }
+        return null;
+    }
+    
+    /**
      * @see org.apache.james.impl.vut.AbstractVirtualUserTable#removeMappingInternal(String, String, String)
      */
-    public boolean removeMappingInternal(String user, String domain, String mapping) throws InvalidMappingException {
+    protected boolean removeMappingInternal(String user, String domain, String mapping) throws InvalidMappingException {
         String newUser = getUserString(user);
         String newDomain = getDomainString(domain);
         Collection<String> map = getUserDomainMappings(newUser,newDomain);
-
         if (map != null && map.size() > 1) {
             map.remove(mapping);
             return updateMapping(newUser,newDomain,VirtualUserTableUtil.CollectionToMapping(map));
@@ -269,26 +351,7 @@ public class JDBCVirtualUserTable extend
         }
     }
 
-
-    /**
-     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#addMappingInternal(String, String, String)
-     */
-    public boolean addMappingInternal(String user, String domain, String regex) throws InvalidMappingException {
-
-        String newUser = getUserString(user);
-        String newDomain = getDomainString(domain);
-        Collection<String> map =  getUserDomainMappings(newUser,newDomain);
-
-        if (map != null && map.size() != 0) {
-            map.add(regex);
-            return updateMapping(newUser,newDomain,VirtualUserTableUtil.CollectionToMapping(map));
-        }
-    
-        return addRawMapping(newUser,newDomain,regex);
-    
-    }
-    
-    /**
+   /**
      * Update the mapping for the given user and domain
      * 
      * @param user the user
@@ -444,73 +507,4 @@ public class JDBCVirtualUserTable extend
         }
     }
     
-    /**
-     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#mapAddress(java.lang.String, java.lang.String)
-     */
-    protected Collection<String> getUserDomainMappingsInternal(String user, String domain) {
-        Connection conn = null;
-        PreparedStatement mappingStmt = null;
-        
-        try {
-            conn = dataSourceComponent.getConnection();
-            mappingStmt = conn.prepareStatement(sqlQueries.getSqlString("selectUserDomainMapping", true));
-
-            ResultSet mappingRS = null;
-            try {
-                mappingStmt.setString(1, user);
-                mappingStmt.setString(2, domain);
-                mappingRS = mappingStmt.executeQuery();
-                if (mappingRS.next()) {
-                    return VirtualUserTableUtil.mappingToCollection(mappingRS.getString(1));
-                }
-            } finally {
-                theJDBCUtil.closeJDBCResultSet(mappingRS);
-            }
-            
-        } catch (SQLException sqle) {
-            getLogger().error("Error accessing database", sqle);
-        } finally {
-            theJDBCUtil.closeJDBCStatement(mappingStmt);
-            theJDBCUtil.closeJDBCConnection(conn);
-        }
-        return null;
-    }
-
-    /**
-     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#getAllMappingsInternal()
-     */
-    public Map<String,Collection<String>> getAllMappingsInternal() {
-        Connection conn = null;
-        PreparedStatement mappingStmt = null;
-        Map<String,Collection<String>> mapping = new HashMap<String,Collection<String>>();
-        
-        try {
-            conn = dataSourceComponent.getConnection();
-            mappingStmt = conn.prepareStatement(sqlQueries.getSqlString("selectAllMappings", true));
-
-            ResultSet mappingRS = null;
-            try {
-                mappingRS = mappingStmt.executeQuery();
-                while(mappingRS.next()) {
-                    String user = mappingRS.getString(1);
-                    String domain = mappingRS.getString(2);
-                    String map = mappingRS.getString(3);
-                    
-                    mapping.put(user + "@" + domain,VirtualUserTableUtil.mappingToCollection(map));
-                }
-                
-                if (mapping.size() > 0 ) return mapping;
-            } finally {
-                theJDBCUtil.closeJDBCResultSet(mappingRS);
-            }
-            
-        } catch (SQLException sqle) {
-            getLogger().error("Error accessing database", sqle);
-        } finally {
-            theJDBCUtil.closeJDBCStatement(mappingStmt);
-            theJDBCUtil.closeJDBCConnection(conn);
-        }
-        return null;
-    }
-    
 }

Added: james/server/trunk/user-function/src/main/java/org/apache/james/vut/JPAVirtualUserTable.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/main/java/org/apache/james/vut/JPAVirtualUserTable.java?rev=995669&view=auto
==============================================================================
--- james/server/trunk/user-function/src/main/java/org/apache/james/vut/JPAVirtualUserTable.java (added)
+++ james/server/trunk/user-function/src/main/java/org/apache/james/vut/JPAVirtualUserTable.java Fri Sep 10 04:57:44 2010
@@ -0,0 +1,287 @@
+/****************************************************************
+ * 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.vut;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.persistence.EntityManager;
+import javax.persistence.EntityManagerFactory;
+import javax.persistence.EntityTransaction;
+import javax.persistence.PersistenceException;
+import javax.persistence.PersistenceUnit;
+
+import org.apache.james.api.vut.management.InvalidMappingException;
+import org.apache.james.impl.vut.AbstractVirtualUserTable;
+import org.apache.james.impl.vut.VirtualUserTableUtil;
+import org.apache.james.vut.model.JPAVirtualUser;
+
+/**
+ * Class responsible to implement the Virtual User Table in database with JPA access.
+ */
+public class JPAVirtualUserTable extends AbstractVirtualUserTable {
+
+    /**
+     * The entity manager to access the database.
+     */
+    private EntityManagerFactory entityManagerFactory;
+
+    /**
+     * Set the entity manager to use.
+     * 
+     * @param entityManagerFactory
+     */
+    @PersistenceUnit
+    public void setEntityManagerFactory(EntityManagerFactory entityManagerFactory) {
+        this.entityManagerFactory = entityManagerFactory;
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#addMappingInternal(String, String, String)
+     */
+    protected boolean addMappingInternal(String user, String domain, String regex) throws InvalidMappingException {
+        
+        String newUser = getUserString(user);
+        String newDomain = getDomainString(domain);
+        Collection<String> map = getUserDomainMappings(newUser,newDomain);
+    
+        if (map != null && map.size() != 0) {
+            map.add(regex);
+            return updateMapping(newUser, newDomain, VirtualUserTableUtil.CollectionToMapping(map));
+        }
+    
+        return addRawMapping(newUser,newDomain,regex);
+    
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#mapAddressInternal(java.lang.String, java.lang.String)
+     */
+    protected String mapAddressInternal(String user, String domain) {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        final EntityTransaction transaction = entityManager.getTransaction();
+        try {
+            transaction.begin();
+            List<JPAVirtualUser> virtualUsers = entityManager.createNamedQuery("selectMappings")
+                .setParameter("user", user)
+                .setParameter("domain", domain).getResultList();
+            transaction.commit();
+            if(virtualUsers.size() > 0) {
+                return virtualUsers.get(0).getTargetAddress();
+            }
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to remove domain", e);
+            if (transaction.isActive()) {
+                transaction.rollback();
+            }
+        } finally {
+            entityManager.close();
+        }
+        return null;
+    }
+    
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#mapAddress(java.lang.String, java.lang.String)
+     */
+    protected Collection<String> getUserDomainMappingsInternal(String user, String domain) {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        try {
+            List<JPAVirtualUser> virtualUsers = entityManager.createNamedQuery("selectUserDomainMapping")
+                .setParameter("user", user)
+                .setParameter("domain", domain).getResultList();
+            if (virtualUsers.size() > 0) {
+                return VirtualUserTableUtil.mappingToCollection(virtualUsers.get(0).getTargetAddress());
+            }
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to get user domain mappings", e);
+        } finally {
+            entityManager.close();
+        }
+        return null;
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#getAllMappingsInternal()
+     */
+    protected Map<String,Collection<String>> getAllMappingsInternal() {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        Map<String,Collection<String>> mapping = new HashMap<String,Collection<String>>();
+        try {
+            List<JPAVirtualUser> virtualUsers = entityManager.createNamedQuery("selectAllMappings").getResultList();
+            for (JPAVirtualUser virtualUser: virtualUsers) {
+                mapping.put(virtualUser.getUser()+ "@" + virtualUser.getDomain(), VirtualUserTableUtil.mappingToCollection(virtualUser.getTargetAddress()));
+            }
+            if (mapping.size() > 0) return mapping;
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to get all mappings", e);
+        } finally {
+            entityManager.close();
+        }
+        return null;
+    }
+
+    /**
+     * @see org.apache.james.impl.vut.AbstractVirtualUserTable#removeMappingInternal(String, String, String)
+     */
+    protected boolean removeMappingInternal(String user, String domain, String mapping) throws InvalidMappingException {
+        String newUser = getUserString(user);
+        String newDomain = getDomainString(domain);
+        Collection<String> map = getUserDomainMappings(newUser,newDomain);
+        if (map != null && map.size() > 1) {
+            map.remove(mapping);
+            return updateMapping(newUser,newDomain,VirtualUserTableUtil.CollectionToMapping(map));
+        } else {
+            return removeRawMapping(newUser,newDomain,mapping);
+        }
+    }
+
+    /**
+     * Update the mapping for the given user and domain
+     * 
+     * @param user the user
+     * @param domain the domain
+     * @param mapping the mapping
+     * @return true if update was successfully
+     */
+    private boolean updateMapping(String user, String domain, String mapping) {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        final EntityTransaction transaction = entityManager.getTransaction();
+        try {
+            transaction.begin();
+            int updated = entityManager.createNamedQuery("updateMapping")
+                .setParameter("targetAddress", mapping)
+                .setParameter("user", user)
+                .setParameter("domain", domain).executeUpdate();
+            transaction.commit();
+            if (updated > 0) {
+                return true;
+            }
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to update mapping", e);
+            if (transaction.isActive()) {
+                transaction.rollback();
+            }
+        } finally {
+            entityManager.close();
+        }
+        return false;
+    }
+    
+    
+    /**
+     * Remove a mapping for the given user and domain
+     * 
+     * @param user the user
+     * @param domain the domain
+     * @param mapping the mapping
+     * @return true if successful
+     */
+    private boolean removeRawMapping(String user, String domain, String mapping) {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        final EntityTransaction transaction = entityManager.getTransaction();
+        try {
+            transaction.begin();
+            int deleted = entityManager.createNamedQuery("deleteMapping")
+                .setParameter("user", user)
+                .setParameter("domain", domain)
+                .setParameter("targetAddress", mapping).executeUpdate();
+            transaction.commit();
+            if (deleted > 0) {
+                return true;
+            }
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to remove mapping", e);
+            if (transaction.isActive()) {
+                transaction.rollback();
+            }
+        } finally {
+            entityManager.close();
+        }
+        return false;
+    }
+    
+    /**
+     * Add mapping for given user and domain
+     * 
+     * @param user the user
+     * @param domain the domain
+     * @param mapping the mapping 
+     * @return true if successfully
+     */
+    private boolean addRawMapping(String user, String domain, String mapping) {
+        EntityManager entityManager = entityManagerFactory.createEntityManager();
+        final EntityTransaction transaction = entityManager.getTransaction();
+        try {
+            transaction.begin();
+            JPAVirtualUser jpaVirtualUser = new JPAVirtualUser(user, domain, mapping);
+            entityManager.persist(jpaVirtualUser);
+            transaction.commit();
+            return true;
+        } catch (PersistenceException e) {
+            getLogger().debug("Failed to save virtual user", e);
+            if (transaction.isActive()) {
+                transaction.rollback();
+            }
+        } finally {
+            entityManager.close();
+        }
+        return false;
+    }
+    
+    /**
+     * Return user String for the given argument
+     * 
+     * @param user the given user String
+     * @return user the user String
+     * @throws InvalidMappingException get thrown on invalid argument
+     */
+    private String getUserString(String user) throws InvalidMappingException {
+        if (user != null) {
+            if(user.equals(WILDCARD) || user.indexOf("@") < 0) {
+                return user;
+            } else {
+                throw new InvalidMappingException("Invalid user: " + user);
+            }
+        } else {
+            return WILDCARD;
+        }
+    }
+    
+    /**
+     * Return domain String for the given argument
+     * 
+     * @param domain the given domain String
+     * @return domainString the domain String
+     * @throws InvalidMappingException get thrown on invalid argument
+     */
+    private String getDomainString(String domain) throws InvalidMappingException {
+        if(domain != null) {
+            if (domain.equals(WILDCARD) || domain.indexOf("@") < 0) {
+                return domain;  
+            } else {
+                throw new InvalidMappingException("Invalid domain: " + domain);
+            }
+        } else {
+            return WILDCARD;
+        }
+    }
+    
+}

Modified: james/server/trunk/user-function/src/main/java/org/apache/james/vut/XMLVirtualUserTable.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/main/java/org/apache/james/vut/XMLVirtualUserTable.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-function/src/main/java/org/apache/james/vut/XMLVirtualUserTable.java (original)
+++ james/server/trunk/user-function/src/main/java/org/apache/james/vut/XMLVirtualUserTable.java Fri Sep 10 04:57:44 2010
@@ -30,7 +30,7 @@ import org.apache.james.impl.vut.Abstrac
 import org.apache.james.impl.vut.VirtualUserTableUtil;
 
 /**
- *
+ * Class responsible to implement the Virtual User Table in XML disk file.
  */
 public class XMLVirtualUserTable extends AbstractVirtualUserTable {
     
@@ -43,7 +43,7 @@ public class XMLVirtualUserTable extends
      * @see org.apache.james.impl.vut.AbstractVirtualUserTable#doConfigure(org.apache.commons.configuration.HierarchicalConfiguration)
      */
     @SuppressWarnings("unchecked")
-    public void doConfigure(HierarchicalConfiguration arg0) throws ConfigurationException {
+    protected void doConfigure(HierarchicalConfiguration arg0) throws ConfigurationException {
 
         List<String> mapConf = arg0.getList("mapping");
     
@@ -62,7 +62,7 @@ public class XMLVirtualUserTable extends
     /**
      * Not implemented
      */
-    public boolean addMappingInternal(String user, String domain, String mapping) {
+    protected boolean addMappingInternal(String user, String domain, String mapping) {
         // Not supported
         return false;
     }
@@ -81,7 +81,7 @@ public class XMLVirtualUserTable extends
     /**
      * Not implemented
      */
-    public boolean removeMappingInternal(String user, String domain, String mapping) {
+    protected boolean removeMappingInternal(String user, String domain, String mapping) {
         // Not supported
         return false;
     }
@@ -89,7 +89,7 @@ public class XMLVirtualUserTable extends
     /**
      * @see org.apache.james.impl.vut.AbstractVirtualUserTable#getUserDomainMappingsInternal(java.lang.String, java.lang.String)
      */
-    public Collection<String> getUserDomainMappingsInternal(String user, String domain) {
+    protected Collection<String> getUserDomainMappingsInternal(String user, String domain) {
         if (mappings == null) {
             return null;
         } else {
@@ -105,7 +105,7 @@ public class XMLVirtualUserTable extends
     /**
      * @see org.apache.james.impl.vut.AbstractVirtualUserTable#getAllMappingsInternal()
      */
-    public Map<String,Collection<String>> getAllMappingsInternal() {
+    protected Map<String,Collection<String>> getAllMappingsInternal() {
         if ( mappings != null && mappings.size() > 0) {
             Map<String,Collection<String>> mappingsNew = new HashMap<String,Collection<String>>();
             Iterator<String> maps = mappings.keySet().iterator();

Added: james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/JPAVirtualUser.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/JPAVirtualUser.java?rev=995669&view=auto
==============================================================================
--- james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/JPAVirtualUser.java (added)
+++ james/server/trunk/user-function/src/main/java/org/apache/james/vut/model/JPAVirtualUser.java Fri Sep 10 04:57:44 2010
@@ -0,0 +1,128 @@
+/****************************************************************
+ * 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.vut.model;
+
+import java.io.Serializable;
+
+import javax.persistence.Column;
+import javax.persistence.Entity;
+import javax.persistence.Id;
+import javax.persistence.IdClass;
+import javax.persistence.NamedQueries;
+import javax.persistence.NamedQuery;
+import javax.persistence.Table;
+
+/**
+ * VirtualUserTable class for the James Virtual User Table to be used for JPA persistence.
+ */
+@Entity(name = "JamesVirtualUserTable")
+@Table(name = "VIRTUALUSERTABLE")
+@NamedQueries( { 
+    @NamedQuery(name = "selectMappings", query = "SELECT vut FROM JamesVirtualUserTable vut WHERE (vut.user LIKE :user OR vut.user='*') and (vut.domain like :domain or vut.domain='*') ORDER BY vut.domain DESC"),
+    @NamedQuery(name = "selectUserDomainMapping", query = "SELECT vut FROM JamesVirtualUserTable vut WHERE vut.user=:user AND vut.domain=:domain"),
+    @NamedQuery(name = "selectAllMappings", query = "SELECT vut FROM JamesVirtualUserTable vut"), 
+    @NamedQuery(name = "deleteMapping", query = "DELETE FROM JamesVirtualUserTable vut WHERE vut.user=:user AND vut.domain=:domain AND vut.targetAddress=:targetAddress"),
+    @NamedQuery(name = "updateMapping", query = "UPDATE JamesVirtualUserTable vut SET vut.targetAddress=:targetAddress WHERE vut.user=:user AND vut.domain=:domain")
+})
+@IdClass(JPAVirtualUser.VirtualUserTableId.class)
+public class JPAVirtualUser {
+
+    public static class VirtualUserTableId implements Serializable {
+
+        private static final long serialVersionUID = 1L;
+
+        private String user;
+        
+        private String domain;
+        
+        public VirtualUserTableId() {}
+
+        @Override
+        public int hashCode() {
+            final int PRIME = 31;
+            int result = 1;
+            result = PRIME * result + (int) (user.hashCode() ^ (user.hashCode() >>> 32));
+            result = PRIME * result + (int) (domain.hashCode() ^ (domain.hashCode() >>> 32));
+            return result;
+        }
+
+        @Override
+        public boolean equals(Object obj) {
+            if (this == obj)
+                return true;
+            if (obj == null)
+                return false;
+            if (getClass() != obj.getClass())
+                return false;
+            final VirtualUserTableId other = (VirtualUserTableId) obj;
+            if (! user.equals(other.user))
+                return false;
+            if (! domain.equals(other.domain))
+                return false;
+            return true;
+        }
+    }
+
+    /**
+     * The name of the user. 
+     * Column name is chosen to be compatible with the JDBCVirtualUserTableList 
+     * (even if user will be probably translated by JPA to another name (example: USER0).
+     */
+    @Id
+    @Column(name = "user", nullable = false, length = 64)
+    private String user = "";
+    
+    /**
+     * The name of the domain.
+     * Column name is chosen to be compatible with the JDBCVirtualUserTableList.
+     */
+    @Id
+    @Column(name = "DOMAIN", nullable = false, length = 255)
+    private String domain = "";
+    
+    /**
+     * The target address. column name is chosen to be compatible with the JDBCVirtualUserTableList.
+     */
+    @Column(name = "TARGET_ADDRESS", nullable = false, length = 255)
+    private String targetAddress = "";
+    
+    /**
+     * Use this simple constructor to create a new VirtualUserTable.
+     * 
+     * @param user, domain and their associated targetAddress
+     */
+    public JPAVirtualUser(String user, String domain, String targetAddress) {
+        this.user = user;
+        this.domain = domain;
+        this.targetAddress = targetAddress;
+    }
+    
+    public String getUser() {
+        return user;
+    }
+
+    public String getDomain() {
+        return domain;
+    }
+
+    public String getTargetAddress() {
+        return targetAddress;
+    }
+
+}

Modified: james/server/trunk/user-function/src/test/java/org/apache/james/vut/JDBCVirtualUserTableTest.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/test/java/org/apache/james/vut/JDBCVirtualUserTableTest.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-function/src/test/java/org/apache/james/vut/JDBCVirtualUserTableTest.java (original)
+++ james/server/trunk/user-function/src/test/java/org/apache/james/vut/JDBCVirtualUserTableTest.java Fri Sep 10 04:57:44 2010
@@ -25,22 +25,25 @@ import org.apache.james.impl.vut.Abstrac
 import org.apache.james.test.mock.james.MockFileSystem;
 import org.apache.james.test.util.Util;
 
+/**
+ * Test the JDBC Virtual User Table implementation.
+ */
 public class JDBCVirtualUserTableTest extends AbstractVirtualUserTableTest {
     
     /**
      * @see org.apache.james.vut.AbstractVirtualUserTableTest#getVirtualUserTable()
      */
     protected AbstractVirtualUserTable getVirtualUserTable() throws Exception {
-        JDBCVirtualUserTable mr = new JDBCVirtualUserTable();
-        mr.setLog(new SimpleLog("MockLog"));
-        mr.setDataSourceSelector(Util.getDataSourceSelector());
-        mr.setFileSystem(new MockFileSystem());
+        JDBCVirtualUserTable virtualUserTable = new JDBCVirtualUserTable();
+        virtualUserTable.setLog(new SimpleLog("MockLog"));
+        virtualUserTable.setDataSourceSelector(Util.getDataSourceSelector());
+        virtualUserTable.setFileSystem(new MockFileSystem());
         DefaultConfigurationBuilder defaultConfiguration = new DefaultConfigurationBuilder();
         defaultConfiguration.addProperty("[@destinationURL]","db://maildb/VirtualUserTable");
         defaultConfiguration.addProperty("sqlFile","file://conf/sqlResources.xml");
-        mr.configure(defaultConfiguration);
-        mr.init();
-        return mr;
+        virtualUserTable.configure(defaultConfiguration);
+        virtualUserTable.init();
+        return virtualUserTable;
     }    
     
     /**

Added: james/server/trunk/user-function/src/test/java/org/apache/james/vut/JPAVirtualUserTableTest.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/test/java/org/apache/james/vut/JPAVirtualUserTableTest.java?rev=995669&view=auto
==============================================================================
--- james/server/trunk/user-function/src/test/java/org/apache/james/vut/JPAVirtualUserTableTest.java (added)
+++ james/server/trunk/user-function/src/test/java/org/apache/james/vut/JPAVirtualUserTableTest.java Fri Sep 10 04:57:44 2010
@@ -0,0 +1,110 @@
+/****************************************************************
+ * 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.vut;
+
+import java.util.HashMap;
+
+import org.apache.commons.configuration.DefaultConfigurationBuilder;
+import org.apache.commons.logging.impl.SimpleLog;
+import org.apache.james.api.vut.management.InvalidMappingException;
+import org.apache.james.impl.vut.AbstractVirtualUserTable;
+import org.apache.james.vut.model.JPAVirtualUser;
+import org.apache.openjpa.persistence.OpenJPAEntityManagerFactory;
+import org.apache.openjpa.persistence.OpenJPAPersistence;
+
+/**
+ * Test the JPA Virtual User Table implementation.
+ */
+public class JPAVirtualUserTableTest extends AbstractVirtualUserTableTest {
+    
+    /**
+     * The OpenJPA Entity Manager used for the tests.
+     */
+    private OpenJPAEntityManagerFactory factory;
+
+    /**
+     * The properties for the OpenJPA Entity Manager.
+     */
+    private HashMap<String, String> properties;
+    
+    @Override
+    protected void setUp() throws Exception {
+
+        // Use a memory database.
+        properties = new HashMap<String, String>();
+        properties.put("openjpa.ConnectionDriverName", org.apache.derby.jdbc.EmbeddedDriver.class.getName());
+        properties.put("openjpa.ConnectionURL", "jdbc:derby:memory:JPAVirtualUserTableTestDB;create=true");
+        properties.put("openjpa.Log", "JDBC=WARN, SQL=TRACE, Runtime=WARN");
+        properties.put("openjpa.ConnectionFactoryProperties", "PrettyPrint=true, PrettyPrintLineLength=72");
+        properties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
+        properties.put("openjpa.MetaDataFactory", "jpa(Types=" + JPAVirtualUser.class.getName() +")");
+        
+        factory = OpenJPAPersistence.getEntityManagerFactory(properties);
+
+        super.setUp();
+        
+    }
+
+    /**
+     * @see org.apache.james.vut.AbstractVirtualUserTableTest#getVirtualUserTable()
+     */
+    protected AbstractVirtualUserTable getVirtualUserTable() throws Exception {
+        JPAVirtualUserTable virtualUserTable = new JPAVirtualUserTable();
+        virtualUserTable.setLog(new SimpleLog("MockLog"));
+        virtualUserTable.setEntityManagerFactory(factory);
+        DefaultConfigurationBuilder defaultConfiguration = new DefaultConfigurationBuilder();
+        virtualUserTable.configure(defaultConfiguration);
+        return virtualUserTable;
+    }    
+    
+    /**
+     * @see org.apache.james.vut.AbstractVirtualUserTableTest#addMapping(java.lang.String, java.lang.String, java.lang.String, int)
+     */
+    protected boolean addMapping(String user, String domain, String mapping, int type) throws InvalidMappingException {
+        if (type == ERROR_TYPE) {
+            return virtualUserTable.addErrorMapping(user, domain, mapping);
+        } else if (type == REGEX_TYPE) {
+            return virtualUserTable.addRegexMapping(user, domain, mapping);
+        } else if (type == ADDRESS_TYPE) {
+            return virtualUserTable.addAddressMapping(user, domain, mapping);
+        } else if (type == ALIASDOMAIN_TYPE) {
+            return virtualUserTable.addAliasDomainMapping(domain, mapping);
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * @see org.apache.james.vut.AbstractVirtualUserTableTest#removeMapping(java.lang.String, java.lang.String, java.lang.String, int)
+     */
+    protected boolean removeMapping(String user, String domain, String mapping, int type) throws InvalidMappingException {
+        if (type == ERROR_TYPE) {
+            return virtualUserTable.removeErrorMapping(user, domain, mapping);
+        } else if (type == REGEX_TYPE) {
+            return virtualUserTable.removeRegexMapping(user, domain, mapping);
+        } else if (type == ADDRESS_TYPE) {
+            return virtualUserTable.removeAddressMapping(user, domain, mapping);
+        } else if (type == ALIASDOMAIN_TYPE) {
+            return virtualUserTable.removeAliasDomainMapping(domain, mapping);
+        } else {
+            return false;
+        }
+    }
+    
+}

Modified: james/server/trunk/user-function/src/test/java/org/apache/james/vut/XMLVirtualUserTableTest.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-function/src/test/java/org/apache/james/vut/XMLVirtualUserTableTest.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-function/src/test/java/org/apache/james/vut/XMLVirtualUserTableTest.java (original)
+++ james/server/trunk/user-function/src/test/java/org/apache/james/vut/XMLVirtualUserTableTest.java Fri Sep 10 04:57:44 2010
@@ -29,6 +29,9 @@ import org.apache.james.api.vut.manageme
 import org.apache.james.impl.vut.AbstractVirtualUserTable;
 import org.apache.james.impl.vut.VirtualUserTableUtil;
 
+/**
+ * Test the XML Virtual User Table implementation.
+ */
 public class XMLVirtualUserTableTest extends AbstractVirtualUserTableTest {
 
     private DefaultConfigurationBuilder defaultConfiguration = new DefaultConfigurationBuilder();
@@ -40,9 +43,9 @@ public class XMLVirtualUserTableTest ext
     }
 
     protected AbstractVirtualUserTable getVirtualUserTable() throws Exception {
-        XMLVirtualUserTable mr = new XMLVirtualUserTable();
-        mr.setLog(new SimpleLog("MockLog"));
-        return mr;
+        XMLVirtualUserTable virtualUserTable = new XMLVirtualUserTable();
+        virtualUserTable.setLog(new SimpleLog("MockLog"));
+        return virtualUserTable;
     }
     
     /**

Modified: james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/AbstractVirtualUserTable.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/AbstractVirtualUserTable.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/AbstractVirtualUserTable.java (original)
+++ james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/AbstractVirtualUserTable.java Fri Sep 10 04:57:44 2010
@@ -57,7 +57,7 @@ public abstract class AbstractVirtualUse
     public void configure(HierarchicalConfiguration config) throws ConfigurationException {
     	setRecursiveMapping(config.getBoolean("recursiveMapping", true));
         try {
-            setMappingLimit(config.getInt("mappingLimit",10));
+            setMappingLimit(config.getInt("mappingLimit", 10));
         } catch (IllegalArgumentException e) {
             throw new ConfigurationException(e.getMessage());
         }
@@ -316,16 +316,6 @@ public abstract class AbstractVirtualUse
         return mappings;
     }
     
-    
-    private boolean checkMapping(String user,String domain, String mapping) {
-       Collection<String> mappings = getUserDomainMappings(user,domain);
-       if (mappings != null && mappings.contains(mapping)) {
-           return false;
-       } else {
-           return true;
-       }
-    }
-
     /**
      * @see org.apache.james.api.vut.management.VirtualUserTableManagement#getUserDomainMappings(java.lang.String, java.lang.String)
      */
@@ -349,42 +339,6 @@ public abstract class AbstractVirtualUse
         return removeMappingInternal(null, aliasDomain, VirtualUserTable.ALIASDOMAIN_PREFIX + realDomain);
     }
     
-    /**
-     * Get all mappings for the given user and domain. If a aliasdomain mapping was found get sure it is in the map as first mapping. 
-     * 
-     * @param user the username
-     * @param domain the domain
-     * @return the mappings
-     */
-    private String mapAddress(String user, String domain) {
-
-        String mappings = mapAddressInternal(user, domain);
-
-        // check if we need to sort
-        // TODO: Maybe we should just return the aliasdomain mapping
-        if (mappings != null && mappings.indexOf(VirtualUserTable.ALIASDOMAIN_PREFIX) > -1) {
-            Collection<String> mapCol = VirtualUserTableUtil.mappingToCollection(mappings);
-            Iterator<String> mapIt = mapCol.iterator();
-        
-            List<String> col = new ArrayList<String>(mapCol.size());
-        
-            while (mapIt.hasNext()) {
-                int i = 0;
-                String mapping = mapIt.next().toString();
-        
-                if (mapping.startsWith(VirtualUserTable.ALIASDOMAIN_PREFIX)) {
-                    col.add(i,mapping);
-                    i++;
-                } else {
-                    col.add(mapping);
-                }
-            }
-            return VirtualUserTableUtil.CollectionToMapping(col);
-        } else {  
-            return mappings;
-        }
-    }
-      
     protected Log getLogger() {
         return logger;
     }
@@ -442,4 +396,49 @@ public abstract class AbstractVirtualUse
      */
     protected abstract String mapAddressInternal(String user, String domain);
     
+    /**
+     * Get all mappings for the given user and domain. If a aliasdomain mapping was found get sure it is in the map as first mapping. 
+     * 
+     * @param user the username
+     * @param domain the domain
+     * @return the mappings
+     */
+    private String mapAddress(String user, String domain) {
+
+        String mappings = mapAddressInternal(user, domain);
+
+        // check if we need to sort
+        // TODO: Maybe we should just return the aliasdomain mapping
+        if (mappings != null && mappings.indexOf(VirtualUserTable.ALIASDOMAIN_PREFIX) > -1) {
+            Collection<String> mapCol = VirtualUserTableUtil.mappingToCollection(mappings);
+            Iterator<String> mapIt = mapCol.iterator();
+        
+            List<String> col = new ArrayList<String>(mapCol.size());
+        
+            while (mapIt.hasNext()) {
+                int i = 0;
+                String mapping = mapIt.next().toString();
+        
+                if (mapping.startsWith(VirtualUserTable.ALIASDOMAIN_PREFIX)) {
+                    col.add(i,mapping);
+                    i++;
+                } else {
+                    col.add(mapping);
+                }
+            }
+            return VirtualUserTableUtil.CollectionToMapping(col);
+        } else {  
+            return mappings;
+        }
+    }
+      
+    private boolean checkMapping(String user,String domain, String mapping) {
+        Collection<String> mappings = getUserDomainMappings(user,domain);
+        if (mappings != null && mappings.contains(mapping)) {
+            return false;
+        } else {
+            return true;
+        }
+     }
+
 }

Modified: james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/VirtualUserTableUtil.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/VirtualUserTableUtil.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/VirtualUserTableUtil.java (original)
+++ james/server/trunk/user-library/src/main/java/org/apache/james/impl/vut/VirtualUserTableUtil.java Fri Sep 10 04:57:44 2010
@@ -171,7 +171,6 @@ public class VirtualUserTableUtil {
          ArrayList<String> map = new ArrayList<String>();
          StringTokenizer tokenizer = new StringTokenizer(rawMapping,
          VirtualUserTableUtil.getSeparator(rawMapping));
-
          while (tokenizer.hasMoreTokens()) {
              final String raw = tokenizer.nextToken().trim();
              map.add(raw);
@@ -187,12 +186,9 @@ public class VirtualUserTableUtil {
       */
      public static String CollectionToMapping(Collection map) {
          StringBuffer mapping = new StringBuffer();
-     
          Iterator mappings = map.iterator();
-     
          while (mappings.hasNext()) {
              mapping.append(mappings.next());
-         
              if (mappings.hasNext()) {
                  mapping.append(";");
              }

Modified: james/server/trunk/user-library/src/test/java/org/apache/james/vut/AbstractVirtualUserTableTest.java
URL: http://svn.apache.org/viewvc/james/server/trunk/user-library/src/test/java/org/apache/james/vut/AbstractVirtualUserTableTest.java?rev=995669&r1=995668&r2=995669&view=diff
==============================================================================
--- james/server/trunk/user-library/src/test/java/org/apache/james/vut/AbstractVirtualUserTableTest.java (original)
+++ james/server/trunk/user-library/src/test/java/org/apache/james/vut/AbstractVirtualUserTableTest.java Fri Sep 10 04:57:44 2010
@@ -30,6 +30,11 @@ import org.apache.james.api.vut.manageme
 import org.apache.james.impl.vut.AbstractVirtualUserTable;
 import org.apache.james.lifecycle.LifecycleUtil;
 
+/**
+ * The abstract test for the virtual user table.
+ * Contains tests related to simple, regexp, wildcard, error,...
+ * Extend this and instanciate the needed virtualUserTable implementation.
+ */
 public abstract class AbstractVirtualUserTableTest extends TestCase {
 
     protected AbstractVirtualUserTable virtualUserTable;
@@ -48,9 +53,9 @@ public abstract class AbstractVirtualUse
         Map<String,Collection<String>> mappings = virtualUserTable.getAllMappings();
 
         if (mappings != null) {
+            
             Iterator<String> mappingsIt = virtualUserTable.getAllMappings().keySet().iterator();
 
-
             while(mappingsIt.hasNext()) {
                 String key = mappingsIt.next().toString();
                 String args[] = key.split("@");
@@ -73,25 +78,6 @@ public abstract class AbstractVirtualUse
     
     }
 
-    private void removeMapping(String user, String domain, String rawMapping) throws InvalidMappingException {
-        if (rawMapping.startsWith(VirtualUserTable.ERROR_PREFIX)) {
-            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.ERROR_PREFIX.length()), ERROR_TYPE);
-        } else if (rawMapping.startsWith(VirtualUserTable.REGEX_PREFIX)) {
-            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.REGEX_PREFIX.length()), REGEX_TYPE);
-        } else if (rawMapping.startsWith(VirtualUserTable.ALIASDOMAIN_PREFIX)) {
-            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.ALIASDOMAIN_PREFIX.length()), ALIASDOMAIN_TYPE);
-        } else {
-            removeMapping(user, domain, rawMapping, ADDRESS_TYPE);
-        }
-    }
-
-    protected abstract AbstractVirtualUserTable getVirtualUserTable() throws Exception;
-
-    protected abstract boolean addMapping(String user , String domain, String mapping,int type)throws InvalidMappingException;
-
-    protected abstract boolean removeMapping(String user, String domain, String mapping, int type) throws InvalidMappingException;
-
-
     public void testStoreAndRetrieveRegexMapping() throws ErrorMappingException {
         
         String user = "test";
@@ -107,9 +93,8 @@ public abstract class AbstractVirtualUse
 
             assertTrue("Added virtual mapping", addMapping(user, domain, regex, REGEX_TYPE));
             assertTrue("Added virtual mapping", addMapping(user, domain, regex2, REGEX_TYPE));
-
-            assertEquals("Two mappings",virtualUserTable.getMappings(user, domain).size(), 2);           
-            assertEquals("One mappingline",virtualUserTable.getAllMappings().size(),1);
+            assertEquals("Two mappings", virtualUserTable.getMappings(user, domain).size(), 2);           
+            assertEquals("One mappingline", virtualUserTable.getAllMappings().size(), 1);
 
             assertTrue("remove virtual mapping", removeMapping(user, domain, regex, REGEX_TYPE));
 
@@ -121,9 +106,10 @@ public abstract class AbstractVirtualUse
             assertTrue("Invalid Mapping throw exception" , catched);
 
             assertTrue("remove virtual mapping", removeMapping(user, domain, regex2, REGEX_TYPE));
-            assertNull("No mapping",virtualUserTable.getMappings(user, domain));
 
-            assertNull("No mappings",virtualUserTable.getAllMappings());
+            assertNull("No mapping", virtualUserTable.getMappings(user, domain));
+
+            assertNull("No mappings", virtualUserTable.getAllMappings());
 
         } catch (InvalidMappingException e) {
             fail("Storing failed");
@@ -146,8 +132,8 @@ public abstract class AbstractVirtualUse
             assertTrue("Added virtual mapping", addMapping(user, domain, address, ADDRESS_TYPE));
             assertTrue("Added virtual mapping", addMapping(user, domain, address2, ADDRESS_TYPE));
 
-            assertEquals("Two mappings",virtualUserTable.getMappings(user, domain).size(),2);
-            assertEquals("One mappingline",virtualUserTable.getAllMappings().size(),1);
+            assertEquals("Two mappings", virtualUserTable.getMappings(user, domain).size(),2);
+            assertEquals("One mappingline", virtualUserTable.getAllMappings().size(),1);
 
             assertTrue("remove virtual mapping", removeMapping(user, domain, address, ADDRESS_TYPE));
 
@@ -166,8 +152,8 @@ public abstract class AbstractVirtualUse
 
             assertTrue("remove virtual mapping", removeMapping(user, domain, address2, ADDRESS_TYPE));
 
-            assertNull("No mapping",virtualUserTable.getMappings(user, domain));
-            assertNull("No mappings",virtualUserTable.getAllMappings());
+            assertNull("No mapping", virtualUserTable.getMappings(user, domain));
+            assertNull("No mappings", virtualUserTable.getAllMappings());
 
         } catch (InvalidMappingException e) {
             fail("Storing failed");
@@ -188,7 +174,7 @@ public abstract class AbstractVirtualUse
             assertNull("No mapping",virtualUserTable.getMappings(user, domain));
 
             assertTrue("Added virtual mapping", addMapping(user, domain, error, ERROR_TYPE));
-            assertEquals("One mappingline",virtualUserTable.getAllMappings().size(),1);
+            assertEquals("One mappingline", virtualUserTable.getAllMappings().size(),1);
 
             try {
                 virtualUserTable.getMappings(user, domain);
@@ -198,8 +184,8 @@ public abstract class AbstractVirtualUse
             assertTrue("Error Mapping throw exception" , catched);
 
             assertTrue("remove virtual mapping", removeMapping(user, domain, error, ERROR_TYPE));
-            assertNull("No mapping",virtualUserTable.getMappings(user, domain));
-            assertNull("No mappings",virtualUserTable.getAllMappings());
+            assertNull("No mapping", virtualUserTable.getMappings(user, domain));
+            assertNull("No mappings", virtualUserTable.getAllMappings());
 
         } catch (InvalidMappingException e) {
             fail("Storing failed");
@@ -300,4 +286,22 @@ public abstract class AbstractVirtualUse
 
     }
 
+    protected abstract AbstractVirtualUserTable getVirtualUserTable() throws Exception;
+
+    protected abstract boolean addMapping(String user , String domain, String mapping,int type)throws InvalidMappingException;
+
+    protected abstract boolean removeMapping(String user, String domain, String mapping, int type) throws InvalidMappingException;
+
+    private void removeMapping(String user, String domain, String rawMapping) throws InvalidMappingException {
+        if (rawMapping.startsWith(VirtualUserTable.ERROR_PREFIX)) {
+            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.ERROR_PREFIX.length()), ERROR_TYPE);
+        } else if (rawMapping.startsWith(VirtualUserTable.REGEX_PREFIX)) {
+            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.REGEX_PREFIX.length()), REGEX_TYPE);
+        } else if (rawMapping.startsWith(VirtualUserTable.ALIASDOMAIN_PREFIX)) {
+            removeMapping(user, domain, rawMapping.substring(VirtualUserTable.ALIASDOMAIN_PREFIX.length()), ALIASDOMAIN_TYPE);
+        } else {
+            removeMapping(user, domain, rawMapping, ADDRESS_TYPE);
+        }
+    }
+
 }



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


Mime
View raw message