Author: [email protected]
Date: Tue Apr 10 11:52:09 2012
New Revision: 2206

Log:
[AMDATUAUTH-140] Added JSON and enhanced http and assert tools

Added:
   
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/JSONTools.java
Modified:
   
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/AuthTestBase.java
   
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/UserAdminRESTTest.java
   
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/launcher/AuthTest.java
   trunk/amdatu-auth/tools/itest/pom.xml
   
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/AssertTools.java
   
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/HttpTools.java

Modified: 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/AuthTestBase.java
==============================================================================
--- 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/AuthTestBase.java
     (original)
+++ 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/AuthTestBase.java
     Tue Apr 10 11:52:09 2012
@@ -21,6 +21,11 @@
 import org.amdatu.auth.tools.itest.IntegrationTestBase;
 import org.amdatu.core.tenant.TenantManagementService;
 
+/**
+ * The base class of all Auth integration tests.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
 @SuppressWarnings("deprecation")
 public abstract class AuthTestBase extends IntegrationTestBase {
     protected volatile OAuthServiceProvider m_oAuthServiceProvider;

Modified: 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/UserAdminRESTTest.java
==============================================================================
--- 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/UserAdminRESTTest.java
        (original)
+++ 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/UserAdminRESTTest.java
        Tue Apr 10 11:52:09 2012
@@ -35,20 +35,20 @@
 
         // -1- First try to create a user and verify that a 401 error 
(Unauthorized) is returned
         String url = "/users/" + TEST_USERNAME;
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_UNAUTHORIZED);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_UNAUTHORIZED);
 
         // -2- Now login as Administrator
         m_httpUtil.loginAsAdministrator();
 
         // -3- And try creating the user again
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_OK);
 
         // -4- Retrieve the user
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
 
         // -5- Delete the user and verify that it has been removed
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_OK);
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_NOT_FOUND);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_NOT_FOUND);
         
         // -6- Now create a new tenant associated with 127.0.0.1
         m_logService.log(LogService.LOG_DEBUG, "Adding test tenant");
@@ -68,27 +68,27 @@
         // Note that since the token provider is also tenant specific, using 
the same token for this
         // request should return an unauthorized response
         url = "/users/Administrator";
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_UNAUTHORIZED);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_UNAUTHORIZED);
         
         // -8- So login as Administrator and try again
         m_httpUtil.loginAsAdministrator();
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
         
         // -9- Create a new user on '127.0.0.1' and verify that this new user 
comes available on this host
         // and not on 'localhost'
         url = "/users/" + TEST_USERNAME;
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.PUT, 
HttpStatus.SC_OK);
         
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_OK);
         m_httpUtil.switchHost(HOSTNAME);
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_NOT_FOUND);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.GET, 
HttpStatus.SC_NOT_FOUND);
         
         // -10- Remove the test user
         m_httpUtil.switchHost(IP);
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_OK);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_OK);
         
         // -11- Remove the tenant and verify that a GET returns a 404
         m_tenantService.deleteTenant(tenant);
-        m_httpUtil.invokeRestApi(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_NOT_FOUND);
+        m_httpUtil.invokeHTTP(url,  javax.ws.rs.HttpMethod.DELETE, 
HttpStatus.SC_NOT_FOUND);
     }
 }

Modified: 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/launcher/AuthTest.java
==============================================================================
--- 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/launcher/AuthTest.java
        (original)
+++ 
trunk/amdatu-auth/test-integration/tests/src/test/java/org/amdatu/auth/test/integration/tests/launcher/AuthTest.java
        Tue Apr 10 11:52:09 2012
@@ -65,6 +65,11 @@
 import org.osgi.service.log.LogService;
 import org.osgi.service.useradmin.UserAdmin;
 
+/**
+ * This class is responsible for executing the individual integration tests.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
 @SuppressWarnings("deprecation")
 @RunWith(JUnit4TestRunner.class)
 @ExamReactorStrategy(AllConfinedStagedReactorFactory.class)

Modified: trunk/amdatu-auth/tools/itest/pom.xml
==============================================================================
--- trunk/amdatu-auth/tools/itest/pom.xml       (original)
+++ trunk/amdatu-auth/tools/itest/pom.xml       Tue Apr 10 11:52:09 2012
@@ -47,5 +47,11 @@
       <version>4.8.1</version>
       <scope>provided</scope>
     </dependency>
+    <dependency>
+      <groupId>org.json</groupId>
+      <artifactId>json</artifactId>
+      <version>20090211</version>
+      <scope>compile</scope>
+    </dependency>
   </dependencies>
 </project>

Modified: 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/AssertTools.java
==============================================================================
--- 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/AssertTools.java
    (original)
+++ 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/AssertTools.java
    Tue Apr 10 11:52:09 2012
@@ -1,3 +1,18 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
 package org.amdatu.auth.tools.itest;
 
 import org.hamcrest.Matcher;
@@ -5,6 +20,24 @@
 import junit.framework.Assert;
 import junit.framework.AssertionFailedError;
 
+/**
+ * When an assertion fails in a Pax Exam integration test, the stacktrace 
displayed
+ * in the error report does not represent the stack where the original 
assertion failed.
+ * Instead it shows a general stacktrace instea, no matter where the assertion 
failed:
+ * 
+ * java.lang.AssertionError: ...
+ *  at org.junit.Assert.fail(Assert.java:91)
+ *  at 
org.ops4j.pax.exam.junit.JUnit4TestRunner$2.evaluate(JUnit4TestRunner.java:263)
+ *  at 
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
+ *  at 
org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
+ *  ...
+ *  
+ * Therefore these assertion utility methods append the original stacktrace to 
the 
+ * assertion message such that this information is not lost. Very usefull when 
you
+ * want to know where the assertion failed.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
 public class AssertTools {
     // End of line
     private final static String EOL = System.getProperty("line.separator");

Modified: 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/HttpTools.java
==============================================================================
--- 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/HttpTools.java
      (original)
+++ 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/HttpTools.java
      Tue Apr 10 11:52:09 2012
@@ -15,6 +15,7 @@
  */
 package org.amdatu.auth.tools.itest;
 
+import static junit.framework.Assert.assertTrue;
 import static org.amdatu.auth.tools.itest.IntegrationTestBase.HOSTNAME;
 import static org.amdatu.auth.tools.itest.IntegrationTestBase.PORTNR;
 import static org.amdatu.auth.tools.itest.UserAdminTools.ADMIN_PASSWORD;
@@ -34,10 +35,12 @@
 import org.apache.commons.httpclient.HttpException;
 import org.apache.commons.httpclient.HttpMethod;
 import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.NameValuePair;
 import org.apache.commons.httpclient.methods.DeleteMethod;
 import org.apache.commons.httpclient.methods.GetMethod;
 import org.apache.commons.httpclient.methods.PostMethod;
 import org.apache.commons.httpclient.methods.PutMethod;
+import org.apache.commons.httpclient.methods.StringRequestEntity;
 
 /**
  * This class provides utility methods for invoking (authentorized) REST 
services.
@@ -131,34 +134,77 @@
         m_host = newHostName;
         m_restBaseUrl = "http://"; + newHostName + ":" + PORTNR + "/rest";
     }
-
-    // Invoke a REST API
-    public String invokeRestApi(String urlPostfix, String httpMethod, int 
expectedStatus) throws Exception {
-        String url = getRESTBaseUrl() + urlPostfix;
+    
+    /**
+     * Invoke a HTTP service.
+     * @param urlPostfix The postfix to append to http://[host]:[port] (should 
start with /)
+     * @param httpMethod The HTTP method call (i.e. GET or POST)
+     * @param expectedStatus The expected return status
+     * @return The result
+     * @throws Exception In case any error occurred
+     */
+    public String invokeHTTP(String urlPostfix, String httpMethod, int 
expectedStatus) throws Exception {
+        return invokeHTTP(urlPostfix, httpMethod, null, null, expectedStatus);
+    }
+    
+    /**
+     * Invoke a HTTP service.
+     * @param urlPostfix The postfix to append to http://[host]:[port] (should 
start with /)
+     * @param httpMethod The HTTP method call (i.e. GET or POST)
+     * @param inputMimeType The mimetype of the input mimetype (for POST and 
PUT)
+     * @param content The content of POST or PUT
+     * @param expectedStatus The expected return status
+     * @return The result
+     * @throws Exception In case any error occurred
+     */
+    public String invokeHTTP(String urlPostfix, String httpMethod, String 
inputMimeType, Object content,
+        int expectedStatus) throws Exception {
+        String url = m_restBaseUrl + urlPostfix;
         HttpClient httpClient = new HttpClient();
-
+       
         HttpMethod method = null;
         if ("GET".equals(httpMethod)) {
             method = new GetMethod(url);
         }
         else if ("PUT".equals(httpMethod)) {
             method = new PutMethod(url);
+            if (inputMimeType != null) {
+                StringRequestEntity entity = new StringRequestEntity((String) 
content, inputMimeType, "UTF-8");
+                ((PutMethod) method).setRequestEntity(entity);
+            }
         }
         else if ("DELETE".equals(httpMethod)) {
             method = new DeleteMethod(url);
         }
         else if ("POST".equals(httpMethod)) {
             method = new PostMethod(url);
+            if (inputMimeType != null) {
+                if ("application/x-www-form-urlencoded".equals(inputMimeType)) 
{
+                    NameValuePair[] nvps = (NameValuePair[]) content;
+                    for (NameValuePair nvp : nvps) {
+                        ((PostMethod) method).addParameter(nvp);
+                    }
+                }
+                else {
+                    StringRequestEntity entity = new 
StringRequestEntity((String) content, inputMimeType, "UTF-8");
+                    ((PostMethod) method).setRequestEntity(entity);
+                }
+            }
         }
+        
         addCookieHeader(method);
+
         try {
             // Execute the method, this should return a 200
             int statusCode = httpClient.executeMethod(method);
-            Assert.assertTrue("HTTP '" + httpMethod + "' to '" + url + "' 
returned " + statusCode,
+            assertTrue("HTTP '" + httpMethod + "' to '" + url + "' returned " 
+ statusCode,
                 statusCode == expectedStatus);
 
             // Read the response body and return it.
-            return new String(method.getResponseBody(), "UTF-8");
+            if (method.getResponseBody() != null) {
+                return new String(method.getResponseBody(), "UTF-8");
+            }
+            return null;
         }
         finally {
             // Release the connection.

Added: 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/JSONTools.java
==============================================================================
--- (empty file)
+++ 
trunk/amdatu-auth/tools/itest/src/main/java/org/amdatu/auth/tools/itest/JSONTools.java
      Tue Apr 10 11:52:09 2012
@@ -0,0 +1,132 @@
+/*
+ * Copyright (c) 2010, 2011 The Amdatu Foundation
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.amdatu.auth.tools.itest;
+
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+/**
+ * This class provides some JSON related utility methods.
+ * 
+ * @author <a href="mailto:[email protected]";>Amdatu Project 
Team</a>
+ */
+public class JSONTools {
+    /**
+     * Facilitates retrieving JSONObjects by a dot expression (i.e. 
user.address.street).
+     * 
+     * @param object The JSON object to get the object from.
+     * @param expression the dot expression to apply.
+     * @return The result of the dot expression
+     * @throws JSONException In case any JSON related exception occurred
+     */
+    public static List<JSONObject> getJSONObjects(JSONObject object, String 
expression) throws JSONException {
+        List<JSONObject> result = new ArrayList<JSONObject>();
+        String expr, subexpr;
+        if (expression.indexOf(".") == -1) {
+            expr = expression;
+            subexpr = null;
+        }
+        else {
+            expr = expression.split("\\.")[0];
+            subexpr = expression.substring(expression.indexOf(".") + 1);
+        }
+
+        if (object.has(expr)) {
+            Object obj = object.get(expr);
+            if (obj instanceof JSONObject) {
+                if (subexpr != null) {
+                    result.addAll(getJSONObjects((JSONObject) obj, subexpr));
+                }
+                else {
+                    result.add((JSONObject) obj);
+                }
+            }
+            else if (obj instanceof JSONArray) {
+                for (int i = 0; i < ((JSONArray) obj).length(); i++) {
+                    JSONObject child = (JSONObject) ((JSONArray) obj).get(i);
+                    if (subexpr != null) {
+                        result.addAll(getJSONObjects(child, subexpr));
+                    }
+                    else {
+                        result.add((JSONObject) child);
+                    }
+                }
+
+            }
+        }
+        return result;
+    }
+
+    /**
+     * Compares two JSON objects and returns if they are equal. Equals means 
that they have 
+     * the same properties with the same values, despite the order of the 
properties.
+     * 
+     * @param obj1 First object to compare.
+     * @param obj2 Second object to compare
+     * @return true of the JSON objects are equal, false otherwise.
+     * @throws JSONException In case any JSON related exception occurred
+     */
+    public static boolean compareJSON(Object obj1, Object obj2) throws 
JSONException {
+        boolean equal = true;
+        if (obj1 instanceof JSONObject) {
+            JSONObject j1 = (JSONObject) obj1;
+            JSONObject j2 = (JSONObject) obj2;
+
+            Iterator<?> keys = j1.keys();
+            while (keys.hasNext()) {
+                String key = keys.next().toString();
+                Object obj = j1.get(key);
+                if (!j2.has(key)) {
+                    return false;
+                }
+                if (obj instanceof JSONObject) {
+                    equal &= compareJSON((JSONObject) obj, (JSONObject) 
j2.get(key));
+                }
+                else if (obj instanceof JSONArray) {
+                    equal &= compareJSON(obj, j2.get(key));
+                }
+                else if (obj instanceof String) {
+                    equal &= ((String) obj).equals(j2.get(key).toString());
+                }
+                else if (obj instanceof Integer) {
+                    equal &= (Integer) obj == 
Integer.parseInt(j2.get(key).toString());
+                }
+            }
+        }
+        else if (obj1 instanceof JSONArray) {
+            JSONArray j1 = (JSONArray) obj1;
+            JSONArray j2 = (JSONArray) obj2;
+
+            equal &= j1.length() == j2.length();
+
+            for (int i = 0; i < j1.length(); i++) {
+                Object o1 = j1.get(i);
+
+                boolean found = false;
+                for (int j = 0; j < j2.length(); j++) {
+                    found |= compareJSON(o1, j2.get(j));
+                }
+                equal &= found;
+            }
+        }
+        return equal;
+    }
+}
_______________________________________________
Amdatu-commits mailing list
[email protected]
http://lists.amdatu.org/mailman/listinfo/amdatu-commits

Reply via email to