Author: ivol37 at gmail.com
Date: Fri Dec 24 12:22:39 2010
New Revision: 546

Log:
[AMDATU-222] Fixed broken integration tests after adding authorization to 
UserAdmin REST API

Added:
   trunk/integration-tests/src/test/java/org/amdatu/test/integration/util/
   
trunk/integration-tests/src/test/java/org/amdatu/test/integration/util/Login.java
Modified:
   
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/bean/RoleBean.java
   
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/GroupsResource.java
   
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/RolesResource.java
   
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/UsersResource.java
   
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
   
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
   
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/RESTTestBase.java
   
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/UserAdminRESTTest.java

Modified: 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/bean/RoleBean.java
==============================================================================
--- 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/bean/RoleBean.java
  (original)
+++ 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/bean/RoleBean.java
  Fri Dec 24 12:22:39 2010
@@ -42,7 +42,7 @@
 
     @XmlAttribute(name = "type")
     private int m_type;
-    
+
     @XmlElement(name = "link")
     private AtomSyndicationLink m_link;
 
@@ -92,8 +92,10 @@
 
     public void setImpliedRoles(String[] impliedRoles) {
         m_impliedRoles = new ArrayList<String>();
-        for (String impliedRole : impliedRoles) {
-            m_impliedRoles.add(impliedRole);
+        if (impliedRoles != null) {
+            for (String impliedRole : impliedRoles) {
+                m_impliedRoles.add(impliedRole);
+            }
         }
     }
 

Modified: 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/GroupsResource.java
==============================================================================
--- 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/GroupsResource.java
 (original)
+++ 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/GroupsResource.java
 Fri Dec 24 12:22:39 2010
@@ -39,7 +39,7 @@
  * GET /rest/services/groups/groups/{name} -> Returns the group with the 
specified name
  * PUT /rest/services/groups/groups/{name} -> Creates a group with the 
specified name
  * PUT /rest/services/groups/groups/{name}/basicmembers/{memberName} -> Adds a 
member to the group
- * PUT /rest/services/groups/groups/{name}/requiredmembers/{memberName} -> 
Adds a required member to the group 
+ * PUT /rest/services/groups/groups/{name}/requiredmembers/{memberName} -> 
Adds a required member to the group
  * DELETE /rest/services/groups/groups/{name} -> Deletes the group with the 
specified name
  * DELETE /rest/services/groups/groups/{name}/members/{memberName} -> Deletes 
a member from group
  * </pre></code>
@@ -53,9 +53,10 @@
      */
     @GET
     @Produces({MediaType.TEXT_PLAIN})
+    @Path("status")
     public String status() {
         return "UserAdmin Groups management service online";
-    } 
+    }
 
     /**
      * Returns all groups that match the specified filter options. This method 
can be invoked by making the following
@@ -92,7 +93,7 @@
     public Response getGroups(@QueryParam("filter") final String filter,
         @QueryParam("sortOrder") final String sortOrder,
         @DefaultValue("1") @QueryParam("startIndex") final int startIndex,
-        @DefaultValue("50") @QueryParam("maxResults") final int maxResults, 
+        @DefaultValue("50") @QueryParam("maxResults") final int maxResults,
         @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();
@@ -166,7 +167,7 @@
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }
         return setCredential(name, key, value, Role.GROUP);
-    }  
+    }
 
     /**
      * Sets a property for the group with the specified name. This method can 
be invoked by making the following REST
@@ -188,7 +189,7 @@
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }
         return setProperty(name, key, value, Role.USER);
-    }    
+    }
 
     /**
      * Adds a basic member to the group with the specified name. This method 
can be invoked by making the following REST
@@ -266,7 +267,7 @@
     @DELETE
     @Path("{name}/members/{memberName}")
     @Produces({MediaType.APPLICATION_JSON})
-    public Response removeMember(@PathParam("name") final String name, 
@PathParam("memberName") final String memberName, 
+    public Response removeMember(@PathParam("name") final String name, 
@PathParam("memberName") final String memberName,
         @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();

Modified: 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/RolesResource.java
==============================================================================
--- 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/RolesResource.java
  (original)
+++ 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/RolesResource.java
  Fri Dec 24 12:22:39 2010
@@ -31,6 +31,17 @@
 @Path("roles")
 public class RolesResource extends ResourceBase{
     /**
+     * This method can be used to check the availability of the Roles 
management service.
+     * @return The text "UserAdmin Roles management service online"
+     */
+    @GET
+    @Produces({MediaType.TEXT_PLAIN})
+    @Path("status")
+    public String status() {
+        return "UserAdmin Roles management service online";
+    }
+
+    /**
      * Returns all users that match the specified filter options. This method 
can be invoked by making the following
      * REST call:<code><pre>
      * GET 
/rest/services/users/users?filter={filter}&sortOrder={sortOrder}&startIndex={startIndex}&maxResults={maxResults}
@@ -57,15 +68,15 @@
      *    }]
      * }
      * </pre></code> a 500 response in case any exception occurred.
-     */    
+     */
     @GET
     @Produces({MediaType.APPLICATION_JSON})
     public Response getUsers(
-            @QueryParam("filter") final String filter,
-            @QueryParam("sortOrder") final String sortOrder,
-            @DefaultValue("1") @QueryParam("startIndex") final int startIndex,
-            @DefaultValue("50") @QueryParam("maxResults") final int maxResults,
-            @Context final HttpServletRequest request) {
+        @QueryParam("filter") final String filter,
+        @QueryParam("sortOrder") final String sortOrder,
+        @DefaultValue("1") @QueryParam("startIndex") final int startIndex,
+        @DefaultValue("50") @QueryParam("maxResults") final int maxResults,
+        @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }

Modified: 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/UsersResource.java
==============================================================================
--- 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/UsersResource.java
  (original)
+++ 
trunk/amdatu-authorization/useradmin-rest/src/main/java/org/amdatu/authorization/useradmin/rest/service/UsersResource.java
  Fri Dec 24 12:22:39 2010
@@ -44,7 +44,18 @@
  * @author ivol
  */
 @Path("users")
-public class UsersResource extends ResourceBase {    
+public class UsersResource extends ResourceBase {
+    /**
+     * This method can be used to check the availability of the Users 
management service.
+     * @return The text "UserAdmin Users management service online"
+     */
+    @GET
+    @Produces({MediaType.TEXT_PLAIN})
+    @Path("status")
+    public String status() {
+        return "UserAdmin Users management service online";
+    }
+
     /**
      * Returns all users that match the specified filter options. This method 
can be invoked by making the following
      * REST call:<code><pre>
@@ -72,21 +83,21 @@
      *    }]
      * }
      * </pre></code> a 500 response in case any exception occurred.
-     */    
+     */
     @GET
     @Produces({MediaType.APPLICATION_JSON})
     public Response getUsers(
-            @QueryParam("filter") final String filter,
-            @QueryParam("sortOrder") final String sortOrder,
-            @DefaultValue("1") @QueryParam("startIndex") final int startIndex,
-            @DefaultValue("50") @QueryParam("maxResults") final int 
maxResults, 
-            @Context final HttpServletRequest request) {
+        @QueryParam("filter") final String filter,
+        @QueryParam("sortOrder") final String sortOrder,
+        @DefaultValue("1") @QueryParam("startIndex") final int startIndex,
+        @DefaultValue("50") @QueryParam("maxResults") final int maxResults,
+        @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }
         return super.getRoles(filter, sortOrder, startIndex, maxResults, 
Role.USER);
     }
-    
+
     /**
      * Returns the user with the specified name. This method can be invoked by 
making the following REST call:
      * <code><pre>
@@ -110,7 +121,7 @@
         }
         return super.getRole(name, Role.USER);
     }
-    
+
     /**
      * Creates the user with the specified name. This method can be invoked by 
making the following REST call:
      * <code><pre>
@@ -130,7 +141,7 @@
         }
         return super.createRole(name, Role.USER);
     }
-    
+
     /**
      * Sets a credential for the user with the specified name. This method can 
be invoked by making the following REST
      * call: <code><pre>
@@ -146,13 +157,13 @@
     @Path("{name}/credentials/{key}")
     @Produces({MediaType.APPLICATION_JSON})
     public Response setCredential(@PathParam("name") final String name,
-            @PathParam("key") final String key, @FormParam("value") final 
String value, @Context final HttpServletRequest request) {
+        @PathParam("key") final String key, @FormParam("value") final String 
value, @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }
         return setCredential(name, key, value, Role.USER);
-    }  
-    
+    }
+
     /**
      * Sets a property for the user with the specified name. This method can 
be invoked by making the following REST
      * call: <code><pre>
@@ -168,13 +179,13 @@
     @Path("{name}/properties/{key}")
     @Produces({MediaType.APPLICATION_JSON})
     public Response setProperty(@PathParam("name") final String name,
-            @PathParam("key") final String key, @FormParam("value") final 
String value, @Context final HttpServletRequest request) {
+        @PathParam("key") final String key, @FormParam("value") final String 
value, @Context final HttpServletRequest request) {
         if (!isAuthorized(request)) {
             return Response.status(Response.Status.UNAUTHORIZED).build();
         }
         return setProperty(name, key, value, Role.USER);
-    }    
-        
+    }
+
     /**
      * Removes the user with the specified name. This method can be invoked by 
making the following REST call:
      * <code><pre>
@@ -193,7 +204,7 @@
         }
         return super.removeRole(name, Role.USER);
     }
-    
+
     protected String getBaseUrl() {
         return "/rest/services/users/users";
     }

Modified: 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
==============================================================================
--- 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
  (original)
+++ 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/ConfigProvider.java
  Fri Dec 24 12:22:39 2010
@@ -43,21 +43,24 @@
 public class ConfigProvider {
     public final static String HOSTNAME = "localhost";
     public final static String DEFAULT_PORTNR = "8080";
-    
+
     // NB: Due to issue https://issues.apache.org/jira/browse/FELIX-2714 we 
must use the default port for testing
     public final static String PORTNR = "8080";
     public final static String SECURE_PORTNR = "8081";
-    
+
     public final static String TEST_USERNAME = "georged";
     public final static String TEST_PASSWORD = "georged";
 
+    public final static String ADMIN_USERNAME = "Administrator";
+    public final static String ADMIN_PASSWORD = "Administrator";
+
     public void addLogConfig(ConfigurationAdmin configAdmin) throws 
IOException {
         Configuration config = 
configAdmin.getConfiguration("org.amdatu.core.loghandler", null);
         Properties properties = new Properties();
         properties.put("console.mininum.loglevel", "DEBUG");
         config.update(properties);
     }
-    
+
     public void addCassandraConfig(ConfigurationAdmin configAdmin) throws 
IOException {
         Configuration config = 
configAdmin.getConfiguration(CassandraConfigurationService.PID, null);
         Properties properties = new Properties();
@@ -90,7 +93,14 @@
         properties.put("datadir", "work/consumerregistrystore");
         config.update(properties);
     }
-    
+
+    public void addSesameConfig(ConfigurationAdmin configAdmin) throws 
IOException {
+        Configuration config = 
configAdmin.getConfiguration("org.amdatu.semanticweb.sesame", null);
+        Properties properties = new Properties();
+        properties.put("datadir", "work/sesame");
+        config.update(properties);
+    }
+
     public void addShindigConfig(ConfigurationAdmin configAdmin) throws 
IOException {
         Configuration config = 
configAdmin.getConfiguration(ShindigService.SHINDIG_CONFIG_PID, null);
         Properties properties = new Properties();
@@ -132,7 +142,7 @@
         properties.put("shindig.cache.lru.messageBundles.capacity", "1000");
         properties.put("shindig.cache.lru.httpResponses.capacity", "10000");
         properties.put("shindig.cache.ehcache.config",
-            "res://org/apache/shindig/common/cache/ehcache/ehcacheConfig.xml");
+        "res://org/apache/shindig/common/cache/ehcache/ehcacheConfig.xml");
         properties.put("shindig.cache.ehcache.jmx.enabled", "true");
         properties.put("shindig.cache.ehcache.jmx.stats", "true");
         properties.put("shindig.http.fast-encoding-detection", "true");
@@ -152,8 +162,8 @@
 
     public void addFelixHttpServiceConfig(ConfigurationAdmin configAdmin) 
throws IOException {
         // NB: Due to issue https://issues.apache.org/jira/browse/FELIX-2714 
updating the felix http service
-        // configuration may cause throwing a connection refused, a service 
that still listens to the default 
-        // port 8080 or returning a 404. Therefore, until this issue has been 
fixed, we will not try to change 
+        // configuration may cause throwing a connection refused, a service 
that still listens to the default
+        // port 8080 or returning a 404. Therefore, until this issue has been 
fixed, we will not try to change
         // any configuration of the felix http service and just use the 
defaults.
         /*
         Configuration config = 
configAdmin.getConfiguration("org.apache.felix.http", null);
@@ -164,7 +174,7 @@
         properties.put("org.apache.felix.http.debug", "true");
         properties.put("org.apache.felix.log.storeDebug", "true");
         config.update(properties);
-        */
+         */
     }
 
     public void addFSUserAdminConfig(ConfigurationAdmin configAdmin) throws 
IOException {
@@ -173,7 +183,7 @@
         properties.put(TenantStorageProvider.DATA_DIRECTORY, 
"work/useradminstore");
         config.update(properties);
     }
-    
+
     public void addOAuthConfig(ConfigurationAdmin configAdmin) throws 
IOException {
         Configuration config = 
configAdmin.getConfiguration(OAuthServerConfig.PID, null);
         Properties properties = new Properties();
@@ -182,7 +192,7 @@
         properties.put(OAuthServerConfig.AUTHORIZE_URL, 
"/oauth-server/jsp/authorize.jsp");
         config.update(properties);
     }
-    
+
     @SuppressWarnings("unchecked")
     public void addTestUser(UserAdmin userAdmin) {
         User user = (User) userAdmin.createRole(TEST_USERNAME, Role.USER);
@@ -194,7 +204,7 @@
         userAdmin.removeRole(TEST_USERNAME);
         Assert.assertFalse("Test user '" + TEST_USERNAME + "' could not be 
removed", userAdmin.getRole(TEST_USERNAME) != null);
     }
-    
+
     /**
      * Wait until the service at the specified URL returns the specified 
response code with a timeout as specified.
      * 

Modified: 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
==============================================================================
--- 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
   (original)
+++ 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/OAuthTestBase.java
   Fri Dec 24 12:22:39 2010
@@ -16,8 +16,6 @@
  */
 package org.amdatu.test.integration.base;
 
-import static org.amdatu.test.integration.base.ConfigProvider.HOSTNAME;
-import static org.amdatu.test.integration.base.ConfigProvider.PORTNR;
 import static org.amdatu.test.integration.base.ConfigProvider.TEST_PASSWORD;
 import static org.amdatu.test.integration.base.ConfigProvider.TEST_USERNAME;
 import static org.ops4j.pax.exam.CoreOptions.provision;
@@ -35,18 +33,14 @@
 import org.amdatu.authentication.oauth.api.OAuthServiceProvider;
 import org.amdatu.authentication.oauth.server.OAuthRequestTokenServlet;
 import org.amdatu.authentication.oauth.server.OAuthTokenProvider;
-import org.amdatu.authentication.tokenprovider.TokenProvider;
 import org.amdatu.authorization.login.service.LoginService;
 import org.amdatu.test.integration.mock.OAuthProtectedTestServlet;
-import org.apache.commons.httpclient.Header;
+import org.amdatu.test.integration.util.Login;
 import org.apache.commons.httpclient.HeaderElement;
-import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpException;
-import org.apache.commons.httpclient.methods.PostMethod;
 import org.apache.felix.dm.Component;
 import org.apache.felix.dm.DependencyManager;
 import org.apache.http.HttpStatus;
-import org.junit.Assert;
 import org.ops4j.pax.exam.Option;
 import org.ops4j.pax.exam.junit.Configuration;
 import org.ops4j.pax.useradmin.service.spi.StorageProvider;
@@ -63,7 +57,7 @@
     protected volatile OAuthTokenProvider m_tokenProvider;
     protected volatile OAuthServiceConsumerRegistry m_consumerRegistry;
     protected volatile UserAdmin m_userAdmin;
-    
+
     private HeaderElement m_cookieHeaderElement;
 
     @Configuration
@@ -90,24 +84,24 @@
         servletProperties.put("alias", 
OAuthProtectedTestServlet.SERVLET_ALIAS);
         servletProperties.put("contextId", 
OAuthProtectedTestServlet.SERVLET_ALIAS);
         Component servletComponent = manager.createComponent()
-            .setImplementation(m_testServlet)
-            .setInterface(new String[] { Servlet.class.getName() }, 
servletProperties)
-            
.add(manager.createServiceDependency().setService(LogService.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true));
+        .setImplementation(m_testServlet)
+        .setInterface(new String[] { Servlet.class.getName() }, 
servletProperties)
+        
.add(manager.createServiceDependency().setService(LogService.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true));
 
         Component testComponent = manager.createComponent()
-            .setImplementation(this)
-            
.add(manager.createServiceDependency().setService(OAuthRequestTokenServlet.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(OAuthServiceProvider.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(HttpService.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(UserAdmin.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(LoginService.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(StorageProvider.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(LogService.class).setRequired(true));
+        .setImplementation(this)
+        
.add(manager.createServiceDependency().setService(OAuthRequestTokenServlet.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(OAuthTokenProvider.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(OAuthServiceProvider.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(OAuthServiceConsumerRegistry.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(HttpService.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(UserAdmin.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(LoginService.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(StorageProvider.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(LogService.class).setRequired(true));
 
         return new Component[] { servletComponent, testComponent };
     }
@@ -154,32 +148,9 @@
     }
 
     protected void login() throws HttpException, IOException {
-        String loginUrl = "http://"; + HOSTNAME + ":" + PORTNR + 
"/rest/services/authorization/authorization/login";
-        HttpClient httpClient = new HttpClient();
-        PostMethod postMethod = null;
-        try {
-            postMethod = new PostMethod(loginUrl);
-            postMethod.addParameter("username", TEST_USERNAME);
-            postMethod.addParameter("password", TEST_PASSWORD);
-            postMethod.addRequestHeader("Content-Type", 
"application/x-www-form-urlencoded;charset=UTF-8");
-            int status = httpClient.executeMethod(postMethod);
-            Header cookieHeader = postMethod.getResponseHeader("Set-Cookie");
-            HeaderElement[] headerElements = cookieHeader.getElements();
-            for (HeaderElement headerElement : headerElements) {
-                if 
(TokenProvider.TOKEN_COOKIE_NAME.equalsIgnoreCase(headerElement.getName())) {
-                    m_logService.log(LogService.LOG_DEBUG, "Login service set 
cookie header " + headerElement.getName()
-                        + "=" + headerElement.getValue());
-                    m_cookieHeaderElement = headerElement;
-                }
-            }
-            Assert.assertTrue("Login failed using Amdatu account '" + 
TEST_USERNAME + "', response code=" + status,
-                status == HttpStatus.SC_OK);
-        }
-        finally {
-            postMethod.releaseConnection();
-        }
+        m_cookieHeaderElement = Login.login(TEST_USERNAME, TEST_PASSWORD);
     }
-    
+
     protected Map<String, String> getCookieHeader() {
         Map<String, String> requestHeaders = new HashMap<String, String>();
         String header = m_cookieHeaderElement.getName() + "=" + 
m_cookieHeaderElement.getValue();

Modified: 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/RESTTestBase.java
==============================================================================
--- 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/RESTTestBase.java
    (original)
+++ 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/base/RESTTestBase.java
    Fri Dec 24 12:22:39 2010
@@ -21,8 +21,11 @@
 
 import java.io.IOException;
 
+import org.amdatu.test.integration.util.Login;
 import org.amdatu.web.httpcontext.HttpContextServiceFactory;
+import org.apache.commons.httpclient.HeaderElement;
 import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.methods.DeleteMethod;
 import org.apache.commons.httpclient.methods.GetMethod;
@@ -44,7 +47,7 @@
  * @author ivol
  */
 public abstract class RESTTestBase extends IntegrationTestBase {
-
+    private HeaderElement m_cookieHeaderElement;
     private String m_baseUrl = null;
 
     @Inject
@@ -55,7 +58,7 @@
     public Option[] configure() {
         return super.configure();
     }
-    
+
     @Override
     protected Option[] getProvisionedBundles() {
         return new Option[]{
@@ -68,19 +71,24 @@
                 slingMime(),
                 commonsHttpClient(),
                 commonsLogging(),
-                commonsCodec()
-               )
+                commonsCodec(),
+                amdatuLogin(),
+                paxUserAdmin(),
+                amdatuUserAdminFSStore(),
+                amdatuTokenProvider(),
+                amdatuMemTokenStore()
+            )
             , provisionBundles()};
     }
 
     public Component getTestComponent(DependencyManager manager) {
         return manager.createComponent().setImplementation(this)
-            
.add(manager.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(HttpService.class).setRequired(true))
-            
.add(manager.createServiceDependency().setService(HttpContextServiceFactory.class).setRequired(true));
+        
.add(manager.createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(HttpService.class).setRequired(true))
+        
.add(manager.createServiceDependency().setService(HttpContextServiceFactory.class).setRequired(true));
     }
-   
-    @Before 
+
+    @Before
     public void initConfig() throws IOException, BundleException {
         m_configAdmin = getService(ConfigurationAdmin.class);
         m_logService = getService(LogService.class);
@@ -93,18 +101,18 @@
     }
 
     protected abstract void addConfig(ConfigProvider configProvider, 
ConfigurationAdmin configAdmin) throws IOException;
-    
+
     protected String getBaseUrl() throws Exception {
         if (m_baseUrl == null) {
             m_baseUrl = "http://"; + ConfigProvider.HOSTNAME + ":" + 
ConfigProvider.PORTNR + "/rest/services";
-        } 
+        }
         return m_baseUrl;
     }
-    
+
     protected String invokeRestApi(String urlPostfix, String httpMethod, int 
expectedStatus) throws Exception {
         String url = getBaseUrl() + urlPostfix;
         HttpClient httpClient = new HttpClient();
-        m_logService.log(LogService.LOG_DEBUG, "Invoking REST API '" + url + 
"'");
+        m_logService.log(LogService.LOG_DEBUG, "Invoking REST API " + 
httpMethod + " '" + url + "'");
         HttpMethod method = null;
         if (httpMethod.equals(javax.ws.rs.HttpMethod.GET)) {
             method = new GetMethod(url);
@@ -115,6 +123,7 @@
         } else if (httpMethod.equals(javax.ws.rs.HttpMethod.POST)) {
             method = new PostMethod(url);
         }
+        addCookieHeader(method);
         try {
             // Execute the method, this should return a 200
             int statusCode = httpClient.executeMethod(method);
@@ -127,6 +136,16 @@
             // Release the connection.
             method.releaseConnection();
         }
-        
+    }
+
+    protected void loginAsAdministrator() throws HttpException, IOException {
+        m_cookieHeaderElement = Login.login(ConfigProvider.ADMIN_USERNAME, 
ConfigProvider.ADMIN_PASSWORD);
+    }
+
+    protected void addCookieHeader(HttpMethod method) {
+        if (m_cookieHeaderElement != null) {
+            String header = m_cookieHeaderElement.getName() + "=" + 
m_cookieHeaderElement.getValue();
+            method.addRequestHeader("Cookie", header);
+        }
     }
 }

Modified: 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/UserAdminRESTTest.java
==============================================================================
--- 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/UserAdminRESTTest.java
      (original)
+++ 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/tests/UserAdminRESTTest.java
      Fri Dec 24 12:22:39 2010
@@ -34,22 +34,22 @@
 
 @RunWith(JUnit4TestRunner.class)
 public class UserAdminRESTTest extends RESTTestBase {
-    
+
     protected Option provisionBundles() {
         return provision(
-            paxUserAdmin(),
-            amdatuUserAdminFSStore(),
-            amdatuUserAdminREST());
+            amdatuUserAdminREST(),
+            amdatuTokenProvider(),
+            amdatuMemTokenStore());
     }
-    
+
     public Component[] getDependencies(DependencyManager manager) {
         Component testComponent = getTestComponent(manager);
         
testComponent.add(manager.createServiceDependency().setService(UserAdmin.class).setRequired(true))
 ;
         return new Component[] {
-            testComponent            
+            testComponent
         };
     }
-    
+
     @Override
     protected void addConfig(ConfigProvider configProvider, ConfigurationAdmin 
configAdmin) throws IOException {
         configProvider.addFSUserAdminConfig(configAdmin);
@@ -58,16 +58,22 @@
     @Test
     public void testTheRest() throws Exception {
         // Test the REST interface of the useradmin bundle. First wait before 
it comes up
-        waitForURL(getBaseUrl() + "/users/users", HttpStatus.SC_OK);
-        
-        // -1- Test create user
+        waitForURL(getBaseUrl() + "/users/users/status", HttpStatus.SC_OK);
+
+        // -1- First try to create a user and verify that a 401 error 
(Unauthorized) is returned
         String url = "/users/users/" + ConfigProvider.TEST_USERNAME;
+        invokeRestApi(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_UNAUTHORIZED);
+
+        // -2- Now login as Administrator
+        loginAsAdministrator();
+
+        // -3- And try creating the user again
         invokeRestApi(url,  javax.ws.rs.HttpMethod.PUT, HttpStatus.SC_OK);
-        
-        // -2- Retrieve the user
+
+        // -4- Retrieve the user
         invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, HttpStatus.SC_OK);
 
-        // -3- Delete the user
+        // -5- Delete the user
         invokeRestApi(url,  javax.ws.rs.HttpMethod.DELETE, HttpStatus.SC_OK);
     }
 }

Added: 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/util/Login.java
==============================================================================
--- (empty file)
+++ 
trunk/integration-tests/src/test/java/org/amdatu/test/integration/util/Login.java
   Fri Dec 24 12:22:39 2010
@@ -0,0 +1,43 @@
+package org.amdatu.test.integration.util;
+
+import static org.amdatu.test.integration.base.ConfigProvider.HOSTNAME;
+import static org.amdatu.test.integration.base.ConfigProvider.PORTNR;
+
+import java.io.IOException;
+
+import org.amdatu.authentication.tokenprovider.TokenProvider;
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HeaderElement;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpException;
+import org.apache.commons.httpclient.methods.PostMethod;
+import org.apache.http.HttpStatus;
+import org.junit.Assert;
+
+public class Login {
+    public static HeaderElement login(String username, String password) throws 
HttpException, IOException {
+        String loginUrl = "http://"; + HOSTNAME + ":" + PORTNR + 
"/rest/services/authorization/authorization/login";
+        HttpClient httpClient = new HttpClient();
+        PostMethod postMethod = null;
+        try {
+            postMethod = new PostMethod(loginUrl);
+            postMethod.addParameter("username", username);
+            postMethod.addParameter("password", password);
+            postMethod.addRequestHeader("Content-Type", 
"application/x-www-form-urlencoded;charset=UTF-8");
+            int status = httpClient.executeMethod(postMethod);
+            Assert.assertTrue("Login failed using Amdatu account '" + username 
+ "', response code=" + status,
+                status == HttpStatus.SC_OK);
+            Header cookieHeader = postMethod.getResponseHeader("Set-Cookie");
+            HeaderElement[] headerElements = cookieHeader.getElements();
+            for (HeaderElement headerElement : headerElements) {
+                if 
(TokenProvider.TOKEN_COOKIE_NAME.equalsIgnoreCase(headerElement.getName())) {
+                    return headerElement;
+                }
+            }
+        }
+        finally {
+            postMethod.releaseConnection();
+        }
+        return null;
+    }
+}

Reply via email to