Author: [email protected]
Date: Tue Nov 15 16:57:31 2011
New Revision: 1722

Log:


Added:
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailService.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailServiceImpl.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAO.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAOImpl.java
Removed:
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigUpdateListenerImpl.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantMutationColumnFamilyProviderImpl.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantMutationDAO.java
Modified:
   sandbox/ivol/tenant-management-gadget/pom.xml
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/osgi/Activator.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantBean.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
   
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
   sandbox/ivol/tenant-management-gadget/src/main/resources/jsp/TenantGadget.jsp
   
sandbox/ivol/tenant-management-gadget/src/main/resources/static/css/tenant.css
   sandbox/ivol/tenant-management-gadget/src/main/resources/static/js/tenant.js
   
sandbox/ivol/tenant-management-gadget/src/main/resources/static/labels/tenantmgmt_ALL_ALL.xml

Modified: sandbox/ivol/tenant-management-gadget/pom.xml
==============================================================================
--- sandbox/ivol/tenant-management-gadget/pom.xml       (original)
+++ sandbox/ivol/tenant-management-gadget/pom.xml       Tue Nov 15 16:57:31 2011
@@ -29,7 +29,6 @@
 
   <properties>
     <amdatu.opensocial.version>0.2.0</amdatu.opensocial.version>
-    <amdatu.cassandra.version>0.2.1-RC2</amdatu.cassandra.version>
   </properties>
 
   <dependencies>
@@ -94,32 +93,10 @@
       <scope>provided</scope>
     </dependency>
     <dependency>
-      <groupId>org.amdatu.cassandra</groupId>
-      <artifactId>org.amdatu.cassandra.listener</artifactId>
-      <version>${amdatu.cassandra.version}</version>
-      <scope>provided</scope>
-      <type>bundle</type>
-    </dependency>
-    <dependency>
-      <groupId>org.amdatu.cassandra</groupId>
-      <artifactId>org.amdatu.cassandra.application</artifactId>
-      <version>${amdatu.cassandra.version}</version>
-      <scope>provided</scope>
-      <type>bundle</type>
-    </dependency>
-    <dependency>
-      <groupId>org.amdatu.cassandra</groupId>
-      <artifactId>org.amdatu.cassandra.persistencemanager</artifactId>
-      <version>${amdatu.cassandra.version}</version>
-      <scope>provided</scope>
-      <type>bundle</type>
-    </dependency>
-    <dependency>
-      <groupId>org.amdatu.cassandra</groupId>
-      <artifactId>org.amdatu.cassandra.persistencemanager.hector</artifactId>
-      <version>${amdatu.cassandra.version}</version>
-      <scope>provided</scope>
-      <type>bundle</type>
+      <groupId>javax.mail</groupId>
+      <artifactId>mail</artifactId>
+      <version>1.4.4</version>
+      <scope>compile</scope>
     </dependency>
   </dependencies>
 
@@ -171,6 +148,10 @@
             <Embed-Dependency>*;scope=compile</Embed-Dependency>
             <Embed-Transitive>true</Embed-Transitive>
             <Export-Package></Export-Package>
+            <Import-Package>
+              !sun.security.util,
+              *
+            </Import-Package>
           </instructions>
         </configuration>
       </plugin>

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/osgi/Activator.java
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/osgi/Activator.java
 (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/osgi/Activator.java
 Tue Nov 15 16:57:31 2011
@@ -18,15 +18,16 @@
 import java.util.Dictionary;
 import java.util.Hashtable;
 
-import org.amdatu.cassandra.listener.ColumnFamilyProvider;
-import 
org.amdatu.cassandra.persistencemanager.hector.HectorCassandraPersistenceManager;
 import org.amdatu.core.tenant.Tenant;
 import org.amdatu.libraries.utilities.osgi.ServiceDependentActivator;
 import org.amdatu.opensocial.gadgetmanagement.GadgetDefinitionProvider;
+import org.amdatu.opensocial.tenant.gadget.service.EMailService;
+import org.amdatu.opensocial.tenant.gadget.service.EMailServiceImpl;
+import org.amdatu.opensocial.tenant.gadget.service.TenantConfigDAO;
+import org.amdatu.opensocial.tenant.gadget.service.TenantConfigDAOImpl;
 import org.amdatu.opensocial.tenant.gadget.service.TenantGadgetDefinition;
 import org.amdatu.opensocial.tenant.gadget.service.TenantGadgetImpl;
 import org.amdatu.opensocial.tenant.gadget.service.TenantRESTServiceImpl;
-import 
org.amdatu.opensocial.tenant.gadget.service.TenantMutationColumnFamilyProviderImpl;
 import org.amdatu.web.dispatcher.DispatcherService;
 import org.amdatu.web.httpcontext.ResourceProvider;
 import org.amdatu.web.jsp.JspSupport;
@@ -86,6 +87,18 @@
         manager.add(createAdapterService(Tenant.class, null)
             .setInterface(GadgetDefinitionProvider.class.getName(), null)
             .setImplementation(TenantGadgetDefinition.class));
+        
+        // Create and register the EMail service
+        manager.add(createComponent()
+            .setInterface(EMailService.class.getName(), null)
+            .setImplementation(EMailServiceImpl.class));
+        
+        // Create and register the TenantConfigDAO service
+        manager.add(
+            createComponent()
+                .setInterface(new String[] { TenantConfigDAO.class.getName() 
}, null)
+                .setImplementation(TenantConfigDAOImpl.class)
+                
.add(createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true)));
 
         // Create and register the REST tenant service
         manager.add(
@@ -93,14 +106,8 @@
                 .setInterface(new String[] { RESTService.class.getName() }, 
null)
                 .setImplementation(TenantRESTServiceImpl.class)
                 
.add(createServiceDependency().setService(LogService.class).setRequired(true))
-                
.add(createServiceDependency().setService(ConfigurationAdmin.class).setRequired(true))
-                
.add(createServiceDependency().setService(HectorCassandraPersistenceManager.class).setRequired(true)));
-
-        // Define a service that provides the ColumnFamily we need
-        manager.add(
-            createComponent()
-                .setInterface(new String[] { 
ColumnFamilyProvider.class.getName() }, null)
-                
.setImplementation(TenantMutationColumnFamilyProviderImpl.class));
+                
.add(createServiceDependency().setService(EMailService.class).setRequired(true))
+                
.add(createServiceDependency().setService(TenantConfigDAO.class).setRequired(true)));
     }
 
     @Override

Added: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailService.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailService.java
   Tue Nov 15 16:57:31 2011
@@ -0,0 +1,7 @@
+package org.amdatu.opensocial.tenant.gadget.service;
+
+import javax.mail.MessagingException;
+
+public interface EMailService {
+    public void send(String email, String subject, String content) throws 
MessagingException;
+}

Added: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailServiceImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/EMailServiceImpl.java
       Tue Nov 15 16:57:31 2011
@@ -0,0 +1,68 @@
+package org.amdatu.opensocial.tenant.gadget.service;
+
+import java.util.Properties;
+
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Session;
+import javax.mail.Transport;
+import javax.mail.internet.InternetAddress;
+import javax.mail.internet.MimeMessage;
+
+public class EMailServiceImpl implements EMailService {
+    private String smtpServer = "smtp.gx.nl";
+    private String port = "21";
+    private String user = "";
+    private String password = "";
+    private String auth = "";
+    private String from = "[email protected]";
+
+    private Properties prepareProperties()
+    {
+        Properties props = new Properties();
+        props.setProperty("mail.smtp.host", smtpServer);
+        //props.setProperty("mail.smtp.port", port);
+       // props.setProperty("mail.smtp.user", user);
+       // props.setProperty("mail.smtp.password", password);
+        props.setProperty("mail.smtp.auth", auth);
+        return props;
+    }
+
+    private MimeMessage prepareMessage(Session mailSession, String charset,
+        String from, String subject,
+        String HtmlMessage, String[] recipient) {
+        // Multipurpose Internet Mail Extensions
+        MimeMessage message = null;
+        try {
+            message = new MimeMessage(mailSession);
+            message.setFrom(new InternetAddress(from));
+            message.setSubject(subject);
+            for (int i = 0; i < recipient.length; i++)
+                message.addRecipient(Message.RecipientType.TO, new 
InternetAddress(recipient[i]));
+            message.setContent(HtmlMessage, "text/html; charset=\"" + charset 
+ "\"");
+        }
+        catch (Exception ex) {}
+        return message;
+    }
+
+    public void send(String email, String subject, String content) throws 
MessagingException {
+        sendEmail(subject, content, new String[] { email });
+    }
+
+    public void sendEmail(String subject, String HtmlMessage, String[] to) 
throws MessagingException
+    {
+        Transport transport = null;
+        try {
+            Properties props = prepareProperties();
+            Session mailSession = Session.getDefaultInstance(props);
+            transport = mailSession.getTransport("smtp");
+            MimeMessage message = prepareMessage(mailSession, "ISO-8859-2", 
from, subject, HtmlMessage, to);
+            transport.connect();
+            Transport.send(message);
+        }
+        finally {
+            transport.close();
+        }
+    }
+
+}

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantBean.java
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantBean.java
     (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantBean.java
     Tue Nov 15 16:57:31 2011
@@ -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.opensocial.tenant.gadget.service;
 
 import java.util.ArrayList;
@@ -9,6 +24,12 @@
 
 import org.amdatu.libraries.utilities.rest.AtomSyndicationLink;
 
+/**
+ * This class represents a Tenant used in JSON expressions returned by the 
Tenant REST interface.
+ * @author ivol
+ *
+ */
+@SuppressWarnings("restriction")
 @XmlRootElement(name = "tenant")
 @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
 public class TenantBean implements Comparable<TenantBean>{

Added: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAO.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAO.java
        Tue Nov 15 16:57:31 2011
@@ -0,0 +1,61 @@
+/*
+ * 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.opensocial.tenant.gadget.service;
+
+import java.io.IOException;
+import java.util.List;
+
+/**
+ * This interface represents a service that provides CRUD operations for 
tenant configuations
+ * managed by ConfigurationAdmin.
+ * 
+ * @author ivol
+ */
+public interface TenantConfigDAO {
+    /**
+     * Returns a list of tenants currently available in ConfigurationAdmin.
+     * @return list of tenants currently available in ConfigurationAdmin.
+     * @throws IOException In case the tenant configuration could not be read 
from ConfigurationAdmin
+     */
+    List<TenantBean> getTenants() throws IOException;
+    
+    /**
+     * Returns the tenant with the specified id or null if it could not be 
found.
+     * @param tenantId The id of the tenant to retrieve
+     * @return the tenant with the specified id or null if it could not be 
found.
+     * @throws IOException In case the tenant configuration could not be read 
from ConfigurationAdmin
+     */
+    TenantBean getTenant(String tenantId) throws IOException;
+ 
+    /**
+     * Creates a new tenant (in case no tenant with the specified id exists) 
or updates an existing 
+     * tenant (in case a tenant with the specified id exists). 
+     * @param id The id of the tenant to create or update
+     * @param name The name of the tenant to create or update
+     * @param hostname The hostname of the tenant to create or update
+     * @param returns true if a tenant was added, false if it was updated
+     * @throws IOException In case the tenant configuration could not be read 
from ConfigurationAdmin
+     */
+    boolean setTenant(String id, String name, String hostname) throws 
IOException;
+    
+    /**
+     * Deletes the tenant with the specified id.
+     * @param tenantId The id of the tenant to remove.
+     * @throws IOException In case the tenant configuration could not be read 
from ConfigurationAdmin
+     * @return true if the tenant was found and deleted, false if no tenant 
exists with the specified id
+     */
+    boolean deleteTenant(String tenantId) throws IOException;
+}

Added: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAOImpl.java
==============================================================================
--- (empty file)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantConfigDAOImpl.java
    Tue Nov 15 16:57:31 2011
@@ -0,0 +1,155 @@
+/*
+ * 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.opensocial.tenant.gadget.service;
+
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.amdatu.core.tenant.Tenant;
+import org.amdatu.core.tenant.TenantManagementService;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+
+@SuppressWarnings({ "rawtypes", "deprecation", "unchecked" })
+public class TenantConfigDAOImpl implements TenantConfigDAO {
+    // Service dependencies
+    private volatile ConfigurationAdmin m_configAdmin;
+
+    public List<TenantBean> getTenants() throws IOException {
+        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+        Dictionary properties = config.getProperties();
+        List<TenantBean> tenants = new ArrayList<TenantBean>();
+        int keyId = 1;
+        String key = "tenant" + keyId;
+        boolean exists = properties.get(key + ".id") != null;
+        while (exists) {
+            tenants.add(getTenantByKey(key));
+            keyId++;
+            key = "tenant" + keyId;
+            exists = properties.get(key + ".id") != null;
+        }
+
+        Collections.sort(tenants);
+        return tenants;
+    }
+
+    // This returns the tenant by its id, for example 'default'
+    public TenantBean getTenant(String tenantId) throws IOException {
+        String key = findTenantKey(tenantId);
+        return getTenantByKey(key);
+    }
+    
+    // This results the tenant by the key as the tenant is prefixed in 
ConfiguartionAdmin, i.e. 'tenant1'
+    private TenantBean getTenantByKey(String key) throws IOException {
+        if (key != null) {
+            Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+            Dictionary properties = config.getProperties();
+            String id = properties.get(key + ".id").toString();
+            String name = properties.get(key + ".name").toString();
+            String hostname = properties.get(key + 
".properties.hostname").toString();
+            Map<String, String> dic = new HashMap<String, String>();
+            dic.put(Tenant.HOSTNAME_PROPERTY, hostname);
+    
+            return new TenantBean(id, name, hostname);
+        }
+        return null;
+    }
+
+    public boolean setTenant(String id, String name, String hostname) throws 
IOException {
+        boolean created = false;
+        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+        Dictionary properties = config.getProperties();
+        String tenantKey = findTenantKey(id);
+        if (tenantKey == null) {
+            int newid = findLastTenantKey() + 1;
+            tenantKey = "tenant" + newid;
+            properties.put(tenantKey + ".id", id);
+            created = true;
+        }
+        properties.put(tenantKey + ".name", name);
+        properties.put(tenantKey + ".properties.hostname", hostname);
+        config.update(properties);
+        return created;
+    }
+    
+    public boolean deleteTenant(String tenantId) throws IOException {
+        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+        Dictionary properties = config.getProperties();
+        String tenantKey = findTenantKey(tenantId);
+        if (tenantKey != null) {
+            properties.remove(tenantKey + ".id");
+            properties.remove(tenantKey + ".name");
+            properties.remove(tenantKey + ".properties.hostname");
+           
+            
+            int removedId = 
Integer.parseInt(tenantKey.substring("tenant".length()));
+            int lastId = findLastTenantKey();
+            if (lastId > removedId) {
+                for (int i=removedId; i<lastId; i++) {
+                    properties.put("tenant" + i + ".id", 
properties.get("tenant" + (i+1) + ".id"));
+                    properties.put("tenant" + i + ".name", 
properties.get("tenant" + (i+1) + ".name"));
+                    properties.put("tenant" + i + ".properties.hostname", 
properties.get("tenant" + (i+1) + ".properties.hostname"));
+                }
+            }
+            
+            properties.remove("tenant" + lastId + ".id");
+            properties.remove("tenant" + lastId + ".name");
+            properties.remove("tenant" + lastId + ".properties.hostname");
+            
+            config.update(properties);
+            return true;
+        }
+        return false;
+    }    
+
+    private String findTenantKey(String tenantId) throws IOException {
+        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+        Dictionary properties = config.getProperties();
+        Enumeration keys = properties.keys();
+        while (keys.hasMoreElements()) {
+            String key = keys.nextElement().toString();
+            if (key.endsWith(".id")) {
+                if (tenantId.equals(properties.get(key))) { 
+                    return key.substring(0, key.indexOf(".id"));
+                }
+            }
+        }
+        return null;
+    }
+
+    private int findLastTenantKey() throws IOException {
+        int maxid = 1;
+        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
+        Dictionary properties = config.getProperties();
+        Enumeration keys = properties.keys();
+        while (keys.hasMoreElements()) {
+            String key = keys.nextElement().toString();
+            if (key.endsWith(".id")) {
+                String id = key.substring("tenant".length(), key.indexOf("."));
+                if (Integer.parseInt(id) > maxid) {
+                    maxid = Integer.parseInt(id);
+                }
+            }
+        }
+        return maxid;
+    }
+}

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
  (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantRESTServiceImpl.java
  Tue Nov 15 16:57:31 2011
@@ -15,19 +15,11 @@
  */
 package org.amdatu.opensocial.tenant.gadget.service;
 
-import static 
org.amdatu.opensocial.tenant.gadget.service.TenantMutationColumnFamilyProviderImpl.CF;
-import static 
org.amdatu.opensocial.tenant.gadget.service.TenantMutationColumnFamilyProviderImpl.*;
-
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Dictionary;
-import java.util.Enumeration;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.Consumes;
 import javax.ws.rs.DELETE;
 import javax.ws.rs.FormParam;
 import javax.ws.rs.GET;
@@ -38,22 +30,20 @@
 import javax.ws.rs.WebApplicationException;
 import javax.ws.rs.core.CacheControl;
 import javax.ws.rs.core.Context;
-import javax.ws.rs.core.HttpHeaders;
 import javax.ws.rs.core.MediaType;
 import javax.ws.rs.core.Response;
+import javax.ws.rs.core.Response.Status;
 
-import 
org.amdatu.cassandra.persistencemanager.hector.HectorCassandraPersistenceManager;
 import org.amdatu.core.tenant.Tenant;
-import org.amdatu.core.tenant.TenantManagementService;
 import org.amdatu.libraries.utilities.rest.AtomSyndicationLink;
 import org.amdatu.web.rest.jaxrs.RESTService;
-import org.osgi.service.cm.Configuration;
-import org.osgi.service.cm.ConfigurationAdmin;
 import org.osgi.service.log.LogService;
 
-@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
 @Path("tenants")
 public class TenantRESTServiceImpl implements RESTService {
+    // The base URL for this REST service
+    static String REST_URL = "/rest/tenants";
+
     // HTTP caching for this REST interface
     protected static CacheControl NO_CACHE_CONTROL;
     static {
@@ -63,25 +53,32 @@
 
     private volatile LogService m_logService;
     private volatile Tenant m_tenant;
-    private volatile TenantMutationDAO m_tenantDAO;
-    
-
+    private volatile TenantConfigDAO m_tenantDAO;
+    private volatile EMailService m_mailService;
 
     public void start() {
         m_logService.log(LogService.LOG_INFO, "Tenant management REST service 
started");
     }
 
+    /**
+     * Returns available tenants.
+     * Example: GET /rest/tenants
+     * 
+     * @param request The http servlet request
+     * @return JSON expression containing the list of tenants.
+     */
     @GET
     @Produces({ MediaType.APPLICATION_JSON })
-    public Response getTenants(@Context final HttpHeaders headers, @Context 
final HttpServletRequest request) {
+    public Response getTenants(@Context final HttpServletRequest request) {
         TenantsBean tenantsBean = new TenantsBean();
         try {
-            for (TenantBean tenant : getTenants()) {
-                String href = request.getContextPath() + "/rest/tenants/" + 
tenant.getId();
+            for (TenantBean tenant : m_tenantDAO.getTenants()) {
+                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())) {
                     // Only provide delete link if the tenant is not the same 
as the current tenant
-                    tenant.addLink(new 
AtomSyndicationLink().setHref(href).setRel("delete").setType("application/json"));
+                    tenant
+                        .addLink(new 
AtomSyndicationLink().setHref(href).setRel("delete").setType("application/json"));
                 }
                 tenantsBean.addTenant(tenant);
             }
@@ -90,117 +87,102 @@
             throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
         }
 
-        return Response.ok(tenantsBean, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
-                        .build();
+        return Response.ok(tenantsBean, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL).build();
     }
 
+    /**
+     * Returns the specified tenant.
+     * Example: GET /rest/tenants/default_tenant
+     * 
+     * @param request The http servlet request
+     * @return JSON expression containing the specified tenant.
+     */
     @GET
     @Path("/{id}")
     @Produces({ MediaType.APPLICATION_JSON })
-    public Response getTenant(@PathParam("id") final String id, @Context final 
HttpHeaders headers, @Context final HttpServletRequest request) {
-        TenantBean tenant = null;
+    public Response getTenant(@PathParam("id") final String id, @Context final 
HttpServletRequest request) {
         try {
-            String key = findTenantKey(id);
-            if (key != null) {
-                tenant = getTenant(key);
+            TenantBean tenant = m_tenantDAO.getTenant(id);
+            if (tenant != null) {
+                return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).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);
         }
-
-        if (tenant == null) {
-            return Response.noContent().cacheControl(NO_CACHE_CONTROL).build();
-        }
-
-        return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
-                        .build();
     }
 
-    
+    /**
+     * Creates a new or updates an existing tenant.
+     * Example: POST /rest/tenants/default_tenant with body parameters 
name='default_tenant_2' and hostame='amdatu.org'
+     * 
+     * @return JSON expression containing the specified tenant.
+     */
     @POST
+    @Consumes("application/x-www-form-urlencoded")
     @Path("/{id}")
-    public Response updateTenant(@PathParam("id") final String id, 
@FormParam("name") final String name, @FormParam("hostname") final String 
hostname) {
-        TenantBean tenant = null;
+    public Response setTenant(@PathParam("id") final String id, 
@FormParam("name") final String name,
+        @FormParam("hostname") final String hostname, @FormParam("email") 
final String email) {
         try {
-            Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
-            Dictionary properties = config.getProperties();
-            String tenantKey = findTenantKey(id);
-            if (tenantKey == null) {
-                int newid = findLastTenantKey() + 1;
-                tenantKey = "tenant" + newid;
-                properties.put(tenantKey + ".id", id);
-            }
-            properties.put(tenantKey + ".name", name);
-            properties.put(tenantKey + ".properties.hostname", hostname);
-            config.update(properties);
-            
-            m_tenantDAO.addUpdateMutation(id, name, hostname);
+            if (!validateEmail(email)) {
+                return 
Response.status(Status.BAD_REQUEST).cacheControl(NO_CACHE_CONTROL).build();
+            }
+            if (m_tenantDAO.setTenant(id, name, hostname)) {
+                // Create an account and send it to the specified email address
+                String subject = "A new tenant has been created";
+                String content = "A new tenant has been created wih the 
following properties : \r\n";
+                content += "Tenant id: " + id + "\r\n";
+                content += "Tenant name: " + name + "\r\n";
+                content += "Tenant hostname: " + hostname + "\r\n";
+                content += "\r\n";
+                content += "A default Administrator account has been created 
for you with the following credentials:\r\n";
+                content += "Username: admin\r\n";
+                content += "Password: amdatu\r\n";
+                content += "You will be asked to change your password the 
first time you login.\r\n";
+                
+                m_mailService.send(email, subject, content);
+            }
         }
         catch (Exception e) {
+            m_logService.log(LogService.LOG_ERROR, "An error occured.", e);
             throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
         }
 
-        return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
-                        .build();
+        return Response.ok().cacheControl(NO_CACHE_CONTROL).build();
+    }
+    
+    private boolean validateEmail(String email) {
+        if (email == null || email.isEmpty()) {
+            return true;
+        }
+        Pattern p = Pattern.compile(".+@.+\\.[a-z]+");
+        Matcher m = p.matcher(email);
+        return m.matches();
     }
 
+    /**
+     * Deletes an existing tenant.
+     * Example: DELETE /rest/tenants/default_tenant
+     */
     @DELETE
     @Path("/{id}")
     public Response deleteTenant(@PathParam("id") final String id) {
         TenantBean tenant = null;
         try {
-            Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
-            Dictionary properties = config.getProperties();
-            String tenantKey = findTenantKey(id);
-            if (tenantKey != null) {
-                properties.remove(tenantKey + ".id");
-                properties.remove(tenantKey + ".name");
-                properties.remove(tenantKey + ".properties.hostname");
-                config.update(properties);
+            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();
             }
-            
-            m_tenantDAO.addDeleteMutation(id);
         }
         catch (Exception e) {
             throw new WebApplicationException(e, 
Response.Status.INTERNAL_SERVER_ERROR);
         }
-
-        return Response.ok(tenant, 
MediaType.APPLICATION_JSON_TYPE).cacheControl(NO_CACHE_CONTROL)
-                        .build();
     }
-
-    private List<TenantBean> getTenants() throws IOException {
-        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
-        Dictionary properties = config.getProperties();
-        List<TenantBean> tenants = new ArrayList<TenantBean>();
-        int keyId = 1;
-        String key = "tenant" + keyId;
-        boolean exists = properties.get(key + ".id") != null;
-        while (exists) {
-            tenants.add(getTenant(key));
-            keyId++;
-            key = "tenant" + keyId;
-            exists = properties.get(key + ".id") != null;
-        }
-        
-        Collections.sort(tenants);
-        return tenants;
-    }
-
-    private TenantBean getTenant(String key) throws IOException {
-        Configuration config = 
m_configAdmin.getConfiguration(TenantManagementService.PID);
-        Dictionary properties = config.getProperties();
-        String id = properties.get(key + ".id").toString();
-        String name = properties.get(key + ".name").toString();
-        String hostname = properties.get(key + 
".properties.hostname").toString();
-        Map<String, String> dic = new HashMap<String, String>();
-        dic.put(Tenant.HOSTNAME_PROPERTY, hostname);
-
-        return new TenantBean(id, name, hostname);
-    }
-
-  
-    
-
 }

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
    (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/java/org/amdatu/opensocial/tenant/gadget/service/TenantsBean.java
    Tue Nov 15 16:57:31 2011
@@ -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.opensocial.tenant.gadget.service;
 
 import java.util.ArrayList;
@@ -8,6 +23,7 @@
 import javax.xml.bind.annotation.XmlElement;
 import javax.xml.bind.annotation.XmlRootElement;
 
+@SuppressWarnings("restriction")
 @XmlRootElement(name = "tenants")
 @XmlAccessorType(XmlAccessType.PUBLIC_MEMBER)
 public class TenantsBean {

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/resources/jsp/TenantGadget.jsp
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/resources/jsp/TenantGadget.jsp   
    (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/resources/jsp/TenantGadget.jsp   
    Tue Nov 15 16:57:31 2011
@@ -38,7 +38,6 @@
   </ModulePrefs>
   <Content type="html">
     <![CDATA[
-    <link rel="stylesheet" 
href="${contextPath}/dashboard/static/css/dashboard.css">
     <link rel="stylesheet" href="${gadgetBaseUrl}/static/css/tenant.css">
 
     <script type="text/javascript" 
src="${contextPath}/dashboard/static/js/lib/jquery-1.4.2.min.js"></script>
@@ -64,7 +63,9 @@
             <tr><td>__MSG_id__</td><td><input type="edit" id="tenant_id" 
disabled="disabled"/></td></tr>
             <tr><td>__MSG_name__</td><td><input type="edit" id="tenant_name" 
value=""/></td></tr>
             <tr><td>__MSG_hostname__</td><td><input type="edit" 
id="tenant_hostname" value=""/></td></tr>
+            <tr id="tenant_email_row"><td>__MSG_email__*</td><td><input 
type="edit" id="tenant_email" value=""/></td></tr>
           </table>
+          <div id="comment" class="comment" 
style="display:none;visibility:hidden">* __MSG_email_comment__</div>
           <input type="submit" id="tenant_save" value="__MSG_save__" 
onclick="javascript:saveTenant();"/>
           <input type="button" id="cancel" value="__MSG_cancel__" 
onclick="javascript:cancelEdit();"/>
       </fieldset>

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/css/tenant.css
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/css/tenant.css  
    (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/css/tenant.css  
    Tue Nov 15 16:57:31 2011
@@ -19,6 +19,28 @@
   background: #fff;
 }
 
+p {
+  font-family: arial, sans-serif;
+  font-size: 13px;
+}
+
+table th {
+  font-family: arial, sans-serif;
+  font-size: 13px;
+  font-style:bold;
+  halign: left;
+}
+
+table td {
+  font-family: arial, sans-serif;
+  font-size: 13px;
+}
+
+ul li {
+  font-family: arial, sans-serif;
+  font-size: 13px;
+}
+
 table td {
    max-width: 280px;
    _width: 280px;               /* IE */
@@ -69,12 +91,19 @@
 
 fieldset {
   border: 1px solid #d0ccc9;
+  font-size: 13px;
 }
 
 fieldset legend {
-  font-size: 0.8em;
+  font-size: 13px;
 }
 
 img.mouseover  {
   cursor:hand;
 }
+
+div.comment {
+  font-style:italic;
+  font-size: 13px;
+  margin-bottom:15px;
+}
\ No newline at end of file

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/js/tenant.js
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/js/tenant.js    
    (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/js/tenant.js    
    Tue Nov 15 16:57:31 2011
@@ -24,7 +24,8 @@
   params[gadgets.io.RequestParameters.METHOD] = gadgets.io.MethodType.POST;
   var name = document.getElementById('tenant_name').value;
   var hostname = document.getElementById('tenant_hostname').value;
-  var postdata = {name : name, hostname : hostname};
+  var email = document.getElementById('tenant_email').value;
+  var postdata = {name : name, hostname : hostname, email : email};
   params[gadgets.io.RequestParameters.POST_DATA] = 
gadgets.io.encodeValues(postdata);
   url = getBaseUrl() + addNoCache(unescape(url));
   gadgets.io.makeRequest(url, callback, params);
@@ -148,6 +149,9 @@
   loadTenant(escape(unescape(link)), onTenantLoaded);
   hide('new_tenant_button');
   hide('infobox');
+  hide('comment');
+  document.getElementById('tenant_email').value = "";
+  hide('tenant_email_row');
   document.getElementById('tenant_details_legend').innerHTML = 
updateTenantLabel;
   show('tenant_details');
 }
@@ -166,6 +170,9 @@
   document.getElementById('tenant_id').value = "";
   document.getElementById('tenant_name').value = "";
   document.getElementById('tenant_hostname').value = "";
+  document.getElementById('tenant_email').value = "";
+  show('comment');
   show('tenant_details');
+  show('tenant_email_row');
   gadgets.window.adjustHeight();
 }
\ No newline at end of file

Modified: 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/labels/tenantmgmt_ALL_ALL.xml
==============================================================================
--- 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/labels/tenantmgmt_ALL_ALL.xml
       (original)
+++ 
sandbox/ivol/tenant-management-gadget/src/main/resources/static/labels/tenantmgmt_ALL_ALL.xml
       Tue Nov 15 16:57:31 2011
@@ -21,6 +21,8 @@
   <msg name="id">Id</msg>
   <msg name="name">Name</msg>
   <msg name="hostname">Hostname</msg>
+  <msg name="email">Email address</msg>
+  <msg name="email_comment">An email will be send to this address with the 
generated admin credentials for this new tenant.</msg>
 
   <msg name="new_tenant">New tenant</msg>
   <msg name="update_tenant">Update tenant</msg>
_______________________________________________
Amdatu-commits mailing list
[email protected]
http://lists.amdatu.org/mailman/listinfo/amdatu-commits

Reply via email to