Author: [email protected]
Date: Tue Nov 29 11:44:33 2011
New Revision: 1799

Log:
Added doclet for automated REST documentation

Added:
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/pom.xml
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/
   sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/
   
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/
   
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/
   
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/
   
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/ClassAnalyzer.java
   
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/RESTDoclet.java
Modified:
   sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/pom.xml
   
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
   
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java

Added: sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/pom.xml
==============================================================================
--- (empty file)
+++ sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/pom.xml     Tue Nov 
29 11:44:33 2011
@@ -0,0 +1,51 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  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.verning permissions and limitations
+  under the License.
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0"; 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
http://maven.apache.org/maven-v4_0_0.xsd";>
+  <modelVersion>4.0.0</modelVersion>
+  <parent>
+    <groupId>org.amdatu.gadgetcontainer</groupId>
+    <artifactId>org.amdatu.gadgetcontainer</artifactId>
+    <version>1.0.0-SNAPSHOT</version>
+  </parent>
+  <artifactId>org.amdatu.doclet.rest</artifactId>
+  <packaging>jar</packaging>
+  <name>Amdatu Doclet - REST</name>
+  <description>A doclet to generate REST documentation</description>
+
+  <dependencies>
+    <dependency>
+      <groupId>javax.ws.rs</groupId>
+      <artifactId>jsr311-api</artifactId>
+      <version>1.1.1</version>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>commons-io</groupId>
+      <artifactId>commons-io</artifactId>
+      <version>2.1</version>
+      <scope>compile</scope>
+    </dependency>
+    <dependency>
+      <groupId>com.sun</groupId>
+      <artifactId>tools</artifactId>
+      <version>1.4.2</version>
+      <scope>system</scope>
+      <systemPath>${java.home}/../lib/tools.jar</systemPath>
+    </dependency>
+  </dependencies>
+</project>

Added: 
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/ClassAnalyzer.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/ClassAnalyzer.java
     Tue Nov 29 11:44:33 2011
@@ -0,0 +1,181 @@
+/*
+ * 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.doclet.rest;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.ws.rs.DELETE;
+import javax.ws.rs.FormParam;
+import javax.ws.rs.GET;
+import javax.ws.rs.HEAD;
+import javax.ws.rs.OPTIONS;
+import javax.ws.rs.POST;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.PathParam;
+import javax.ws.rs.QueryParam;
+
+import com.sun.javadoc.AnnotationDesc;
+import com.sun.javadoc.AnnotationDesc.ElementValuePair;
+import com.sun.javadoc.AnnotationTypeDoc;
+import com.sun.javadoc.ClassDoc;
+import com.sun.javadoc.MethodDoc;
+import com.sun.javadoc.ParamTag;
+import com.sun.javadoc.Parameter;
+import com.sun.javadoc.Tag;
+
+public class ClassAnalyzer {
+    private static final Class<?>[] HTTP_METHODS = new Class[] { GET.class, 
POST.class, PUT.class, DELETE.class,
+        HEAD.class, OPTIONS.class };
+
+    // Returns the REST Path
+    public String getPath(ClassDoc classDoc, MethodDoc methodDoc) {
+        String path = "/rest";
+        String[] classPath = getAnnotationValues(classDoc, Path.class);
+        if (classPath != null && classPath.length == 1) {
+            path += "/" + classPath[0];
+        }
+        String[] resourcePath = getAnnotationValues(methodDoc, Path.class);
+        if (resourcePath != null && resourcePath.length == 1) {
+            if (resourcePath[0].startsWith("/")) {
+                path += resourcePath[0];
+            }
+            else {
+                path += "/" + resourcePath[0];
+            }
+        }
+        return path;
+    }
+
+    // Returns the HTTP Method annotation
+    public String getHTTPMethod(MethodDoc methodDoc) {
+        AnnotationDesc[] annotationDescs = methodDoc.annotations();
+        if (annotationDescs != null) {
+            for (AnnotationDesc annotationDesc : annotationDescs) {
+                AnnotationTypeDoc type = annotationDesc.annotationType();
+                for (Class<?> httpMethod : HTTP_METHODS) {
+                    if (type.qualifiedName().equals(httpMethod.getName())) {
+                        return 
type.qualifiedName().substring(type.qualifiedName().lastIndexOf(".") + 1);
+                    }
+                }
+            }
+        }
+        return null;
+    }
+
+    public String[] getAnnotationValues(ClassDoc classDoc, Class<?> 
annotation) {
+        return getAnnotationValues(classDoc.annotations(), annotation);
+    }
+
+    public String[] getAnnotationValues(MethodDoc methodDoc, Class<?> 
annotation) {
+        return getAnnotationValues(methodDoc.annotations(), annotation);
+    }
+
+    // Returns the descriptive javadoc
+    public String getDescription(MethodDoc methodDoc) {
+        return methodDoc.commentText();
+    }
+
+    // Returns the description of all PathParam annotated parameters
+    public List<String> getPathParameters(MethodDoc methodDoc) {
+        return getParameters(methodDoc, PathParam.class);
+    }
+
+    // Returns the description of all QueryParam annotated parameters
+    public List<String> getQueryParameters(MethodDoc methodDoc) {
+        return getParameters(methodDoc, QueryParam.class);
+    }
+
+    // Returns the description of all formParam annotated parameters
+    public List<String> getFormParameters(MethodDoc methodDoc) {
+        return getParameters(methodDoc, FormParam.class);
+    }
+
+    public String getReturn(MethodDoc methodDoc) {
+        Tag[] tags = methodDoc.tags();
+        if (tags != null) {
+            for (Tag tag : tags) {
+                if ("@return".equals(tag.kind())) {
+                    return tag.text();
+                }
+            }
+        }
+        return "-";
+    }
+
+    private List<String> getParameters(MethodDoc methodDoc, Class<?> 
annotationClass) {
+        List<String> pathParameters = new ArrayList<String>();
+        Parameter[] params = methodDoc.parameters();
+        if (params != null) {
+            ParamTag[] tags = methodDoc.paramTags();
+            for (Parameter param : params) {
+                AnnotationDesc[] annotationDescs = param.annotations();
+                if (annotationDescs != null) {
+                    for (AnnotationDesc annotationDesc : annotationDescs) {
+                        AnnotationTypeDoc type = 
annotationDesc.annotationType();
+                        if 
(type.qualifiedName().equals(annotationClass.getName())) {
+                            // This is a path parameter, find the param tag 
matching the parameter
+                            String javadoc = null;
+                            if (tags != null) {
+                                for (ParamTag tag : tags) {
+                                    if 
(tag.parameterName().equals(param.name())) {
+                                        javadoc = tag.parameterComment();
+                                    }
+                                }
+                            }
+                            String descr = param.toString();
+                            if (javadoc != null) {
+                                descr += " : " + javadoc;
+                            }
+                            pathParameters.add(descr);
+                        }
+                    }
+                }
+            }
+        }
+        return pathParameters;
+    }
+
+    private String[] getAnnotationValues(AnnotationDesc[] annotationDescs, 
Class<?> annotation) {
+        if (annotationDescs != null) {
+            for (AnnotationDesc annotationDesc : annotationDescs) {
+                AnnotationTypeDoc type = annotationDesc.annotationType();
+                if (type.qualifiedName().equals(annotation.getName())) {
+                    String[] vals = new 
String[annotationDesc.elementValues().length];
+                    int i = 0;
+                    for (ElementValuePair value : 
annotationDesc.elementValues()) {
+                        vals[i] = omitQuotes(value.value().toString());
+                        i++;
+                    }
+                    return vals;
+                }
+            }
+        }
+        return null;
+    }
+
+    private String omitQuotes(String value) {
+        String result = value;
+        if (result.startsWith("\"")) {
+            result = result.substring(1);
+        }
+        if (result.endsWith("\"")) {
+            result = result.substring(0, result.length() - 1);
+        }
+        return result;
+    }
+}

Added: 
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/RESTDoclet.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/amdatu-gadget-container/amdatu-rest-doclet/src/main/java/org/amdatu/doclet/rest/RESTDoclet.java
        Tue Nov 29 11:44:33 2011
@@ -0,0 +1,118 @@
+/*
+ * 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.doclet.rest;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
+import javax.ws.rs.Path;
+
+import org.apache.commons.io.FileUtils;
+
+import com.sun.javadoc.ClassDoc;
+import com.sun.javadoc.MethodDoc;
+import com.sun.javadoc.RootDoc;
+
+public class RESTDoclet {
+
+    private final static String EOL = System.getProperty("line.separator");
+
+    private static File m_file = null;
+
+    private static ClassAnalyzer m_classAnalyzer = new ClassAnalyzer();
+
+    public static void main(String[] args) {
+        com.sun.tools.javadoc.Main.execute(new String[] { "@options", 
"@packages" });
+    }
+
+    public static boolean start(RootDoc root) throws IOException {
+        System.out.println("***** Generating REST dcoumentation for " + 
root.getClass().toString() + " *****");
+        ClassDoc[] docClasses = root.classes();
+        for (int i = 0; i < docClasses.length; ++i) {
+            // Detect if the JAX-RS @Path annotation is present, this makes it 
a REST service
+            String[] annotations = 
m_classAnalyzer.getAnnotationValues(docClasses[i], Path.class);
+            if (annotations != null && annotations.length > 0) {
+                handle(docClasses[i]);
+            }
+        }
+        System.out.println("***** DONE ****");
+        return true;
+    }
+
+    private static void handle(ClassDoc classDoc) throws IOException {
+        System.out.println("> Generating documentation for REST resource " + 
classDoc);
+
+        // Initialize the result .html file
+        initFile(classDoc);
+
+        MethodDoc[] methodDocs = classDoc.methods();
+        if (methodDocs != null) {
+            for (MethodDoc methodDoc : methodDocs) {
+                // Check if the method is annotated with GET, POST
+                if (m_classAnalyzer.getHTTPMethod(methodDoc) != null) {
+                    handle(classDoc, methodDoc);
+                }
+            }
+        }
+    }
+
+    private static void initFile(ClassDoc classDoc) throws IOException {
+        m_file = new File(classDoc + "-api.html");
+        if (m_file.exists()) {
+            m_file.delete();
+        }
+        m_file.createNewFile();
+        Collection<String> lines = new ArrayList<String>();
+        lines.add("<html>");
+        lines.add("<body>");
+    }
+
+    private static void handle(ClassDoc classDoc, MethodDoc methodDoc) throws 
IOException {
+        System.out.println("> Generating documentation for HTTP method " + 
methodDoc);
+
+        Collection<String> lines = new ArrayList<String>();
+        lines.add("<br/><table border='1'>");
+        lines.add(getRow("URI", m_classAnalyzer.getPath(classDoc, methodDoc)));
+        lines.add(getRow("Method", m_classAnalyzer.getHTTPMethod(methodDoc)));
+        lines.add(getRow("Description", 
m_classAnalyzer.getDescription(methodDoc)));
+        lines.add(getRow("Path parameters", 
toUl(m_classAnalyzer.getPathParameters(methodDoc))));
+        lines.add(getRow("Query parameters", 
toUl(m_classAnalyzer.getQueryParameters(methodDoc))));
+        lines.add(getRow("Body parameters", 
toUl(m_classAnalyzer.getFormParameters(methodDoc))));
+        lines.add(getRow("Response", m_classAnalyzer.getReturn(methodDoc)));
+        lines.add("</table>");
+        FileUtils.writeLines(m_file, lines, EOL, true);
+    }
+
+    private static String getRow(String key, String value) {
+        return "<tr><th align='left' valign='top'>" + key + "</th><td 
align='left' valign='top'>" + value
+            + "</td></tr>";
+    }
+    
+    private static String toUl(List<String> values) {
+        if (values != null && values.size() > 0) {
+            String ul = "<ul>";
+            for (String value : values) {
+                ul += "<li>" + value + "</li>";
+            }
+            ul += "</ul>";
+            return ul;
+        }
+        return "-";
+    }
+}
\ No newline at end of file

Modified: sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/pom.xml
==============================================================================
--- sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/pom.xml       
(original)
+++ sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/pom.xml       
Tue Nov 29 11:44:33 2011
@@ -133,6 +133,24 @@
           </instructions>
         </configuration>
       </plugin>
+
+      <!-- At build time, generate the REST documentation using a custom 
javadoc Doclet -->
+      <plugin>
+        <groupId>org.apache.maven.plugins</groupId>
+        <artifactId>maven-javadoc-plugin</artifactId>
+        <version>2.8</version>
+        <configuration>
+          <useStandardDocletOptions>false</useStandardDocletOptions>
+          <doclet>org.amdatu.doclet.rest.RESTDoclet</doclet>
+          <docletArtifact>
+            <groupId>org.amdatu.gadgetcontainer</groupId>
+            <artifactId>org.amdatu.doclet.rest</artifactId>
+            <version>1.0.0-SNAPSHOT</version>
+          </docletArtifact>
+          <debug>true</debug>
+        </configuration>
+      </plugin>
+
     </plugins>
   </build>
 

Modified: 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
==============================================================================
--- 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
  (original)
+++ 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
  Tue Nov 29 11:44:33 2011
@@ -31,6 +31,7 @@
 import javax.ws.rs.Path;
 import javax.ws.rs.PathParam;
 import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.CacheControl;
 import javax.ws.rs.core.Context;
@@ -62,6 +63,11 @@
 
     private static final String DEFAULT_ADMIN_GROUP = "Administrators";
 
+    private static final String UNAUTHORIZED_ERROR =
+        "401-UNAUTHORIZED. You do not have the proper authorization to manage 
tenants.";
+
+    private int DEFAULT_ITEMSPERPAGE = 10;
+
     private static String VALID_HOSTNAME_REGEX =
         
"^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\\-]*[a-zA-Z0-9])\\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\\-]*[A-Za-z0-9])$";
 
@@ -80,7 +86,7 @@
     private volatile UserAdmin m_userAdmin;
     private volatile TokenProvider m_tokenProvider;
     private volatile DependencyManager m_dependencyManager;
-    
+
     /**
      * The init() method is invoked by the Felix dependency manager.
      * 
@@ -123,20 +129,59 @@
         return "Tenant service online";
     }
 
+    @GET
+    @Produces({ MediaType.TEXT_HTML })
+    @Path("api")
+    public String documentation() {
+        String html = "<html><body><table border='1'>";
+        html += addTD("URI", "/rest/tenants");
+        html += addTD("Method", "GET");
+        html += addTD("Description", "Returns available tenants.");
+        html += addTD("Path parameters", "-");
+        html +=
+            addTD("Query parameters",
+                "<ul><li>startIndex: The start index</li><li>itemsPerPage: nr 
of items per page</ul>");
+        html += addTD("Body parameters", "-");
+        html +=
+            addTD(
+                "Response",
+                "<ul><li>200 (OK): Returns the requested tenants</li><li>401 
(UNAUTHORIZED): returned in case the user is not logged in or unauthorized to 
manage tenants.</li><li></ul>");
+
+        html += "</table></body></html>";
+        return html;
+    }
+
+    private String addTD(String key, String value) {
+        return "<tr><th align='left' valign='top'>" + key + "</th><td 
align='left' valign='top'>" + value
+            + "</td></tr>";
+    }
+
     /**
-     * Returns available tenants.
-     * Example: GET /rest/tenants
+     * Returns available tenants. Example: GET /rest/tenants
      * 
-     * @param request The http servlet request
-     * @return JSON expression containing the list of tenants.
+     * @param request The HTTP request
+     * @param startIndex The startindex (optional)
+     * @param itemsPerPage The number of items per page to return (optional)
+     * @return <ul>
+     *         <li>200 (OK) : Returns the requested tenants</li>
+     *         <li>401 (UNAUTHORIZED) : returned in case the user is not 
logged in or unauthorized to manage tenants.</li>
+     *         </ul>
      */
     @GET
-    @Produces({ MediaType.APPLICATION_JSON })
-    public Response getTenants(@Context final HttpServletRequest request) {
+    @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
+    public Response getTenants(@Context final HttpServletRequest request,
+        @QueryParam(value = "startIndex") final int startIndex,
+        @QueryParam(value = "itemsPerPage") int itemsPerPage) {
         if (isAuthorized(request)) {
-            TenantsBean tenantsBean = new TenantsBean();
             try {
-                for (TenantBean tenant : m_tenantDAO.getTenants()) {
+                TenantsBean tenantsBean = new TenantsBean();
+                if (itemsPerPage <= 0) {
+                    itemsPerPage = DEFAULT_ITEMSPERPAGE;
+                }
+                List<TenantBean> unfilteredTenants = m_tenantDAO.getTenants();
+                List<TenantBean> tenants = getPage(unfilteredTenants, 
startIndex, itemsPerPage);
+
+                for (TenantBean tenant : tenants) {
                     String href = request.getContextPath() + REST_URL + "/" + 
tenant.getId();
                     tenant.addLink(new 
AtomSyndicationLink().setHref(href).setRel("edit").setType("application/json"));
                     if (!tenant.getId().equals(m_tenant.getId())) {
@@ -147,23 +192,59 @@
                     }
                     tenantsBean.addTenant(tenant);
                 }
+
+                // Return an uncacheable response. The REST service is invoked 
by the tenant manager gadget,
+                // so it is very likely that tenants have been updated, added 
or removed between subsequent
+                // GET requests and it makes no sense to cache them.
+                tenantsBean.setStartIndex(startIndex);
+                tenantsBean.setTotalPages((int) Math.ceil(new 
Double(unfilteredTenants.size())
+                    / new Double(itemsPerPage)));
+                tenantsBean.setTotalResults(unfilteredTenants.size());
+                tenantsBean.setItemsPerPage(10);
+
+                return uncachedResponse(tenantsBean);
             }
             catch (Exception e) {
                 m_logService.log(LogService.LOG_ERROR, "An error occured while 
retrieving tenants", e);
-                throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
+                throwInternalServerError(e, "An error occured while retrieving 
tenants");
             }
-
-            return Response.ok(tenantsBean, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL).build();
         }
         else {
-            return 
Response.status(org.apache.http.HttpStatus.SC_UNAUTHORIZED).cacheControl(NO_CACHE_CONTROL).build();
+            throwNoAuthorizationException();
+        }
+
+        // Unreachable code, but compiler doesn't know
+        return null;
+    }
+
+    private List<TenantBean> getPage(List<TenantBean> tenants, int startIndex, 
int itemsPerPage) {
+        List<TenantBean> filteredTenants = new ArrayList<TenantBean>();
+        for (int i = startIndex; i < (startIndex + itemsPerPage); i++) {
+            if (i < tenants.size()) {
+                filteredTenants.add(tenants.get(i));
+            }
         }
+        return filteredTenants;
+    }
+
+    private Response uncachedResponse(Object entity) {
+        return Response.ok(entity).cacheControl(NO_CACHE_CONTROL).build();
+    }
+
+    private void throwInternalServerError(Exception e, String msg) {
+        throw new 
WebApplicationException(Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(msg).build());
+    }
+
+    private void throwNoAuthorizationException() {
+        throw new 
WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).entity(UNAUTHORIZED_ERROR)
+            .build());
     }
 
     /**
      * Returns the specified tenant.
      * Example: GET /rest/tenants/default_tenant
      * 
+     * @param id The id of the tenant to retrieve
      * @param request The http servlet request
      * @return JSON expression containing the specified tenant.
      */
@@ -201,7 +282,7 @@
     @Consumes("application/x-www-form-urlencoded")
     @Path("/{id}")
     public Response setTenant(@PathParam("id") final String id, 
@FormParam("name") final String name,
-        @FormParam("hostname") final String hostname, @FormParam("email") 
final String email, 
+        @FormParam("hostname") final String hostname, @FormParam("email") 
final String email,
         @Context final HttpServletRequest request) {
         if (isAuthorized(request)) {
             try {
@@ -225,7 +306,7 @@
             return 
Response.status(org.apache.http.HttpStatus.SC_UNAUTHORIZED).cacheControl(NO_CACHE_CONTROL).build();
         }
     }
-    
+
     /**
      * Deletes an existing tenant.
      * Example: DELETE /rest/tenants/default_tenant
@@ -234,20 +315,20 @@
     @Path("/{id}")
     public Response deleteTenant(@PathParam("id") final String id, @Context 
final HttpServletRequest request) {
         if (isAuthorized(request)) {
-        TenantBean tenant = null;
-        try {
-            if (m_tenantDAO.deleteTenant(id)) {               
-                return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
-                    .build();
+            TenantBean tenant = null;
+            try {
+                if (m_tenantDAO.deleteTenant(id)) {
+                    return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
+                        .build();
+                }
+                else {
+                    return 
Response.noContent().cacheControl(NO_CACHE_CONTROL).build();
+                }
             }
-            else {
-                return 
Response.noContent().cacheControl(NO_CACHE_CONTROL).build();
+            catch (Exception e) {
+                throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
             }
         }
-        catch (Exception e) {
-            throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
-        }
-        }
         else {
             return 
Response.status(org.apache.http.HttpStatus.SC_UNAUTHORIZED).cacheControl(NO_CACHE_CONTROL).build();
         }
@@ -283,27 +364,33 @@
     }
 
     private boolean isAuthorized(final HttpServletRequest request) {
-        String token = m_tokenProvider.getTokenFromRequest(request);
-        if (token != null) {
-            try {
-                Map<String, String> attributes = 
m_tokenProvider.verifyToken(token);
-                if (attributes.containsKey(TokenProvider.USERNAME)) {
-                    String userName = attributes.get(TokenProvider.USERNAME);
-                    if (userName != null && !userName.isEmpty()) {
-                        User user = (User) m_userAdmin.getRole(userName);
-                        if (user != null) {
-                            return 
m_userAdmin.getAuthorization(user).hasRole(DEFAULT_ADMIN_GROUP);
+        try {
+            String token = m_tokenProvider.getTokenFromRequest(request);
+            if (token != null) {
+                try {
+                    Map<String, String> attributes = 
m_tokenProvider.verifyToken(token);
+                    if (attributes.containsKey(TokenProvider.USERNAME)) {
+                        String userName = 
attributes.get(TokenProvider.USERNAME);
+                        if (userName != null && !userName.isEmpty()) {
+                            User user = (User) m_userAdmin.getRole(userName);
+                            if (user != null) {
+                                return 
m_userAdmin.getAuthorization(user).hasRole(DEFAULT_ADMIN_GROUP);
+                            }
                         }
                     }
                 }
+                catch (TokenProviderException e) {
+                    // Ignore invalid tokens
+                }
+                catch (InvalidTokenException e) {
+                    // Ignore invalid tokens
+                }
             }
-            catch (TokenProviderException e) {
-                // Ignore invalid tokens
-            }
-            catch (InvalidTokenException e) {
-                // Ignore invalid tokens
-            }
+            return false;
+        }
+        catch (Exception e) {
+            m_logService.log(LogService.LOG_ERROR, "Could not evaluate Amdatu 
token", e);
+            return false;
         }
-        return false;
     }
 }

Modified: 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
==============================================================================
--- 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
    (original)
+++ 
sandbox/ivol/amdatu-gadget-container/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
    Tue Nov 29 11:44:33 2011
@@ -27,8 +27,45 @@
 @XmlRootElement(name = "tenants")
 @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
 public class TenantsBean {
+    private int m_startIndex;
+    private int m_itemsPerPage;
+    private int m_totalResults;
+    private int m_totalPages;
     private List<TenantBean> m_tenants;
 
+    
+    public int getStartIndex() {
+        return m_startIndex;
+    }
+
+    public void setStartIndex(int startIndex) {
+        m_startIndex = startIndex;
+    }
+
+    public int getItemsPerPage() {
+        return m_itemsPerPage;
+    }
+
+    public void setItemsPerPage(int itemsPerPage) {
+        m_itemsPerPage = itemsPerPage;
+    }
+
+    public int getTotalResults() {
+        return m_totalResults;
+    }
+
+    public void setTotalResults(int totalResults) {
+        m_totalResults = totalResults;
+    }
+
+    public int getTotalPages() {
+        return m_totalPages;
+    }
+
+    public void setTotalPages(int totalPages) {
+        m_totalPages = totalPages;
+    }
+
     @XmlElement(name = "tenant")
     public List<TenantBean> getTenants() {
         return m_tenants;
_______________________________________________
Amdatu-commits mailing list
[email protected]
http://lists.amdatu.org/mailman/listinfo/amdatu-commits

Reply via email to