archiva-commits mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From jdu...@apache.org
Subject svn commit: r705848 [2/3] - in /archiva/branches/archiva-struts2: ./ archiva-docs/ archiva-docs/src/site/ archiva-docs/src/site/apt/ archiva-jetty/ archiva-modules/archiva-base/archiva-common/src/main/java/org/apache/maven/archiva/common/utils/ archiva...
Date Sat, 18 Oct 2008 06:45:05 GMT
Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueArtifactIdConstraintTest.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueArtifactIdConstraintTest.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueArtifactIdConstraintTest.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueArtifactIdConstraintTest.java Fri Oct 17 23:45:02 2008
@@ -22,6 +22,7 @@
 import org.apache.commons.lang.StringUtils;
 import org.apache.maven.archiva.database.AbstractArchivaDatabaseTestCase;
 import org.apache.maven.archiva.database.ArchivaDAO;
+import org.apache.maven.archiva.database.ArchivaDatabaseException;
 import org.apache.maven.archiva.database.ArtifactDAO;
 import org.apache.maven.archiva.database.SimpleConstraint;
 import org.apache.maven.archiva.model.ArchivaArtifact;
@@ -62,9 +63,31 @@
     public void testConstraint()
         throws Exception
     {
-        ArchivaArtifact artifact;
+        setUpArtifacts();
 
-        // Setup artifacts in fresh DB.
+        assertConstraint( new String[] {}, new UniqueArtifactIdConstraint( "org.apache" ) );
+        assertConstraint( new String[] { "commons-lang" }, new UniqueArtifactIdConstraint( "commons-lang" ) );
+        assertConstraint( new String[] { "test-one" }, new UniqueArtifactIdConstraint( "org.apache.maven.test" ) );
+        assertConstraint( new String[] { "test-two", "test-bar" },
+                          new UniqueArtifactIdConstraint( "org.apache.maven.shared" ) );
+        assertConstraint( new String[] { "modellong" }, new UniqueArtifactIdConstraint( "org.codehaus.modello" ) );
+    }
+    
+    public void testConstraintDisregardGroupId()
+        throws Exception
+    {
+        setUpArtifacts();
+        
+        assertConstraintWithMultipleResultTypes( new String[] { "commons-lang", "test-one", "test-two", "test-two", "test-bar", "modellong" },
+                          new UniqueArtifactIdConstraint( "testable_repo", true ) );
+    }
+
+    private void setUpArtifacts()
+        throws ArchivaDatabaseException
+    {
+        ArchivaArtifact artifact;
+        
+     // Setup artifacts in fresh DB.
         artifact = createArtifact( "commons-lang", "commons-lang", "2.0" );
         artifactDao.saveArtifact( artifact );
 
@@ -88,26 +111,41 @@
 
         artifact = createArtifact( "org.codehaus.modello", "modellong", "3.0" );
         artifactDao.saveArtifact( artifact );
-
-        assertConstraint( new String[] {}, new UniqueArtifactIdConstraint( "org.apache" ) );
-        assertConstraint( new String[] { "commons-lang" }, new UniqueArtifactIdConstraint( "commons-lang" ) );
-        assertConstraint( new String[] { "test-one" }, new UniqueArtifactIdConstraint( "org.apache.maven.test" ) );
-        assertConstraint( new String[] { "test-two", "test-bar" },
-                          new UniqueArtifactIdConstraint( "org.apache.maven.shared" ) );
-        assertConstraint( new String[] { "modellong" }, new UniqueArtifactIdConstraint( "org.codehaus.modello" ) );
     }
-
+    
+    private void assertConstraintWithMultipleResultTypes( String[] artifactIds, SimpleConstraint constraint )
+        throws Exception
+    {
+        String prefix = "Unique Artifact IDs: ";
+    
+        List<Object[]> results = dao.query( constraint );
+        assertNotNull( prefix + "Not Null", results );
+        assertEquals( prefix + "Results.size", artifactIds.length, results.size() );
+    
+        List<String> expectedArtifactIds = Arrays.asList( artifactIds );
+    
+        Iterator<Object[]> it = results.iterator();
+        while ( it.hasNext() )
+        {
+            Object[] actualArtifactIds = (Object[]) it.next();            
+            String actualArtifactId = ( String ) actualArtifactIds[1];
+            assertTrue( prefix + "artifactId result should not be blank.", StringUtils.isNotBlank( actualArtifactId ) );
+            assertTrue( prefix + " artifactId result <" + actualArtifactId + "> exists in expected artifactIds.",
+                        expectedArtifactIds.contains( actualArtifactId ) );            
+        }
+    }
+    
     private void assertConstraint( String[] artifactIds, SimpleConstraint constraint )
     {
         String prefix = "Unique Artifact IDs: ";
 
-        List results = dao.query( constraint );
+        List<String> results = dao.query( constraint );
         assertNotNull( prefix + "Not Null", results );
         assertEquals( prefix + "Results.size", artifactIds.length, results.size() );
 
-        List expectedArtifactIds = Arrays.asList( artifactIds );
+        List<String> expectedArtifactIds = Arrays.asList( artifactIds );
 
-        Iterator it = results.iterator();
+        Iterator<String> it = results.iterator();
         while ( it.hasNext() )
         {
             String actualArtifactId = (String) it.next();

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueGroupIdConstraintTest.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueGroupIdConstraintTest.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueGroupIdConstraintTest.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-database/src/test/java/org/apache/maven/archiva/database/constraints/UniqueGroupIdConstraintTest.java Fri Oct 17 23:45:02 2008
@@ -230,8 +230,8 @@
 
         assertConstraint( new String[] { "org.codehaus.modello", "org.codehaus.mojo", "org.apache.archiva" },
                           new UniqueGroupIdConstraint( observableRepositories ) );
-    }
-
+    }   
+    
     private void assertConstraint( String[] expectedGroupIds, SimpleConstraint constraint )
         throws Exception
     {

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-reporting/archiva-report-manager/pom.xml
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-reporting/archiva-report-manager/pom.xml?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-reporting/archiva-report-manager/pom.xml (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-reporting/archiva-report-manager/pom.xml Fri Oct 17 23:45:02 2008
@@ -48,6 +48,11 @@
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
     </dependency>
+    <dependency>
+      <groupId>org.codehaus.plexus</groupId>
+      <artifactId>plexus-spring</artifactId>
+      <scope>test</scope>
+    </dependency>
   </dependencies>
   <build>
   </build>

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-scheduled/src/main/java/org/apache/maven/archiva/scheduled/executors/ArchivaRepositoryScanningTaskExecutor.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-scheduled/src/main/java/org/apache/maven/archiva/scheduled/executors/ArchivaRepositoryScanningTaskExecutor.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-scheduled/src/main/java/org/apache/maven/archiva/scheduled/executors/ArchivaRepositoryScanningTaskExecutor.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-scheduled/src/main/java/org/apache/maven/archiva/scheduled/executors/ArchivaRepositoryScanningTaskExecutor.java Fri Oct 17 23:45:02 2008
@@ -20,11 +20,17 @@
  */
 
 import org.apache.commons.collections.CollectionUtils;
+import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
 import org.apache.maven.archiva.configuration.ArchivaConfiguration;
 import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
 import org.apache.maven.archiva.database.ArchivaDAO;
+import org.apache.maven.archiva.database.ArchivaDatabaseException;
+import org.apache.maven.archiva.database.ObjectNotFoundException;
+import org.apache.maven.archiva.database.constraints.ArtifactsByRepositoryConstraint;
 import org.apache.maven.archiva.database.constraints.MostRecentRepositoryScanStatistics;
+import org.apache.maven.archiva.database.constraints.UniqueArtifactIdConstraint;
+import org.apache.maven.archiva.database.constraints.UniqueGroupIdConstraint;
 import org.apache.maven.archiva.model.RepositoryContentStatistics;
 import org.apache.maven.archiva.repository.RepositoryException;
 import org.apache.maven.archiva.repository.scanner.RepositoryScanStatistics;
@@ -38,6 +44,8 @@
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
 
+import java.io.File;
+import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -112,19 +120,59 @@
 
             log.info( "Finished repository task: " + stats.toDump( arepo ) );
             
-            // I hate jpox and modello
-            RepositoryContentStatistics dbstats = new RepositoryContentStatistics();
-            dbstats.setDuration( stats.getDuration() );
-            dbstats.setNewFileCount( stats.getNewFileCount() );
-            dbstats.setRepositoryId( stats.getRepositoryId() );
-            dbstats.setTotalFileCount( stats.getTotalFileCount() );
-            dbstats.setWhenGathered( stats.getWhenGathered() );
+            RepositoryContentStatistics dbstats = constructRepositoryStatistics( arepo, sinceWhen, results, stats );
             
-            dao.getRepositoryContentStatisticsDAO().saveRepositoryContentStatistics( dbstats );
+            dao.getRepositoryContentStatisticsDAO().saveRepositoryContentStatistics( dbstats );            
         }
         catch ( RepositoryException e )
-        {
+        {   
             throw new TaskExecutionException( "Repository error when executing repository job.", e );
-        }        
+        }    
     }
+
+    private RepositoryContentStatistics constructRepositoryStatistics( ManagedRepositoryConfiguration arepo,
+                                                                       long sinceWhen,
+                                                                       List<RepositoryContentStatistics> results,
+                                                                       RepositoryScanStatistics stats )        
+    {
+        // I hate jpox and modello <-- and so do I
+        RepositoryContentStatistics dbstats = new RepositoryContentStatistics();
+        dbstats.setDuration( stats.getDuration() );
+        dbstats.setNewFileCount( stats.getNewFileCount() );
+        dbstats.setRepositoryId( stats.getRepositoryId() );
+        dbstats.setTotalFileCount( stats.getTotalFileCount() );
+        dbstats.setWhenGathered( stats.getWhenGathered() );
+                
+        // total artifact count
+        try
+        {
+            List artifacts = dao.getArtifactDAO().queryArtifacts( 
+                      new ArtifactsByRepositoryConstraint( arepo.getId(), stats.getWhenGathered(), "groupId", true ) );            
+            dbstats.setTotalArtifactCount( artifacts.size() );
+        }
+        catch ( ObjectNotFoundException oe )
+        {
+            log.error( "Object not found in the database : " + oe.getMessage() );
+        }
+        catch ( ArchivaDatabaseException ae )
+        {   
+            log.error( "Error occurred while querying artifacts for artifact count : " + ae.getMessage() );
+        }
+        
+        // total repo size
+        long size = FileUtils.sizeOfDirectory( new File( arepo.getLocation() ) );
+        dbstats.setTotalSize( size );
+          
+          // total unique groups
+        List<String> repos = new ArrayList<String>();
+        repos.add( arepo.getId() ); 
+        
+        List<String> groupIds = dao.query( new UniqueGroupIdConstraint( repos ) );
+        dbstats.setTotalGroupCount( groupIds.size() );
+                
+        List<Object[]> artifactIds = dao.query( new UniqueArtifactIdConstraint( arepo.getId(), true ) );
+        dbstats.setTotalProjectCount( artifactIds.size() );
+                        
+        return dbstats;
+    }    
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-rss/src/main/java/org/apache/archiva/rss/processor/NewArtifactsRssFeedProcessor.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-rss/src/main/java/org/apache/archiva/rss/processor/NewArtifactsRssFeedProcessor.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-rss/src/main/java/org/apache/archiva/rss/processor/NewArtifactsRssFeedProcessor.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-rss/src/main/java/org/apache/archiva/rss/processor/NewArtifactsRssFeedProcessor.java Fri Oct 17 23:45:02 2008
@@ -89,7 +89,7 @@
         Calendar greaterThanThisDate = Calendar.getInstance( DateUtils.UTC_TIME_ZONE );
         greaterThanThisDate.add( Calendar.DATE, -( getNumberOfDaysBeforeNow() ) );
         
-        Constraint artifactsByRepo = new ArtifactsByRepositoryConstraint( repoId, greaterThanThisDate.getTime(), "whenGathered" );
+        Constraint artifactsByRepo = new ArtifactsByRepositoryConstraint( repoId, greaterThanThisDate.getTime(), "whenGathered", false );
         List<ArchivaArtifact> artifacts = artifactDAO.queryArtifacts( artifactsByRepo );
 
         List<RssFeedEntry> entries = processData( artifacts, true );

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaServletAuthenticator.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaServletAuthenticator.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaServletAuthenticator.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaServletAuthenticator.java Fri Oct 17 23:45:02 2008
@@ -93,11 +93,18 @@
         return true;
     }
 
-    public boolean isAuthorized( String principal, String repoId )
+    public boolean isAuthorized( String principal, String repoId, boolean isWriteRequest )
         throws UnauthorizedException
     {
         try
         {
+            String permission = ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS;
+
+            if ( isWriteRequest )
+            {
+                permission = ArchivaRoleConstants.OPERATION_REPOSITORY_UPLOAD;
+            }
+            
             User user = securitySystem.getUserManager().findUser( principal );
             if ( user.isLocked() )
             {
@@ -107,8 +114,7 @@
             AuthenticationResult authn = new AuthenticationResult( true, principal, null );
             SecuritySession securitySession = new DefaultSecuritySession( authn, user );
 
-            return securitySystem.isAuthorized( securitySession, ArchivaRoleConstants.OPERATION_REPOSITORY_ACCESS,
-                                                repoId );
+            return securitySystem.isAuthorized( securitySession, permission, repoId );
         }
         catch ( UserNotFoundException e )
         {

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaXworkUser.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaXworkUser.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaXworkUser.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ArchivaXworkUser.java Fri Oct 17 23:45:02 2008
@@ -85,4 +85,9 @@
         
         return guest;
     }
+    
+    public void setGuest( String guesT )
+    {
+        guest = guesT;
+    }
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ServletAuthenticator.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ServletAuthenticator.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ServletAuthenticator.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/main/java/org/apache/maven/archiva/security/ServletAuthenticator.java Fri Oct 17 23:45:02 2008
@@ -35,12 +35,46 @@
  */
 public interface ServletAuthenticator
 {
+    /**
+     * Authentication check for users.
+     * 
+     * @param request
+     * @param result
+     * @return
+     * @throws AuthenticationException
+     * @throws AccountLockedException
+     * @throws MustChangePasswordException
+     */
     public boolean isAuthenticated( HttpServletRequest request, AuthenticationResult result )
         throws AuthenticationException, AccountLockedException, MustChangePasswordException;
 
+    /**
+     * Authorization check for valid users.
+     * 
+     * @param request
+     * @param securitySession
+     * @param repositoryId
+     * @param isWriteRequest
+     * @return
+     * @throws AuthorizationException
+     * @throws UnauthorizedException
+     */
     public boolean isAuthorized( HttpServletRequest request, SecuritySession securitySession, String repositoryId,
         boolean isWriteRequest ) throws AuthorizationException, UnauthorizedException;
     
-    public boolean isAuthorized( String principal, String repoId )
+    /**
+     * Authorization check specific for user guest, which doesn't go through 
+     * HttpBasicAuthentication#getAuthenticationResult( HttpServletRequest request, HttpServletResponse response )
+     * since no credentials are attached to the request. 
+     * 
+     * See also MRM-911
+     * 
+     * @param principal
+     * @param repoId
+     * @param isWriteRequest
+     * @return
+     * @throws UnauthorizedException
+     */
+    public boolean isAuthorized( String principal, String repoId, boolean isWriteRequest )
         throws UnauthorizedException;
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/test/java/org/apache/maven/archiva/security/DefaultUserRepositoriesTest.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/test/java/org/apache/maven/archiva/security/DefaultUserRepositoriesTest.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/test/java/org/apache/maven/archiva/security/DefaultUserRepositoriesTest.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-security/src/test/java/org/apache/maven/archiva/security/DefaultUserRepositoriesTest.java Fri Oct 17 23:45:02 2008
@@ -19,19 +19,9 @@
  * under the License.
  */
 
-import java.io.File;
 import java.util.List;
 
-import org.apache.commons.io.FileUtils;
 import org.apache.commons.lang.StringUtils;
-import org.apache.maven.archiva.configuration.ArchivaConfiguration;
-import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
-import org.codehaus.plexus.spring.PlexusInSpringTestCase;
-import org.codehaus.plexus.redback.rbac.RBACManager;
-import org.codehaus.plexus.redback.role.RoleManager;
-import org.codehaus.plexus.redback.system.SecuritySystem;
-import org.codehaus.plexus.redback.users.User;
-import org.codehaus.plexus.redback.users.UserManager;
 
 /**
  * DefaultUserRepositoriesTest 
@@ -40,24 +30,14 @@
  * @version $Id$
  */
 public class DefaultUserRepositoriesTest
-    extends PlexusInSpringTestCase
-{
-    private static final String USER_GUEST = "guest";
-
-    private static final String USER_ADMIN = "admin";
-
-    private static final String USER_ALPACA = "alpaca";
-
-    private SecuritySystem securitySystem;
-
-    private RBACManager rbacManager;
-
-    private RoleManager roleManager;
-
-    private ArchivaConfiguration archivaConfiguration;
-
-    private UserRepositories userRepos;
-
+    extends AbstractSecurityTest
+{   
+    @Override
+    protected String getPlexusConfigLocation()
+    {
+        return "org/apache/maven/archiva/security/DefaultUserRepositoriesTest.xml";
+    }
+    
     public void testGetObservableRepositoryIds()
         throws Exception
     {
@@ -98,78 +78,9 @@
         }
     }
 
-    private void setupRepository( String repoId )
-        throws Exception
-    {
-        // Add repo to configuration.
-        ManagedRepositoryConfiguration repoConfig = new ManagedRepositoryConfiguration();
-        repoConfig.setId( repoId );
-        repoConfig.setName( "Testable repo <" + repoId + ">" );
-        repoConfig.setLocation( getTestPath( "target/test-repo/" + repoId ) );
-        archivaConfiguration.getConfiguration().addManagedRepository( repoConfig );
-
-        // Add repo roles to security.
-        userRepos.createMissingRepositoryRoles( repoId );
-    }
-
     private void assignGlobalRepositoryObserverRole( String principal )
         throws Exception
     {
         roleManager.assignRole( ArchivaRoleConstants.TEMPLATE_GLOBAL_REPOSITORY_OBSERVER, principal );
     }
-
-    private void assignRepositoryObserverRole( String principal, String repoId )
-        throws Exception
-    {
-        roleManager.assignTemplatedRole( ArchivaRoleConstants.TEMPLATE_REPOSITORY_OBSERVER, repoId, principal );
-    }
-
-    private User createUser( String principal, String fullname )
-    {
-        UserManager userManager = securitySystem.getUserManager();
-
-        User user = userManager.createUser( principal, fullname, principal + "@testable.archiva.apache.org" );
-        securitySystem.getPolicy().setEnabled( false );
-        userManager.addUser( user );
-        securitySystem.getPolicy().setEnabled( true );
-
-        return user;
-    }
-
-    @Override
-    protected void setUp()
-        throws Exception
-    {
-        super.setUp();
-
-        File srcConfig = getTestFile( "src/test/resources/repository-archiva.xml" );
-        File destConfig = getTestFile( "target/test-conf/archiva.xml" );
-
-        destConfig.getParentFile().mkdirs();
-        destConfig.delete();
-
-        FileUtils.copyFile( srcConfig, destConfig );
-
-        securitySystem = (SecuritySystem) lookup( SecuritySystem.class, "testable" );
-        rbacManager = (RBACManager) lookup( RBACManager.class, "memory" );
-        roleManager = (RoleManager) lookup( RoleManager.class, "default" );
-        userRepos = (UserRepositories) lookup( UserRepositories.class, "default" );
-        archivaConfiguration = (ArchivaConfiguration) lookup( ArchivaConfiguration.class );
-
-        // Some basic asserts.
-        assertNotNull( securitySystem );
-        assertNotNull( rbacManager );
-        assertNotNull( roleManager );
-        assertNotNull( userRepos );
-        assertNotNull( archivaConfiguration );
-
-        // Setup Admin User.
-        User adminUser = createUser( USER_ADMIN, "Admin User" );
-        roleManager.assignRole( ArchivaRoleConstants.TEMPLATE_SYSTEM_ADMIN, adminUser.getPrincipal().toString() );
-
-        // Setup Guest User.
-        User guestUser = createUser( USER_GUEST, "Guest User" );
-        roleManager.assignRole( ArchivaRoleConstants.TEMPLATE_GUEST, guestUser.getPrincipal().toString() );
-
-    }
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/java/org/apache/maven/archiva/web/action/reports/GenerateReportAction.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/java/org/apache/maven/archiva/web/action/reports/GenerateReportAction.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/java/org/apache/maven/archiva/web/action/reports/GenerateReportAction.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/java/org/apache/maven/archiva/web/action/reports/GenerateReportAction.java Fri Oct 17 23:45:02 2008
@@ -19,30 +19,48 @@
  * under the License.
  */
 
-import org.apache.struts2.interceptor.ServletRequestAware;
 import com.opensymphony.xwork2.Preparable;
+import org.apache.commons.lang.time.DateFormatUtils;
+import org.apache.commons.lang.time.DateUtils;
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
 import org.apache.maven.archiva.database.ArchivaDAO;
+import org.apache.maven.archiva.database.ArchivaDatabaseException;
 import org.apache.maven.archiva.database.Constraint;
+import org.apache.maven.archiva.database.ObjectNotFoundException;
+import org.apache.maven.archiva.database.RepositoryContentStatisticsDAO;
 import org.apache.maven.archiva.database.constraints.RangeConstraint;
+import org.apache.maven.archiva.database.constraints.RepositoryContentStatisticsByRepositoryConstraint;
 import org.apache.maven.archiva.database.constraints.RepositoryProblemByGroupIdConstraint;
 import org.apache.maven.archiva.database.constraints.RepositoryProblemByRepositoryIdConstraint;
 import org.apache.maven.archiva.database.constraints.RepositoryProblemConstraint;
 import org.apache.maven.archiva.database.constraints.UniqueFieldConstraint;
+import org.apache.maven.archiva.model.RepositoryContentStatistics;
 import org.apache.maven.archiva.model.RepositoryProblem;
 import org.apache.maven.archiva.model.RepositoryProblemReport;
+import org.apache.maven.archiva.reporting.ArchivaReportException;
+import org.apache.maven.archiva.reporting.DataLimits;
+import org.apache.maven.archiva.reporting.RepositoryStatistics;
+import org.apache.maven.archiva.reporting.RepositoryStatisticsReportGenerator;
 import org.apache.maven.archiva.security.ArchivaRoleConstants;
-import org.apache.maven.archiva.web.action.PlexusActionSupport;
 import org.codehaus.plexus.redback.rbac.Resource;
-import org.codehaus.plexus.redback.struts2.interceptor.SecureAction;
-import org.codehaus.plexus.redback.struts2.interceptor.SecureActionBundle;
-import org.codehaus.plexus.redback.struts2.interceptor.SecureActionException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
 
 import javax.servlet.http.HttpServletRequest;
+
+import java.text.ParseException;
 import java.util.ArrayList;
+import java.util.Calendar;
 import java.util.Collection;
+import java.util.Date;
 import java.util.List;
 import java.util.Map;
 import java.util.TreeMap;
+import org.apache.maven.archiva.web.action.PlexusActionSupport;
+import org.apache.struts2.interceptor.ServletRequestAware;
+import org.codehaus.plexus.redback.struts2.interceptor.SecureAction;
+import org.codehaus.plexus.redback.struts2.interceptor.SecureActionBundle;
+import org.codehaus.plexus.redback.struts2.interceptor.SecureActionException;
 
 /**
  * @plexus.component role="com.opensymphony.xwork2.Action" role-hint="generateReport"
@@ -51,10 +69,17 @@
     extends PlexusActionSupport
     implements SecureAction, ServletRequestAware, Preparable
 {
+    private Logger log = LoggerFactory.getLogger( GenerateReportAction.class );
+    
     /**
      * @plexus.requirement role-hint="jdo"
      */
     protected ArchivaDAO dao;
+    
+    /**
+     * @plexus.requirement
+     */
+    private ArchivaConfiguration archivaConfiguration;
 
     protected Constraint constraint;
 
@@ -90,13 +115,50 @@
     
     protected Map<String, List<RepositoryProblemReport>> repositoriesMap = 
     		new TreeMap<String, List<RepositoryProblemReport>>();
-
+    
+    // for statistics report
+    /**
+     * @plexus.requirement role-hint="simple"
+     */
+    private RepositoryStatisticsReportGenerator generator;
+    
+    private List<String> selectedRepositories = new ArrayList<String>();
+    
+    private List<String> availableRepositories;  
+    
+    private String startDate;
+    
+    private String endDate;
+    
+    private int reposSize;
+    
+    private String selectedRepo;
+    
+    private List<RepositoryStatistics> repositoryStatistics = new ArrayList<RepositoryStatistics>();
+    
+    private DataLimits limits = new DataLimits();
+    
+    private String[] datePatterns = new String[] { "MM/dd/yy", "MM/dd/yyyy", "MMMMM/dd/yyyy", "MMMMM/dd/yy", 
+        "dd MMMMM yyyy", "dd/MM/yy", "dd/MM/yyyy", "yyyy/MM/dd" };
+    
     public void prepare()
     {
         repositoryIds = new ArrayList<String>();
         repositoryIds.add( ALL_REPOSITORIES ); // comes first to be first in the list
         repositoryIds.addAll(
             dao.query( new UniqueFieldConstraint( RepositoryProblem.class.getName(), "repositoryId" ) ) );
+        
+        availableRepositories = new ArrayList<String>();
+     
+        // remove selected repositories in the option for the statistics report
+        availableRepositories.addAll( archivaConfiguration.getConfiguration().getManagedRepositoriesAsMap().keySet() );        
+        for( String repo : selectedRepositories )
+        {
+            if( availableRepositories.contains( repo ) )
+            {
+                availableRepositories.remove( repo );
+            }
+        }
     }
 
     public Collection<String> getRepositoryIds()
@@ -104,10 +166,202 @@
         return repositoryIds;
     }
 
-    @Override
+    /**
+     * Generate the statistics report.
+     * 
+     * check whether single repo report or comparison report
+     * 1. if it is a single repository, get all the statistics for the repository on the specified date
+     *    - if no date is specified, get only the latest 
+     *          (total page = 1 --> no pagination since only the most recent stats will be displayed)
+     *    - otherwise, get everything within the date range (total pages = repo stats / rows per page)
+     *       - required params: repository, startDate, endDate
+     *       
+     * 2. if multiple repositories, get the latest statistics on each repository on the specified date
+     *    - if no date is specified, use the current date endDate
+     *       - required params: repositories, endDate
+     *    - total pages = repositories / rows per page
+     * 
+     * @return
+     */
+    public String generateStatistics()
+    {   
+        if( rowCount < 10 )
+        {
+            addFieldError( "rowCount", "Row count must be larger than 10." );
+            return INPUT;
+        }
+        reposSize = selectedRepositories.size();
+        Date startDateInDateFormat = null;
+        Date endDateInDateFormat = null;
+        
+        if( startDate == null || "".equals( startDate ) )
+        {
+            startDateInDateFormat = getDefaultStartDate();
+        }
+        else
+        {
+            try
+            {
+                startDateInDateFormat = DateUtils.parseDate( startDate, datePatterns );
+            }
+            catch ( ParseException e )
+            {
+                addFieldError( "startDate", "Invalid date format.");
+                return INPUT;
+            }
+        }
+        
+        if( endDate == null || "".equals( endDate ) )
+        {
+            endDateInDateFormat = getDefaultEndDate();
+        }
+        else
+        {
+            try
+            {
+                endDateInDateFormat = DateUtils.parseDate( endDate, datePatterns );                
+            }
+            catch ( ParseException e )
+            {
+                addFieldError( "endDate", "Invalid date format.");
+                return INPUT;
+            }
+        }
+        
+        try
+        {
+            RepositoryContentStatisticsDAO repoContentStatsDao = dao.getRepositoryContentStatisticsDAO();            
+            if( selectedRepositories.size() > 1 )
+            {
+                limits.setTotalCount( selectedRepositories.size() );            
+                limits.setCurrentPage( 1 );
+                limits.setPerPageCount( 1 );
+                limits.setCountOfPages( 1 );
+                
+                // multiple repos
+                for( String repo : selectedRepositories )
+                {  
+                    try
+                    {
+                        List contentStats = repoContentStatsDao.queryRepositoryContentStatistics( 
+                           new RepositoryContentStatisticsByRepositoryConstraint( repo, startDateInDateFormat, endDateInDateFormat ) );
+                        
+                        if( contentStats == null || contentStats.isEmpty() )
+                        {
+                            log.info( "No statistics available for repository '" + repo + "'." );
+                            // TODO set repo's stats to 0
+                            
+                            continue;
+                        }                        
+                        repositoryStatistics.addAll( generator.generateReport( contentStats, repo, startDateInDateFormat, endDateInDateFormat, limits ) );
+                    }
+                    catch ( ObjectNotFoundException oe )
+                    {
+                        log.error( "No statistics available for repository '" + repo + "'." );
+                        // TODO set repo's stats to 0
+                    }
+                    catch ( ArchivaDatabaseException ae )
+                    {
+                        log.error( "Error encountered while querying statistics of repository '" + repo + "'." );
+                        // TODO set repo's stats to 0
+                    }
+                }
+            }
+            else if ( selectedRepositories.size() == 1 )
+            {   
+                limits.setCurrentPage( getPage() );
+                limits.setPerPageCount( getRowCount() );
+                
+                selectedRepo = selectedRepositories.get( 0 );
+                try
+                {
+                    List<RepositoryContentStatistics> contentStats = repoContentStatsDao.queryRepositoryContentStatistics( 
+                           new RepositoryContentStatisticsByRepositoryConstraint( selectedRepo, startDateInDateFormat, endDateInDateFormat ) );
+                    
+                    if( contentStats == null || contentStats.isEmpty() )
+                    {   
+                        addActionError( "No statistics available for repository. Repository might not have been scanned." );
+                        return ERROR;
+                    }   
+                    
+                    limits.setTotalCount( contentStats.size() );                    
+                    int extraPage = ( limits.getTotalCount() % limits.getPerPageCount() ) != 0 ? 1 : 0;
+                    int totalPages = ( limits.getTotalCount() / limits.getPerPageCount() ) + extraPage;                    
+                    limits.setCountOfPages( totalPages );
+                    
+                    repositoryStatistics = generator.generateReport( contentStats, selectedRepo, startDateInDateFormat, endDateInDateFormat, limits );
+                }
+                catch ( ObjectNotFoundException oe )
+                {
+                    addActionError( oe.getMessage() );
+                    return ERROR;
+                }
+                catch ( ArchivaDatabaseException de )
+                {
+                    addActionError( de.getMessage() );
+                    return ERROR;
+                }
+            }
+            else
+            {
+                addFieldError( "availableRepositories", "Please select a repository (or repositories) from the list." );
+                return INPUT;
+            } 
+            
+            if( repositoryStatistics.isEmpty() )
+            {
+                return BLANK;
+            }
+            
+            if( startDate.equals( getDefaultStartDate() ) )
+            {
+                startDate = null;
+            }
+            else
+            {   
+                startDate = DateFormatUtils.format( startDateInDateFormat, "MM/dd/yyyy" );                
+            }
+            
+            endDate = DateFormatUtils.format( endDateInDateFormat, "MM/dd/yyyy" );
+        }
+        catch ( ArchivaReportException e )
+        {
+            addActionError( "Error encountered while generating report :: " + e.getMessage() );
+            return ERROR;
+        }
+        
+        return SUCCESS;
+    }
+    
+    private Date getDefaultStartDate()
+    {
+        Calendar cal = Calendar.getInstance();
+        cal.clear();
+        cal.set( 1900, 1, 1, 0, 0, 0 );
+        
+        return cal.getTime();
+    }
+    
+    private Date getDefaultEndDate()
+    {
+        return Calendar.getInstance().getTime();
+    }
+    
     public String execute()
         throws Exception
-    {
+    {   
+        if( repositoryId == null )
+        {
+            addFieldError( "repositoryId", "You must provide a repository id.");            
+            return INPUT;
+        }
+        
+        if( rowCount < 10 )
+        {
+            addFieldError( "rowCount", "Row count must be larger than 10." );
+            return INPUT;
+        }
+        
         List<RepositoryProblem> problemArtifacts =
             dao.getRepositoryProblemDAO().queryRepositoryProblems( configureConstraint() );
 
@@ -157,7 +411,7 @@
             return SUCCESS;
         }
     }
-
+    
     private static boolean isJasperPresent()
     {
         if ( jasperPresent == null )
@@ -208,6 +462,34 @@
 
         return constraint;
     }
+    
+    public SecureActionBundle getSecureActionBundle()
+        throws SecureActionException
+    {
+        SecureActionBundle bundle = new SecureActionBundle();
+    
+        bundle.setRequiresAuthentication( true );
+        bundle.addRequiredAuthorization( ArchivaRoleConstants.OPERATION_ACCESS_REPORT, Resource.GLOBAL );
+    
+        return bundle;
+    }
+    
+    private void addToList( RepositoryProblemReport repoProblemReport )
+    {
+        List<RepositoryProblemReport> problemsList = null;
+        
+        if ( repositoriesMap.containsKey( repoProblemReport.getRepositoryId() ) )
+        {
+            problemsList = ( List<RepositoryProblemReport> ) repositoriesMap.get( repoProblemReport.getRepositoryId() );
+        }
+        else
+        {
+            problemsList = new ArrayList<RepositoryProblemReport>();
+            repositoriesMap.put( repoProblemReport.getRepositoryId(), problemsList );
+        }
+        
+        problemsList.add( repoProblemReport );
+    }
 
     public void setServletRequest( HttpServletRequest request )
     {
@@ -284,31 +566,83 @@
     	return repositoriesMap;
     }
     
-    public SecureActionBundle getSecureActionBundle()
-        throws SecureActionException
+    public List<String> getSelectedRepositories()
     {
-        SecureActionBundle bundle = new SecureActionBundle();
+        return selectedRepositories;
+    }
 
-        bundle.setRequiresAuthentication( true );
-        bundle.addRequiredAuthorization( ArchivaRoleConstants.OPERATION_ACCESS_REPORT, Resource.GLOBAL );
+    public void setSelectedRepositories( List<String> selectedRepositories )
+    {
+        this.selectedRepositories = selectedRepositories;
+    }
 
-        return bundle;
+    public List<String> getAvailableRepositories()
+    {
+        return availableRepositories;
+    }
+
+    public void setAvailableRepositories( List<String> availableRepositories )
+    {
+        this.availableRepositories = availableRepositories;
+    }
+
+    public String getStartDate()
+    {
+        return startDate;
+    }
+
+    public void setStartDate( String startDate )
+    {
+        this.startDate = startDate;
+    }
+
+    public String getEndDate()
+    {
+        return endDate;
+    }
+
+    public void setEndDate( String endDate )
+    {
+        this.endDate = endDate;
+    }
+
+    public List<RepositoryStatistics> getRepositoryStatistics()
+    {
+        return repositoryStatistics;
+    }
+
+    public void setRepositoryStatistics( List<RepositoryStatistics> repositoryStatistics )
+    {
+        this.repositoryStatistics = repositoryStatistics;
     }
     
-    private void addToList( RepositoryProblemReport repoProblemReport )
+    public int getReposSize()
+    {
+        return reposSize;
+    }
+
+    public void setReposSize( int reposSize )
+    {
+        this.reposSize = reposSize;
+    }
+
+    public String getSelectedRepo()
+    {
+        return selectedRepo;
+    }
+
+    public void setSelectedRepo( String selectedRepo )
+    {
+        this.selectedRepo = selectedRepo;
+    }
+
+    public DataLimits getLimits()
+    {
+        return limits;
+    }
+
+    public void setLimits( DataLimits limits )
     {
-    	List<RepositoryProblemReport> problemsList = null;
-    	
-    	if ( repositoriesMap.containsKey( repoProblemReport.getRepositoryId() ) )
-    	{
-    		problemsList = ( List<RepositoryProblemReport> ) repositoriesMap.get( repoProblemReport.getRepositoryId() );
-    	}
-    	else
-    	{
-    		problemsList = new ArrayList<RepositoryProblemReport>();
-    		repositoriesMap.put( repoProblemReport.getRepositoryId(), problemsList );
-    	}
-    	
-    	problemsList.add( repoProblemReport );
+        this.limits = limits;
     }
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/admin/repositoryGroups.jsp
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/admin/repositoryGroups.jsp?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/admin/repositoryGroups.jsp (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/admin/repositoryGroups.jsp Fri Oct 17 23:45:02 2008
@@ -152,6 +152,10 @@
 </c:forEach>
 </div> <%-- admin --%>
 
-</div> <%-- content area --%>
 </c:otherwise>
 </c:choose>
+</div> <%-- content area --%>
+
+</body>
+</html>
+

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/decorators/default.jsp
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/decorators/default.jsp?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/decorators/default.jsp (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/decorators/default.jsp Fri Oct 17 23:45:02 2008
@@ -115,6 +115,11 @@
             <my:currentWWUrl action="userlist" namespace="/security">User Management</my:currentWWUrl>
           </li>
         </redback:ifAuthorized>
+        <redback:ifAuthorized permission="archiva-manage-users">
+          <li class="none">
+            <my:currentWWUrl action="roles" namespace="/security">User Roles</my:currentWWUrl>
+          </li>
+        </redback:ifAuthorized>        
         <redback:ifAuthorized permission="archiva-manage-configuration">
           <li class="none">
             <my:currentWWUrl action="configureAppearance" namespace="/admin">Appearance</my:currentWWUrl>

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/reports/pickReport.jsp
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/reports/pickReport.jsp?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/reports/pickReport.jsp (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/WEB-INF/jsp/reports/pickReport.jsp Fri Oct 17 23:45:02 2008
@@ -22,18 +22,34 @@
 <html>
 <head>
   <title>Reports</title>
-  <s:head/>
+  <s:head theme="ajax" />
 </head>
 
 <body>
 <h1>Reports</h1>
-
+  
 <div id="contentArea">
 
-  <s:form action="generateReport" namespace="/report" validate="true">
+  <h2>Repository Statistics</h2>
+  <s:form action="generateStatisticsReport" namespace="/report" validate="true">
+    
+    <s:optiontransferselect label="Repositories To Be Compared" name="availableRepositories"
+		list="availableRepositories" doubleName="selectedRepositories"
+		doubleList="selectedRepositories" size="8" doubleSize="8"/>
+		
+	<s:datetimepicker label="Start Date" name="startDate" id="startDate"/>
+	<s:datetimepicker label="End Date" name="endDate" id="endDate"/>
+	<s:textfield label="Row Count" name="rowCount" />
+		    
+    <s:submit value="View Statistics"/>
+  </s:form>
+    
+  <h2>Repository Health</h2>
+  <s:form namespace="/report" action="generateReport" validate="true">
     <s:textfield label="Row Count" name="rowCount" />
     <s:textfield label="Group ID" name="groupId"/>
     <s:select label="Repository ID" name="repositoryId" list="repositoryIds"/>
+  
     <s:submit value="Show Report"/>
   </s:form>
 

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/css/maven-theme.css
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/css/maven-theme.css?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/css/maven-theme.css (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/css/maven-theme.css Fri Oct 17 23:45:02 2008
@@ -33,7 +33,8 @@
 
 select {
     padding-left: 3px;
-	height: 1.4em;	
+	height: auto;
+	width: auto;	
 }
 
 input {

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/images/archiva-splat-32.gif
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webapp/src/main/webapp/images/archiva-splat-32.gif?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
Binary files - no diff available.

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavResourceFactory.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavResourceFactory.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavResourceFactory.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavResourceFactory.java Fri Oct 17 23:45:02 2008
@@ -186,14 +186,14 @@
     {
         checkLocatorIsInstanceOfRepositoryLocator( locator );
         ArchivaDavResourceLocator archivaLocator = (ArchivaDavResourceLocator) locator;
-
+        
         RepositoryGroupConfiguration repoGroupConfig =
             archivaConfiguration.getConfiguration().getRepositoryGroupsAsMap().get( archivaLocator.getRepositoryId() );
         List<String> repositories = new ArrayList<String>();
 
         boolean isGet = WebdavMethodUtil.isReadMethod( request.getMethod() );
         boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
-
+        
         if ( repoGroupConfig != null )
         {
             if( WebdavMethodUtil.isWriteMethod( request.getMethod() ) )
@@ -230,7 +230,7 @@
 
             try
             {
-                managedRepository = getManagedRepository( repositoryId );
+                managedRepository = getManagedRepository( repositoryId );                
             }
             catch ( DavException de )
             {
@@ -241,13 +241,13 @@
             DavResource resource = null;
             
             if ( !locator.getResourcePath().startsWith( ArchivaDavResource.HIDDEN_PATH_PREFIX ) )
-            {
+            {                
                 if ( managedRepository != null )
                 {
                     try
                     {
                         if( isAuthorized( request, repositoryId ) )
-                        {
+                        {   
                             LogicalResource logicalResource =
                                 new LogicalResource( RepositoryPathUtil.getLogicalResource( locator.getResourcePath() ) );
 
@@ -258,12 +258,12 @@
 
                             if ( isPut )
                             {
-                                resource = doPut( managedRepository, request, archivaLocator, logicalResource );
+                                resource = doPut( managedRepository, request, archivaLocator, logicalResource );                                
                             }
                         }
                     }
                     catch ( DavException de ) 
-                    {
+                    {                        
                         e = de;
                         continue;
                     }
@@ -273,11 +273,11 @@
                         e = new DavException( HttpServletResponse.SC_NOT_FOUND, "Resource does not exist" );
                     }
                     else
-                    {   
+                    {                           
                         availableResources.add( resource );
 
                         String logicalResource = RepositoryPathUtil.getLogicalResource( locator.getResourcePath() );
-                        resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );
+                        resourcesInAbsolutePath.add( managedRepository.getRepoRoot() + logicalResource );                        
                     }
                 }
                 else
@@ -491,15 +491,16 @@
 
         File rootDirectory = new File( managedRepository.getRepoRoot() );
         File destDir = new File( rootDirectory, logicalResource.getPath() ).getParentFile();
+        
         if ( request.getMethod().equals(HTTP_PUT_METHOD) && !destDir.exists() )
         {
             destDir.mkdirs();
             String relPath = PathUtil.getRelative( rootDirectory.getAbsolutePath(), destDir );
             triggerAuditEvent( request.getRemoteAddr(), logicalResource.getPath(), relPath, AuditEvent.CREATE_DIR );
         }
-
-        File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );
-
+        
+        File resourceFile = new File( managedRepository.getRepoRoot(), logicalResource.getPath() );        
+                
         return new ArchivaDavResource( resourceFile.getAbsolutePath(), logicalResource.getPath(),
                                        managedRepository.getRepository(), request.getRemoteAddr(),
                                        request.getDavSession(), locator, this, mimeTypes, auditListeners, consumers, archivaXworkUser );
@@ -721,9 +722,9 @@
 
     protected boolean isAuthorized( DavServletRequest request, String repositoryId )
         throws DavException
-    {
+    {   
         try
-        {
+        {     
             AuthenticationResult result = httpAuth.getAuthenticationResult( request, null );
             SecuritySession securitySession = httpAuth.getSecuritySession();
 
@@ -732,13 +733,15 @@
                                           WebdavMethodUtil.isWriteMethod( request.getMethod() ) );
         }
         catch ( AuthenticationException e )
-        {
+        {            
+            boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
+            
             // safety check for MRM-911            
             String guest = archivaXworkUser.getGuest();
             try
             {
                 if( servletAuth.isAuthorized( guest, 
-                      ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId() ) )
+                      ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId(), isPut ) )
                 {   
                     return true;
                 }
@@ -795,6 +798,8 @@
 
         if( allow )
         {
+            boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
+            
             for( String repository : repositories )
             {
                 // for prompted authentication
@@ -817,7 +822,7 @@
                     // for the current user logged in
                     try
                     {
-                        if( servletAuth.isAuthorized( activePrincipal, repository ) )
+                        if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
                         {
                             getResource( locator, mergedRepositoryContents, logicalResource, repository );
                         }
@@ -909,11 +914,12 @@
         }
         else
         {
+            boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
             for( String repository : repositories )
             {
                 try
-                {
-                    if( servletAuth.isAuthorized( activePrincipal, repository ) )
+                {   
+                    if( servletAuth.isAuthorized( activePrincipal, repository, isPut ) )
                     {
                         allow = true;
                         break;
@@ -974,4 +980,14 @@
            return true;
        }
     }
+    
+    public void setServletAuth( ServletAuthenticator servletAuth )
+    {
+        this.servletAuth = servletAuth;
+    }
+    
+    public void setHttpAuth( HttpAuthenticator httpAuth )
+    {
+        this.httpAuth = httpAuth;
+    }
 }

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProvider.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProvider.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProvider.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/main/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProvider.java Fri Oct 17 23:45:02 2008
@@ -24,6 +24,7 @@
 import org.apache.jackrabbit.webdav.DavException;
 import org.apache.jackrabbit.webdav.DavServletRequest;
 import org.apache.maven.archiva.webdav.util.RepositoryPathUtil;
+import org.apache.maven.archiva.webdav.util.WebdavMethodUtil;
 import org.apache.maven.archiva.security.ArchivaXworkUser;
 import org.apache.maven.archiva.security.ServletAuthenticator;
 import org.codehaus.plexus.redback.authentication.AuthenticationException;
@@ -72,12 +73,14 @@
         }
         catch ( AuthenticationException e )
         {   
+            boolean isPut = WebdavMethodUtil.isWriteMethod( request.getMethod() );
+            
             // safety check for MRM-911            
             String guest = archivaXworkUser.getGuest();
             try
             {
                 if( servletAuth.isAuthorized( guest, 
-                      ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId() ) )
+                      ( ( ArchivaDavResourceLocator ) request.getRequestLocator() ).getRepositoryId(), isPut ) )
                 {
                     request.setDavSession(new ArchivaDavSession());
                     return true;

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProviderTest.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProviderTest.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProviderTest.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/ArchivaDavSessionProviderTest.java Fri Oct 17 23:45:02 2008
@@ -362,7 +362,7 @@
             return true;
         }
 
-        public boolean isAuthorized(String arg0, String arg1)
+        public boolean isAuthorized(String arg0, String arg1, boolean isWriteRequest)
             throws UnauthorizedException
         {
             return true;

Modified: archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/RepositoryServletSecurityTest.java
URL: http://svn.apache.org/viewvc/archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/RepositoryServletSecurityTest.java?rev=705848&r1=705847&r2=705848&view=diff
==============================================================================
--- archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/RepositoryServletSecurityTest.java (original)
+++ archiva/branches/archiva-struts2/archiva-modules/archiva-web/archiva-webdav/src/test/java/org/apache/maven/archiva/webdav/RepositoryServletSecurityTest.java Fri Oct 17 23:45:02 2008
@@ -1,21 +1,550 @@
 package org.apache.maven.archiva.webdav;
 
-/**
- * RepositoryServletSecurityTest 
+/*
+ * 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.
+ */
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.servlet.http.HttpServletResponse;
+
+import net.sf.ehcache.CacheManager;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.jackrabbit.webdav.DavResourceFactory;
+import org.apache.jackrabbit.webdav.DavSessionProvider;
+import org.apache.maven.archiva.configuration.ArchivaConfiguration;
+import org.apache.maven.archiva.configuration.Configuration;
+import org.apache.maven.archiva.configuration.ManagedRepositoryConfiguration;
+import org.apache.maven.archiva.security.ArchivaXworkUser;
+import org.apache.maven.archiva.security.ServletAuthenticator;
+import org.codehaus.plexus.redback.authentication.AuthenticationException;
+import org.codehaus.plexus.redback.authentication.AuthenticationResult;
+import org.codehaus.plexus.redback.authorization.UnauthorizedException;
+import org.codehaus.plexus.redback.system.DefaultSecuritySession;
+import org.codehaus.plexus.redback.system.SecuritySession;
+import org.codehaus.plexus.redback.xwork.filter.authentication.HttpAuthenticator;
+import org.codehaus.plexus.redback.xwork.filter.authentication.basic.HttpBasicAuthentication;
+import org.codehaus.plexus.spring.PlexusInSpringTestCase;
+import org.easymock.MockControl;
+import org.easymock.classextension.MockClassControl;
+import org.easymock.internal.AlwaysMatcher;
+
+import com.meterware.httpunit.GetMethodWebRequest;
+import com.meterware.httpunit.HttpUnitOptions;
+import com.meterware.httpunit.PutMethodWebRequest;
+import com.meterware.httpunit.WebRequest;
+import com.meterware.httpunit.WebResponse;
+import com.meterware.servletunit.InvocationContext;
+import com.meterware.servletunit.ServletRunner;
+import com.meterware.servletunit.ServletUnitClient;
+
+/**
+ * RepositoryServletSecurityTest
+ * 
+ * Test the flow of the authentication and authorization checks. This does not necessarily
+ * perform redback security checking.
+ * 
  * @author <a href="mailto:joakime@apache.org">Joakim Erdfelt</a>
  * @version $Id$
  */
 public class RepositoryServletSecurityTest
-    extends AbstractRepositoryServletTestCase
+    extends PlexusInSpringTestCase
 {
-    public void testSecuredGet()
+    protected static final String REPOID_INTERNAL = "internal";
+
+    protected ServletUnitClient sc;
+
+    protected File repoRootInternal;
+
+    private ServletRunner sr;
+
+    protected ArchivaConfiguration archivaConfiguration;
+
+    private DavSessionProvider davSessionProvider;
+
+    private MockControl servletAuthControl;
+
+    private ServletAuthenticator servletAuth;
+
+    private MockClassControl httpAuthControl;
+
+    private HttpAuthenticator httpAuth;
+
+    private ArchivaXworkUser archivaXworkUser;
+
+    private RepositoryServlet servlet;
+    
+    public void setUp()
+        throws Exception
+    {
+        super.setUp();
+
+        String appserverBase = getTestFile( "target/appserver-base" ).getAbsolutePath();
+        System.setProperty( "appserver.base", appserverBase );
+
+        File testConf = getTestFile( "src/test/resources/repository-archiva.xml" );
+        File testConfDest = new File( appserverBase, "conf/archiva.xml" );
+        FileUtils.copyFile( testConf, testConfDest );
+
+        archivaConfiguration = (ArchivaConfiguration) lookup( ArchivaConfiguration.class );
+        repoRootInternal = new File( appserverBase, "data/repositories/internal" );
+        Configuration config = archivaConfiguration.getConfiguration();
+
+        config.addManagedRepository( createManagedRepository( REPOID_INTERNAL, "Internal Test Repo", repoRootInternal ) );
+        saveConfiguration( archivaConfiguration );
+
+        CacheManager.getInstance().removeCache( "url-failures-cache" );
+
+        HttpUnitOptions.setExceptionsThrownOnErrorStatus( false );
+
+        sr = new ServletRunner( getTestFile( "src/test/resources/WEB-INF/repository-servlet-security-test/web.xml" ) );
+        sr.registerServlet( "/repository/*", RepositoryServlet.class.getName() );
+        sc = sr.newClient();
+
+        servletAuthControl = MockControl.createControl( ServletAuthenticator.class );
+        servletAuthControl.setDefaultMatcher( MockControl.ALWAYS_MATCHER );
+        servletAuth = (ServletAuthenticator) servletAuthControl.getMock();
+
+        httpAuthControl =
+            MockClassControl.createControl( HttpBasicAuthentication.class, HttpBasicAuthentication.class.getMethods() );
+        httpAuthControl.setDefaultMatcher( MockControl.ALWAYS_MATCHER );
+        httpAuth = (HttpAuthenticator) httpAuthControl.getMock();
+
+        archivaXworkUser = new ArchivaXworkUser();
+        archivaXworkUser.setGuest( "guest" );
+
+        davSessionProvider = new ArchivaDavSessionProvider( servletAuth, httpAuth, archivaXworkUser );      
+    }
+
+    protected ManagedRepositoryConfiguration createManagedRepository( String id, String name, File location )
     {
+        ManagedRepositoryConfiguration repo = new ManagedRepositoryConfiguration();
+        repo.setId( id );
+        repo.setName( name );
+        repo.setLocation( location.getAbsolutePath() );
+        return repo;
+    }
+
+    protected void saveConfiguration()
+        throws Exception
+    {
+        saveConfiguration( archivaConfiguration );
+    }
+
+    protected void saveConfiguration( ArchivaConfiguration archivaConfiguration )
+        throws Exception
+    {
+        archivaConfiguration.save( archivaConfiguration.getConfiguration() );
+    }
+
+    protected void setupCleanRepo( File repoRootDir )
+        throws IOException
+    {
+        FileUtils.deleteDirectory( repoRootDir );
+        if ( !repoRootDir.exists() )
+        {
+            repoRootDir.mkdirs();
+        }
+    }
+
+    @Override
+    protected String getPlexusConfigLocation()
+    {
+        return "org/apache/maven/archiva/webdav/RepositoryServletSecurityTest.xml";
+    }
+
+    @Override
+    protected void tearDown()
+        throws Exception
+    {
+        if ( sc != null )
+        {
+            sc.clearContents();
+        }
+
+        if ( sr != null )
+        {
+            sr.shutDown();
+        }
+
+        if ( repoRootInternal.exists() )
+        {
+            FileUtils.deleteDirectory(repoRootInternal);
+        }
+
+        servlet = null;
         
+        super.tearDown();
     }
-    
-    public void testSecuredBrowse()
+
+    // test deploy with invalid user, and guest has no write access to repo
+    // 401 must be returned
+    public void testPutWithInvalidUserAndGuestHasNoWriteAccess()
+        throws Exception
     {
+        setupCleanRepo( repoRootInternal );
+
+        String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
+        InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
+        assertNotNull( "artifact.jar inputstream", is );
+
+        WebRequest request = new PutMethodWebRequest( putUrl, is, "application/octet-stream" );
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthenticated( null, null ),
+                           new AuthenticationException( "Authentication error" ) );
+        
+        servletAuth.isAuthorized( "guest", "internal", true );        
+        servletAuthControl.setMatcher( MockControl.EQUALS_MATCHER );
+        servletAuthControl.setThrowable( new UnauthorizedException( "'guest' has no write access to repository" ) );
+
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+        
+        servlet.service( ic.getRequest(), ic.getResponse() );
+        
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        //assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getResponseCode());
+    }
+
+    // test deploy with invalid user, but guest has write access to repo
+    public void testPutWithInvalidUserAndGuestHasWriteAccess()
+        throws Exception
+    {
+        setupCleanRepo( repoRootInternal );
+
+        String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
+        InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
+        assertNotNull( "artifact.jar inputstream", is );
+
+        WebRequest request = new PutMethodWebRequest( putUrl, is, "application/octet-stream" );
+
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+
+        servlet.setResourceFactory( archivaDavResourceFactory );
+        
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthenticated( null, null ),
+                                           new AuthenticationException( "Authentication error" ) );
+        
+        servletAuth.isAuthorized( "guest", "internal", true );
+        servletAuthControl.setMatcher( MockControl.EQUALS_MATCHER );
+        servletAuthControl.setReturnValue( true );
+                
+     // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthenticated( null, result ),
+                                           new AuthenticationException( "Authentication error" ) );
+        
+        // check if guest has write access
+        servletAuth.isAuthorized( "guest", "internal", true );
+        servletAuthControl.setMatcher( MockControl.EQUALS_MATCHER );
+        servletAuthControl.setReturnValue( true );
+        
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+
+        servlet.service( ic.getRequest(), ic.getResponse() );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        // assertEquals( HttpServletResponse.SC_CREATED, response.getResponseCode() );
+    }
+
+    // test deploy with a valid user with no write access
+    public void testPutWithValidUserWithNoWriteAccess()
+        throws Exception
+    {
+        setupCleanRepo( repoRootInternal );
+
+        String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
+        InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
+        assertNotNull( "artifact.jar inputstream", is );
+        
+        WebRequest request = new PutMethodWebRequest( putUrl, is, "application/octet-stream" );
+        
+        InvocationContext ic = sc.newInvocation( request ); 
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+        
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+        servlet.setResourceFactory( archivaDavResourceFactory );
+
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, null ), true );
+        
+     // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, result ), true );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthorized( null, session, "internal", true ),
+                                           new UnauthorizedException( "User not authorized" ) );
+                
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+        
+        servlet.service( ic.getRequest(), ic.getResponse() );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+        
+        // assertEquals(HttpServletResponse.SC_UNAUTHORIZED, response.getResponseCode());
+    }
+
+    // test deploy with a valid user with write access
+    public void testPutWithValidUserWithWriteAccess()
+        throws Exception
+    {
+        setupCleanRepo( repoRootInternal );
+        assertTrue( repoRootInternal.exists() );
+
+        String putUrl = "http://machine.com/repository/internal/path/to/artifact.jar";
+        InputStream is = getClass().getResourceAsStream( "/artifact.jar" );
+        assertNotNull( "artifact.jar inputstream", is );
+
+        WebRequest request = new PutMethodWebRequest( putUrl, is, "application/octet-stream" );
+
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+
+        servlet.setResourceFactory( archivaDavResourceFactory );
+
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, null ), true );
+
+        // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, result ), true );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthorized( null, session, "internal", true ), true );
+
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+
+        servlet.service( ic.getRequest(), ic.getResponse() );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        // assertEquals(HttpServletResponse.SC_CREATED, response.getResponseCode());
+    }
+
+    // test get with invalid user, and guest has read access to repo
+    public void testGetWithInvalidUserAndGuestHasReadAccess()
+        throws Exception
+    {
+        String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
+        String expectedArtifactContents = "dummy-commons-lang-artifact";
+
+        File artifactFile = new File( repoRootInternal, commonsLangJar );
+        artifactFile.getParentFile().mkdirs();
+
+        FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, null );
+
+        WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangJar );
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+        
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+
+        servlet.setResourceFactory( archivaDavResourceFactory );
+
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthenticated( null, null ),
+                                           new AuthenticationException( "Authentication error" ) );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthorized( "guest", "internal", false ), true );
+        
+     // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, result ), true );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthorized( null, session, "internal", true ), true );
+
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+
+        WebResponse response = sc.getResponse( request );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        assertEquals( HttpServletResponse.SC_OK, response.getResponseCode() );
+        assertEquals( "Expected file contents", expectedArtifactContents, response.getText() );
+    }
+
+    // test get with invalid user, and guest has no read access to repo
+    public void testGetWithInvalidUserAndGuestHasNoReadAccess()
+        throws Exception
+    {
+        String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
+        String expectedArtifactContents = "dummy-commons-lang-artifact";
+
+        File artifactFile = new File( repoRootInternal, commonsLangJar );
+        artifactFile.getParentFile().mkdirs();
+
+        FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, null );
+
+        WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangJar );
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthenticated( null, null ),
+                                           new AuthenticationException( "Authentication error" ) );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthorized( "guest", "internal", false ), false );
+
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+
+        WebResponse response = sc.getResponse( request );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        assertEquals( HttpServletResponse.SC_UNAUTHORIZED, response.getResponseCode() );
+    }
+
+    // test get with valid user with read access to repo
+    public void testGetWithAValidUserWithReadAccess()
+        throws Exception
+    {
+        String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
+        String expectedArtifactContents = "dummy-commons-lang-artifact";
+
+        File artifactFile = new File( repoRootInternal, commonsLangJar );
+        artifactFile.getParentFile().mkdirs();
+
+        FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, null );
+
+        WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangJar );
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+
+        servlet.setResourceFactory( archivaDavResourceFactory );
+        
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, null ), true );
+        
+     // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, result ), true );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthorized( null, session, "internal", true ), true );
+        
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+
+        WebResponse response = sc.getResponse( request );
+        
+        httpAuthControl.verify();
+        servletAuthControl.verify();
+
+        assertEquals( HttpServletResponse.SC_OK, response.getResponseCode() );
+        assertEquals( "Expected file contents", expectedArtifactContents, response.getText() );
+    }
+
+    // test get with valid user with no read access to repo
+    public void testGetWithAValidUserWithNoReadAccess()
+        throws Exception
+    {
+        String commonsLangJar = "commons-lang/commons-lang/2.1/commons-lang-2.1.jar";
+        String expectedArtifactContents = "dummy-commons-lang-artifact";
+
+        File artifactFile = new File( repoRootInternal, commonsLangJar );
+        artifactFile.getParentFile().mkdirs();
+
+        FileUtils.writeStringToFile( artifactFile, expectedArtifactContents, null );
+
+        WebRequest request = new GetMethodWebRequest( "http://machine.com/repository/internal/" + commonsLangJar );
+        InvocationContext ic = sc.newInvocation( request );
+        servlet = (RepositoryServlet) ic.getServlet();
+        servlet.setDavSessionProvider( davSessionProvider );
+
+        ArchivaDavResourceFactory archivaDavResourceFactory = (ArchivaDavResourceFactory) servlet.getResourceFactory();
+        archivaDavResourceFactory.setHttpAuth( httpAuth );
+        archivaDavResourceFactory.setServletAuth( servletAuth );
+
+        servlet.setResourceFactory( archivaDavResourceFactory );
+        
+        AuthenticationResult result = new AuthenticationResult();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, null ), true );
+
+     // ArchivaDavResourceFactory#isAuthorized()
+        SecuritySession session = new DefaultSecuritySession();
+        httpAuthControl.expectAndReturn( httpAuth.getAuthenticationResult( null, null ), result );
+        httpAuthControl.expectAndReturn( httpAuth.getSecuritySession(), session );
+        servletAuthControl.expectAndReturn( servletAuth.isAuthenticated( null, result ), true );
+        servletAuthControl.expectAndThrow( servletAuth.isAuthorized( null, session, "internal", true ),
+                                           new UnauthorizedException( "User not authorized to read repository." ) );
+        
+        httpAuthControl.replay();
+        servletAuthControl.replay();
+        
+        WebResponse response = sc.getResponse( request );
+
+        httpAuthControl.verify();
+        servletAuthControl.verify();
         
+        assertEquals( HttpServletResponse.SC_UNAUTHORIZED, response.getResponseCode() );
     }
 }



Mime
View raw message