Join Message Service added

Project: http://git-wip-us.apache.org/repos/asf/incubator-wave/repo
Commit: http://git-wip-us.apache.org/repos/asf/incubator-wave/commit/0f7ee712
Tree: http://git-wip-us.apache.org/repos/asf/incubator-wave/tree/0f7ee712
Diff: http://git-wip-us.apache.org/repos/asf/incubator-wave/diff/0f7ee712

Branch: refs/heads/swellrt
Commit: 0f7ee71289967dbb3a770f915527f29efe3115b7
Parents: 635c8a7
Author: Antonio Tenorio Fornés <[email protected]>
Authored: Mon Sep 26 18:03:39 2016 +0200
Committer: Antonio Tenorio Fornés <[email protected]>
Committed: Mon Sep 26 18:03:39 2016 +0200

----------------------------------------------------------------------
 wave/config/email/EmailMessages.properties      |   3 +
 wave/config/email/EmailMessages_en.properties   |   3 +
 wave/config/email/EmailMessages_es.properties   |   5 +-
 wave/config/email/Join.vm                       |  25 +++
 wave/src/main/java/org/swellrt/api/SwellRT.java | 187 +++++++++++--------
 .../main/java/org/swellrt/api/WaveClient.java   |  28 ++-
 .../java/org/swellrt/api/js/WaveClientJS.java   |  16 ++
 .../server/box/servlet/JoinMessageService.java  | 155 +++++++++++++++
 .../server/box/servlet/SwellRtServlet.java      |  26 +--
 9 files changed, 357 insertions(+), 91 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/config/email/EmailMessages.properties
----------------------------------------------------------------------
diff --git a/wave/config/email/EmailMessages.properties 
b/wave/config/email/EmailMessages.properties
index cde80c4..118480d 100644
--- a/wave/config/email/EmailMessages.properties
+++ b/wave/config/email/EmailMessages.properties
@@ -1,5 +1,8 @@
 invitationEmailSubject = {0} wants to collaborate with you
 invitationHeader= {0} wants to collaborate with you
 invitationEmailBody= Hello {0},\n\n{1} wants to collaborate with you in <a 
href="{2}">{3}</a>.
+joinNamedEmailSubject = Welcome {0}, a new collaborator in {1}
+joinUnnamedEmailSubject = Welcome a new collaborator of {1}
+joinEmailBody= Hi {0},\n\n<a mailto="{1}">{2}</a> has joint <a 
href="{3}">{4}</a>:,\n\n<blockquote>{5}</blockquote>\n\n. <a 
mailto="{1}?subject=Wellcome to {4}&body=... We can keep collaborating at 
{3}">Welcome {2}!</a>
 restoreEmailSubject=Restore {0} password
 restoreEmailBody=Hello {0},\n\nTo restore your password, please visit the 
following link {1}. \n\nIf you did not request a password recovery, you can 
ignore this message.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/config/email/EmailMessages_en.properties
----------------------------------------------------------------------
diff --git a/wave/config/email/EmailMessages_en.properties 
b/wave/config/email/EmailMessages_en.properties
index cde80c4..118480d 100644
--- a/wave/config/email/EmailMessages_en.properties
+++ b/wave/config/email/EmailMessages_en.properties
@@ -1,5 +1,8 @@
 invitationEmailSubject = {0} wants to collaborate with you
 invitationHeader= {0} wants to collaborate with you
 invitationEmailBody= Hello {0},\n\n{1} wants to collaborate with you in <a 
href="{2}">{3}</a>.
+joinNamedEmailSubject = Welcome {0}, a new collaborator in {1}
+joinUnnamedEmailSubject = Welcome a new collaborator of {1}
+joinEmailBody= Hi {0},\n\n<a mailto="{1}">{2}</a> has joint <a 
href="{3}">{4}</a>:,\n\n<blockquote>{5}</blockquote>\n\n. <a 
mailto="{1}?subject=Wellcome to {4}&body=... We can keep collaborating at 
{3}">Welcome {2}!</a>
 restoreEmailSubject=Restore {0} password
 restoreEmailBody=Hello {0},\n\nTo restore your password, please visit the 
following link {1}. \n\nIf you did not request a password recovery, you can 
ignore this message.
\ No newline at end of file

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/config/email/EmailMessages_es.properties
----------------------------------------------------------------------
diff --git a/wave/config/email/EmailMessages_es.properties 
b/wave/config/email/EmailMessages_es.properties
index 6f77dc8..808e7de 100644
--- a/wave/config/email/EmailMessages_es.properties
+++ b/wave/config/email/EmailMessages_es.properties
@@ -1,5 +1,8 @@
 invitationEmailSubject = {0} quiere colaborar contigo
 invitationHeader= {0} quiere colaborar contigo
 invitationEmailBody= Hola {0},\n\n{1} quiere colaborar contigo en <a 
href="{2}">{3}</a>.
+joinNamedEmailSubject = Dale la bienvenida a {0}, un nuevo colaborador de {1}
+joinUnnamedEmailSubject = Dale la bienvenida a un nuevo colaborador de {1}
+joinEmailBody= Hola {0},\n\n<a mailto="{1}">{2}</a> se ha unido a <a 
href="{3}">{4}</a>:,\n\n<blockquote>{5}</blockquote>\n\n. <a 
mailto="{1}?subject=Bienvenido a {4}&body=... Podemos seguir colaborando en 
{3}">�Dale la bienvenida a {2}!</a>
 restoreEmailSubject=Recuperaci�n de contrase�a para {0}
-restoreEmailBody=Hola {0},\n\nPara recuperar tu contrase�a, por favor, 
visita este enlace: {1}. \n\nSi no has pedido una recuperaci�n de 
contrase�a, puedes ignorar este mensaje.
\ No newline at end of file
+restoreEmailBody=Hola {0},\n\nPara recuperar tu contrase�a, por favor, 
visita este enlace: {1}. \n\nSi no has pedido una recuperaci�n de 
contrase�a, puedes ignorar este mensaje.

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/config/email/Join.vm
----------------------------------------------------------------------
diff --git a/wave/config/email/Join.vm b/wave/config/email/Join.vm
new file mode 100644
index 0000000..2cfa8db
--- /dev/null
+++ b/wave/config/email/Join.vm
@@ -0,0 +1,25 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd";>
+<html xmlns="http://www.w3.org/1999/xhtml";>
+ <head>
+  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
+</head>
+ <body>
+   <h1>SwellRT</h1>
+   <table align="center" cellpadding="0" cellspacing="0" width="600">
+     <tr>
+      <td style="color: #20686e; font-size: 20px; font-family: Helvetica, 
Arial, sans-serif; padding: 10px 10px 10px 10px;">
+       $text.joinUnnamedEmailSubject.insert($joiner)
+      </td>
+     </tr>
+     <tr>
+      <td style="padding: 15px 30px 15px 30px; font-size: 15px">
+
+       <p style="margin: 0 0 9px">
+        $text.joinEmailBody.insert($admin, $joiner, $joinerEmail, $url, 
$url_text, $message)
+       </p>
+      </td>
+     </tr>
+    </table>
+  </body>
+</html>

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/src/main/java/org/swellrt/api/SwellRT.java
----------------------------------------------------------------------
diff --git a/wave/src/main/java/org/swellrt/api/SwellRT.java 
b/wave/src/main/java/org/swellrt/api/SwellRT.java
index 798d42f..3d4376e 100644
--- a/wave/src/main/java/org/swellrt/api/SwellRT.java
+++ b/wave/src/main/java/org/swellrt/api/SwellRT.java
@@ -142,10 +142,10 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
   /** List of living waves for the active session. */
   private Map<WaveId, WaveLoader> waveRegistry = CollectionUtils.newHashMap();
-  
+
   /** List of living collab objects with waves as substrate  */
   private Map<WaveId, ModelJS> objectRegistry = CollectionUtils.newHashMap();
-  
+
   /** List of editors created in the app */
   private Map<Element, TextEditor> editorRegistry = 
CollectionUtils.newHashMap();
 
@@ -153,7 +153,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
   private SwellRT.Listener listener = null;
 
   private boolean useWebSocket = true;
-  
+
   private boolean shouldOpenWebsocket = true;
 
 
@@ -197,12 +197,12 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       _callback = ServiceCallback.getVoidCallback();
 
     final ServiceCallback callback = _callback;
-    
+
     JsoView jsParameters = JsoView.as(parameters);
     String participantId = null;
-    if (jsParameters != null) 
+    if (jsParameters != null)
       participantId = jsParameters.getString("id");
-    
+
     String url = baseServerUrl + "/swell/auth/"+(participantId != null ? 
participantId : "");
 
     RequestBuilder builder = 
SwellRTUtils.newRequestBuilder(RequestBuilder.POST, url);
@@ -229,7 +229,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
           sessionId = responseData.getValue("sessionId");
           waveDomain = responseData.getValue("domain");
           seed = SwellRTUtils.nextBase64(10);
-          
+
           BrowserSession.setUserData(loggedInUser.getDomain(), 
loggedInUser.getAddress(), seed,
                   sessionId);
 
@@ -252,7 +252,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
   public void resume(JavaScriptObject parameters, ServiceCallback _callback)
       throws RequestException {
-    
+
     if (_callback == null)
       _callback = ServiceCallback.getVoidCallback();
 
@@ -260,9 +260,9 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
     JsoView jsParameters = JsoView.as(parameters);
     String participantId = null;
-    if (jsParameters != null) 
+    if (jsParameters != null)
       participantId = jsParameters.getString("id");
- 
+
     String url = baseServerUrl + "/swell/auth/"+(participantId != null ? 
participantId : "");
     url = BrowserSession.addSessionToUrl(url);
 
@@ -318,7 +318,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       _callback = ServiceCallback.getVoidCallback();
 
     final ServiceCallback callback = _callback;
-    
+
     //
     // Clean session, websocket ,objects and registries
     //
@@ -329,7 +329,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
         if (!editor.isClean())
           editor.cleanUp();
       editorRegistry.clear();
-      
+
       for (ModelJS co : objectRegistry.values())
         SwellRTUtils.deleteJsObject(co);
       objectRegistry.clear();
@@ -347,11 +347,11 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       //
       // Call server to close remote session
       //
-      
-      JsoView jsParameters = JsoView.as(parameters);    
+
+      JsoView jsParameters = JsoView.as(parameters);
       String participantId = null;
       if (jsParameters != null)
-       participantId = jsParameters.getString("id");    
+       participantId = jsParameters.getString("id");
 
       String url = baseServerUrl + "/swell/auth/"+ (participantId != null ? 
participantId : "");
       url = BrowserSession.addSessionToUrl(url);
@@ -379,8 +379,8 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       });
 
     } catch (RuntimeException e) {
-      
-      // TODO 
+
+      // TODO
 
     } finally {
 
@@ -388,10 +388,10 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
     }
 
   }
-  
+
   protected void openWebsocket(final Callback<Void, Void> callback) {
     Preconditions.checkArgument(loggedInUser != null, "User not logged in. 
Can't open websocket.");
-    
+
     // this is needed to atmosphere to work
     setWebsocketAddress(baseServerUrl);
 
@@ -411,12 +411,12 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
         callback.onFailure((Void) null);
 
       }
-    });    
-    
+    });
+
   }
-  
+
   private void openProc(WaveId waveId, final Callback<WaveLoader, String> 
callback) {
-    
+
      final WaveLoader wave =
           new WaveLoader(WaveRef.of(waveId), channel, TypeIdGenerator.get()
               .getUnderlyingGenerator(), waveDomain, 
Collections.<ParticipantId> emptySet(),
@@ -425,52 +425,52 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
     if (wave.isLoaded()) {
       callback.onSuccess(wave);
     } else {
-      
+
       try {
-              
+
         wave.load(new Command() {
           @Override
           public void execute() {
             callback.onSuccess(wave);
           }
         });
-  
+
         } catch(RuntimeException e) {
             callback.onFailure(e.getMessage());
         }
     }
 
-    
+
   }
-  
+
   /**
-   * Open or create a collaborative object. 
+   * Open or create a collaborative object.
    * The underlying websocket will be openend if it is necessary.
-   * 
-   * @param parameters field "id" for collab object id or void to create a new 
one 
+   *
+   * @param parameters field "id" for collab object id or void to create a new 
one
    * @param callback
    * @throws RequestException
    */
   public void open(JavaScriptObject parameters, ServiceCallback _callback) 
throws RequestException {
-    
+
     if (_callback == null)
       _callback = ServiceCallback.getVoidCallback();
 
     final ServiceCallback callback = _callback;
-    
+
     Preconditions.checkArgument(loggedInUser != null, "Login is not present");
-    
+
     JsoView p = JsoView.as(parameters);
-   
+
     WaveId id = null;
     if (p.getString("id") != null) {
       id = WaveId.deserialise(p.getString("id"));
     } else {
       id = TypeIdGenerator.get().newWaveId();
     }
-    
+
     final WaveId waveId = id;
-   
+
     final Callback<WaveLoader, String> openProcCallback = new  
Callback<WaveLoader, String>() {
 
       @Override
@@ -480,9 +480,9 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
       @Override
       public void onSuccess(WaveLoader wave) {
-        
+
         waveRegistry.put(waveId, wave);
-        
+
         ModelJS cobJsFacade = null;
 
         Model cob =
@@ -492,30 +492,30 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
           cobJsFacade = ModelJS.create(cob);
           cob.addListener(cobJsFacade);
-          
+
           objectRegistry.put(waveId, cobJsFacade);
-          
+
           
callback.onComplete(ServiceCallback.JavaScriptResponse.success(cobJsFacade));
       }
-      
+
     };
-    
-    if (waveRegistry.containsKey(waveId)) {    
+
+    if (waveRegistry.containsKey(waveId)) {
       ModelJS cobJsFacade = objectRegistry.get(waveId);
-      
+
       if (cobJsFacade != null)
         
callback.onComplete(ServiceCallback.JavaScriptResponse.success(cobJsFacade));
       else
         
callback.onComplete(ServiceCallback.JavaScriptResponse.error("SERVICE_EXCEPTION",
 "Object is open but no native facade found"));
-      
+
       return; // don't continue
     }
-    
-    
+
+
     if (shouldOpenWebsocket) {
       openWebsocket(new Callback<Void, Void>() {
-        
-        
+
+
         @Override
         public void onFailure(Void reason) {
           
callback.onComplete(ServiceCallback.JavaScriptResponse.error("WEBSOCKET_ERROR", 
"Websocket can't be open"));
@@ -523,70 +523,70 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
         @Override
         public void onSuccess(Void result) {
-          openProc(waveId, openProcCallback);          
+          openProc(waveId, openProcCallback);
         }
       });
     } else {
       openProc(waveId, openProcCallback);
     }
-    
+
   }
-  
+
   private native String extractWaveIdParameter(JavaScriptObject parameters) 
/*-{
-  
+
     if (parameters == null || parameters === undefined)
       return null;
-  
+
     if (typeof parameters == "string")
       return parameters;
-      
+
     if (parameters.id && typeof parameters.id == "function")
        return parameters.id();
-    
+
     if (parameters.id && typeof parameters.id == "string")
        return parameters.id;
-       
+
     return null;
   }-*/;
 
-  
+
   public void close(JavaScriptObject parameters, ServiceCallback callback) 
throws RequestException {
-    
+
     if (callback == null)
       callback = ServiceCallback.getVoidCallback();
-    
+
     String id = extractWaveIdParameter(parameters);
     Preconditions.checkArgument(id != null, "Missing object or id");
     WaveId waveId = WaveId.deserialise(id);
-    
+
     if (!waveRegistry.containsKey(waveId)) {
       return;
     }
-    
+
     for (TextEditor e: editorRegistry.values())
-      if (!e.isClean()) 
+      if (!e.isClean())
         if (e.getWaveId().equals(waveId))
           e.cleanUp();
 
     ModelJS co = objectRegistry.get(waveId);
     objectRegistry.remove(waveId);
-    SwellRTUtils.deleteJsObject(co);   
-    
+    SwellRTUtils.deleteJsObject(co);
+
     waveRegistry.remove(waveId).destroy();
   }
 
-  
+
   public TextEditor createTextEditor(Element parent, 
StringMap<JsoWidgetController> widgetControllers, 
StringMap<JsoAnnotationController> annotationControllers) {
-            
+
     TextEditor textEditor = TextEditor.create(parent,
         widgetControllers,
         annotationControllers);
-   
+
     editorRegistry.put(parent, textEditor);
-    
+
     return textEditor;
   }
-  
+
   //
   // 
*******************************************************************************
   //
@@ -1433,7 +1433,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       _callback = ServiceCallback.getVoidCallback();
 
     final ServiceCallback callback = _callback;
-    
+
     String url = baseServerUrl + "/swell/account/" + loggedInUser.getName();
     url = BrowserSession.addSessionToUrl(url);
 
@@ -1464,7 +1464,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
   public void getUserProfile(ServiceCallback _callback)
       throws RequestException {
-    
+
     if (_callback == null)
       _callback = ServiceCallback.getVoidCallback();
 
@@ -1502,7 +1502,7 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
       _callback = ServiceCallback.getVoidCallback();
 
     final ServiceCallback callback = _callback;
-    
+
     String url = baseServerUrl + "/swell/account/";
     url = BrowserSession.addSessionToUrl(url);
 
@@ -1578,4 +1578,43 @@ public class SwellRT implements EntryPoint, 
UnsavedDataListener {
 
     }
   }
+
+  public void join(String email, String inviteUrl, String urlText, String 
message, String admin,
+    final Callback<String, String> callback)
+    throws RequestException {
+
+    String baseUrl = baseServerUrl + "/swell/join/";
+    baseUrl = BrowserSession.addSessionToUrl(baseUrl);
+
+    String query = "id-or-email=" + URL.encodeQueryString(email);
+    query += "&url=" + URL.encodeQueryString(inviteUrl);
+    query += "&url_text=" + URL.encodeQueryString(urlText);
+    query += "&message=" + URL.encodeQueryString(message);
+    query += "&admin=" + URL.encodeQueryString(admin);
+    String url = baseUrl + "?" + query;
+
+    RequestBuilder builder = 
SwellRTUtils.newRequestBuilder(RequestBuilder.POST, url);
+
+    builder.sendRequest(null, new RequestCallback() {
+
+      @Override
+      public void onResponseReceived(Request request, Response response) {
+
+        if (response.getStatusCode() != 200)
+          callback.onFailure("SERVICE_EXCEPTION " + response.getText());
+        else
+          callback.onSuccess(response.getText());
+      }
+
+      @Override
+      public void onError(Request request, Throwable exception) {
+        callback.onFailure("SERVICE_EXCEPTION " + exception.getMessage());
+
+      }
+
+    });
+
+
+  }
+
 }

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/src/main/java/org/swellrt/api/WaveClient.java
----------------------------------------------------------------------
diff --git a/wave/src/main/java/org/swellrt/api/WaveClient.java 
b/wave/src/main/java/org/swellrt/api/WaveClient.java
index c685fbe..8b53017 100644
--- a/wave/src/main/java/org/swellrt/api/WaveClient.java
+++ b/wave/src/main/java/org/swellrt/api/WaveClient.java
@@ -390,13 +390,13 @@ public class WaveClient implements SwellRT.Listener {
   public TextEditorJS getTextEditor(String elementId, JavaScriptObject 
widgets, JavaScriptObject annotations) {
     Element parent = Document.get().getElementById(elementId);
     Preconditions.checkArgument(parent != null, "Can't hook editor in a null 
element");
-    
+
     TextEditor textEditor = coreClient.createTextEditor(parent, 
JsoWidgetController.fromJso(widgets),
         JsoAnnotationController.fromJso(annotations));
-    
+
     TextEditorJS textEditorJS = TextEditorJS.create(textEditor, this);
     textEditor.initialize(textEditorJS);
-    
+
     return textEditorJS;
   }
 
@@ -519,6 +519,24 @@ public class WaveClient implements SwellRT.Listener {
     });
     };
 
+  public void join(String email, String url, String urlText, String message, 
String admin,
+      final JavaScriptObject callback)
+      throws RequestException {
+
+    coreClient.join(email, url, urlText, message, admin, new Callback<String, 
String>() {
+
+      @Override
+      public void onFailure(String reason) {
+        invoke(callback, WaveClientJS.FAILURE, reason);
+      }
+
+      @Override
+      public void onSuccess(String result) {
+        invoke(callback, WaveClientJS.SUCCESS);
+      }
+    });
+  };
+
   /**
    * Enable/disable WebSockets transport. Alternative protocol is long-polling.
    *
@@ -640,8 +658,8 @@ public class WaveClient implements SwellRT.Listener {
     } else if (e instanceof Throwable) {
 
     }
- 
-    
+
+
     return exceptionCode;
   }
 

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/src/main/java/org/swellrt/api/js/WaveClientJS.java
----------------------------------------------------------------------
diff --git a/wave/src/main/java/org/swellrt/api/js/WaveClientJS.java 
b/wave/src/main/java/org/swellrt/api/js/WaveClientJS.java
index 322cc48..92f3ecd 100644
--- a/wave/src/main/java/org/swellrt/api/js/WaveClientJS.java
+++ b/wave/src/main/java/org/swellrt/api/js/WaveClientJS.java
@@ -472,6 +472,22 @@ public class WaveClientJS extends JavaScriptObject {
          },
 
          //
+         // Join
+         //
+         join: function(email, url, urlText, message, admin, onSuccess, 
onFailure){
+           var callback = new Object();
+           callback.success = onSuccess;
+           callback.failure = onFailure;
+
+           try {
+             
[email protected]::join(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;Lcom/google/gwt/core/client/JavaScriptObject;)(email,
 url, urlText, message, admin, callback);
+           } catch (e) {
+             throw 
@org.swellrt.api.WaveClient::wrapJavaException(Ljava/lang/Object;)(e);
+           }
+         },
+
+
+         //
          // Utils
          //
 

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/src/main/java/org/swellrt/server/box/servlet/JoinMessageService.java
----------------------------------------------------------------------
diff --git 
a/wave/src/main/java/org/swellrt/server/box/servlet/JoinMessageService.java 
b/wave/src/main/java/org/swellrt/server/box/servlet/JoinMessageService.java
new file mode 100644
index 0000000..8514cee
--- /dev/null
+++ b/wave/src/main/java/org/swellrt/server/box/servlet/JoinMessageService.java
@@ -0,0 +1,155 @@
+package org.swellrt.server.box.servlet;
+
+import java.io.IOException;
+import java.text.MessageFormat;
+import java.util.HashMap;
+import java.util.Locale;
+import java.util.ResourceBundle;
+
+import javax.mail.MessagingException;
+import javax.mail.internet.AddressException;
+import javax.mail.internet.InternetAddress;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.servlet.http.HttpSession;
+
+import org.apache.velocity.Template;
+import org.apache.velocity.tools.ConversionUtils;
+import org.waveprotocol.box.server.account.AccountData;
+import org.waveprotocol.box.server.account.HumanAccountData;
+import org.waveprotocol.box.server.authentication.SessionManager;
+import org.waveprotocol.box.server.persistence.AccountStore;
+import org.waveprotocol.box.server.persistence.PersistenceException;
+import org.waveprotocol.wave.model.wave.ParticipantId;
+
+import com.google.inject.Inject;
+
+public class JoinMessageService extends BaseService {
+
+  private static final String ID_OR_EMAIL = "id-or-email";
+  private static final String ADMIN = "admin";
+  private static final String JOIN_MESSAGE_BUNDLE = "EmailMessages";
+  private static final String JOIN_MESSAGE_TEMPLATE = "Join.vm";
+  public static final String URL = "url";
+  public static final String URL_TEXT = "url_text";
+  public static final String MESSAGE = "message";
+  private final AccountStore accountStore;
+  private final EmailSender emailSender;
+  private DecoupledTemplates decTemplates;
+
+  @Inject
+  public JoinMessageService(SessionManager sessionManager, AccountStore 
accountStore,
+      EmailSender emailSender, DecoupledTemplates decTemplates) {
+    super(sessionManager);
+    this.accountStore = accountStore;
+    this.emailSender = emailSender;
+    this.decTemplates = decTemplates;
+  }
+
+  @Override
+  public void execute(HttpServletRequest req, HttpServletResponse response) 
throws IOException {
+
+    ParticipantId participantId = sessionManager.getLoggedInUser(req);
+
+    HttpSession session = sessionManager.getSession(req);
+    HumanAccountData hum = 
sessionManager.getLoggedInAccount(session).asHuman();
+
+    Locale locale;
+
+    if (hum != null && !hum.getId().isAnonymous()) {
+
+      if (hum.getLocale() != null) {
+
+        locale = ConversionUtils.toLocale(hum.getLocale());
+
+      }
+
+      locale = Locale.getDefault();
+
+    } else {
+
+      locale = Locale.getDefault();
+
+    }
+
+    String url = req.getParameter(URL);
+
+    String urlText = req.getParameter(URL_TEXT);
+
+    HashMap<String, Object> params = new HashMap<String, Object>();
+
+    String idOrEmail = req.getParameter(ID_OR_EMAIL);
+
+    String admin = req.getParameter(ADMIN);
+
+    String message = req.getParameter(MESSAGE);
+
+    String joinerEmail = idOrEmail;
+
+    String joinerNickOrEmail = idOrEmail;
+
+    String adminNick = null;
+
+    String adminEmail = null;
+
+
+    // Get admin email information
+    try {
+      AccountData acc = accountStore.getAccount(new ParticipantId(admin));
+      if (acc != null && !acc.getId().isAnonymous()) {
+        adminEmail = acc.asHuman().getEmail();
+        adminNick = acc.getId().getName();
+      }
+    } catch (PersistenceException e) {
+      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+    }
+
+    // Get joiner information if it is an user
+    try {
+      AccountData acc = accountStore.getAccount(new ParticipantId(idOrEmail));
+      if (acc != null && !acc.getId().isAnonymous()) {
+        joinerEmail = acc.asHuman().getEmail();
+        joinerNickOrEmail = acc.getId().getName();
+      }
+    } catch (PersistenceException e) {
+      response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
+    }
+
+
+    params.put("admin", adminNick);
+    params.put("joiner", joinerNickOrEmail);
+    params.put("joinerEmail", joinerEmail);
+    params.put("url", url);
+    params.put("url_text", urlText);
+    params.put("message", message);
+
+    try {
+
+      Template t = decTemplates.getTemplateFromName(JOIN_MESSAGE_TEMPLATE);
+      ResourceBundle b = decTemplates.getBundleFromName(JOIN_MESSAGE_BUNDLE, 
locale);
+
+      String subject;
+
+      if (participantId != null){
+        String inviter = participantId.getAddress().split("@")[0];
+        subject = MessageFormat.format(b.getString("joinNamedEmailSubject"), 
inviter, urlText);
+      } else {
+        subject = MessageFormat.format(b.getString("unnamedEmailSubject"), 
urlText);
+      }
+
+
+      String body = decTemplates.getTemplateMessage(t, JOIN_MESSAGE_BUNDLE, 
params, locale);
+
+      emailSender.send(new InternetAddress(adminEmail), subject, body);
+
+    } catch (AddressException e) {
+        // TODO Auto-generated catch block
+      e.printStackTrace();
+    } catch (MessagingException e) {
+        // TODO Auto-generated catch block
+      e.printStackTrace();
+      }
+    }
+
+
+}

http://git-wip-us.apache.org/repos/asf/incubator-wave/blob/0f7ee712/wave/src/main/java/org/swellrt/server/box/servlet/SwellRtServlet.java
----------------------------------------------------------------------
diff --git 
a/wave/src/main/java/org/swellrt/server/box/servlet/SwellRtServlet.java 
b/wave/src/main/java/org/swellrt/server/box/servlet/SwellRtServlet.java
index 72100c8..3090916 100644
--- a/wave/src/main/java/org/swellrt/server/box/servlet/SwellRtServlet.java
+++ b/wave/src/main/java/org/swellrt/server/box/servlet/SwellRtServlet.java
@@ -1,12 +1,5 @@
 package org.swellrt.server.box.servlet;
 
-import com.google.inject.Injector;
-
-import org.waveprotocol.box.server.authentication.SessionManager;
-import org.waveprotocol.box.server.persistence.mongodb.MongoDbProvider;
-import org.waveprotocol.box.server.waveserver.WaveletProvider;
-import org.waveprotocol.wave.util.logging.Log;
-
 import java.io.IOException;
 
 import javax.inject.Inject;
@@ -15,6 +8,13 @@ import javax.servlet.http.HttpServlet;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 
+import org.waveprotocol.box.server.authentication.SessionManager;
+import org.waveprotocol.box.server.persistence.mongodb.MongoDbProvider;
+import org.waveprotocol.box.server.waveserver.WaveletProvider;
+import org.waveprotocol.wave.util.logging.Log;
+
+import com.google.inject.Injector;
+
 /**
  * A Servlet providing SwellRT REST operations on /swell context
  *
@@ -137,6 +137,10 @@ public class SwellRtServlet extends HttpServlet {
 
       injector.getInstance(InviteService.class).execute(req, response);
 
+    } else if (entity.equals("join")) {
+
+      injector.getInstance(JoinMessageService.class).execute(req, response);
+
     } else if (entity.equals("object")) {
 
         injector.getInstance(ObjectApiService.class).execute(req, response);
@@ -149,13 +153,13 @@ public class SwellRtServlet extends HttpServlet {
     }
 
   }
-  
+
   @Override
   protected void doDelete(HttpServletRequest req, HttpServletResponse 
response) throws IOException {
-    
+
     String[] pathTokens = getCleanPathInfo(req).split("/");
     String entity = pathTokens[1];
-    
+
     if (entity.equals("auth")) {
 
       injector.getInstance(AuthenticationService.class).execute(req, response);
@@ -166,6 +170,6 @@ public class SwellRtServlet extends HttpServlet {
       return;
 
     }
-    
+
   }
 }

Reply via email to