Author: yurize
Date: Sat Jan  7 09:46:06 2012
New Revision: 1228584

URL: http://svn.apache.org/viewvc?rev=1228584&view=rev
Log:
Implements WAVE-313: registration disabling. By [email protected]

Added:
    
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/
    
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/RegistrationRobot.java
Modified:
    incubator/wave/trunk/server-config.xml
    incubator/wave/trunk/server.config.example
    incubator/wave/trunk/src/org/waveprotocol/box/server/CoreSettings.java
    incubator/wave/trunk/src/org/waveprotocol/box/server/ServerMain.java
    
incubator/wave/trunk/src/org/waveprotocol/box/server/gxp/UserRegistrationPage.gxp
    
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/RobotAgentUtil.java
    
incubator/wave/trunk/src/org/waveprotocol/box/server/rpc/UserRegistrationServlet.java
    
incubator/wave/trunk/test/org/waveprotocol/box/server/rpc/UserRegistrationServletTest.java

Modified: incubator/wave/trunk/server-config.xml
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/server-config.xml?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- incubator/wave/trunk/server-config.xml (original)
+++ incubator/wave/trunk/server-config.xml Sat Jan  7 09:46:06 2012
@@ -22,6 +22,7 @@
   <property name="listener_executor_thread_count" value="1" />
   <property name="wavelet_load_executor_thread_count" value="2" />
   <property name="delta_persist_executor_thread_count" value="2" />
+  <property name="disable_registration" value="false" />
 
 
   <!-- Properties for server.federation.config -->
@@ -83,6 +84,7 @@
           <token key="LISTENER_EXECUTOR_THREAD_COUNT" 
value="${listener_executor_thread_count}" />
           <token key="WAVELET_LOAD_EXECUTOR_THREAD_COUNT" 
value="${wavelet_load_executor_thread_count}" />
           <token key="DELTA_PERSIST_EXECUTOR_THREAD_COUNT" 
value="${delta_persist_executor_thread_count}" />
+          <token key="DISABLE_REGISTRATION" value="${disable_registration}" />
         </replacetokens>
       </filterchain>
     </copy>
@@ -117,4 +119,4 @@
       </filterchain>
     </copy>
   </target>
-</project>
\ No newline at end of file
+</project>

Modified: incubator/wave/trunk/server.config.example
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/server.config.example?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- incubator/wave/trunk/server.config.example (original)
+++ incubator/wave/trunk/server.config.example Sat Jan  7 09:46:06 2012
@@ -109,3 +109,8 @@ waveserver_disable_verification = true
 
 # Set true to disable the verification of signers (certificates)
 waveserver_disable_signer_verification = true
+
+# Set true to prevent anyone registering on your server.
+# When true, only the admin user can use the RegistrationRobot to add new 
accounts
+# Default value: false
+disable_registration = @DISABLE_REGISTRATION@

Modified: incubator/wave/trunk/src/org/waveprotocol/box/server/CoreSettings.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/CoreSettings.java?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- incubator/wave/trunk/src/org/waveprotocol/box/server/CoreSettings.java 
(original)
+++ incubator/wave/trunk/src/org/waveprotocol/box/server/CoreSettings.java Sat 
Jan  7 09:46:06 2012
@@ -49,10 +49,11 @@ public class CoreSettings {
   public static final String GADGET_SERVER_PORT = "gadget_server_port";
   public static final String GADGET_SERVER_PATH = "gadget_server_path";
   public static final String ADMIN_USER = "admin_user";
-  public static final String  WELCOME_WAVE_ID = "welcome_wave_id";
+  public static final String WELCOME_WAVE_ID = "welcome_wave_id";
   public static final String LISTENER_EXECUTOR_THREAD_COUNT = 
"listener_executor_thread_count";
   public static final String WAVELET_LOAD_EXECUTOR_THREAD_COUNT = 
"wavelet_load_executor_thread_count";
   public static final String DELTA_PERSIST_EXECUTOR_THREAD_COUNT = 
"delta_persist_executor_thread_count";
+  public static final String DISABLE_REGISTRATION = "disable_registration";
 
   @Setting(name = WAVE_SERVER_DOMAIN)
   private static String waveServerDomain;
@@ -169,4 +170,9 @@ public class CoreSettings {
       description = "The number of threads to persist deltas.",
       defaultValue = "2")
   private static int deltaPersistExecutorThreadCount;
+
+
+  @Setting(name = DISABLE_REGISTRATION,
+      description = "Prevents the register page from being available to 
anyone", defaultValue = "false")
+  private static boolean disableRegistration;
 }

Modified: incubator/wave/trunk/src/org/waveprotocol/box/server/ServerMain.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/ServerMain.java?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- incubator/wave/trunk/src/org/waveprotocol/box/server/ServerMain.java 
(original)
+++ incubator/wave/trunk/src/org/waveprotocol/box/server/ServerMain.java Sat 
Jan  7 09:46:06 2012
@@ -45,6 +45,7 @@ import org.waveprotocol.box.server.robot
 import org.waveprotocol.box.server.robots.active.ActiveApiServlet;
 import org.waveprotocol.box.server.robots.agent.passwd.PasswordAdminRobot;
 import org.waveprotocol.box.server.robots.agent.passwd.PasswordRobot;
+import org.waveprotocol.box.server.robots.agent.registration.RegistrationRobot;
 import org.waveprotocol.box.server.robots.agent.welcome.WelcomeRobot;
 import org.waveprotocol.box.server.robots.dataapi.DataApiOAuthServlet;
 import org.waveprotocol.box.server.robots.dataapi.DataApiServlet;
@@ -215,6 +216,7 @@ public class ServerMain {
     server.addServlet(SessionManager.SIGN_IN_URL, AuthenticationServlet.class);
     server.addServlet("/auth/signout", SignOutServlet.class);
     server.addServlet("/auth/register", UserRegistrationServlet.class);
+
     server.addServlet("/fetch/*", FetchServlet.class);
     server.addServlet("/search/*", SearchServlet.class);
 
@@ -248,6 +250,7 @@ public class ServerMain {
     server.addServlet(PasswordRobot.ROBOT_URI + "/*", PasswordRobot.class);
     server.addServlet(PasswordAdminRobot.ROBOT_URI + "/*", 
PasswordAdminRobot.class);
     server.addServlet(WelcomeRobot.ROBOT_URI + "/*", WelcomeRobot.class);
+    server.addServlet(RegistrationRobot.ROBOT_URI + "/*", 
RegistrationRobot.class);
   }
 
   private static void initializeFrontend(Injector injector, ServerRpcProvider 
server,

Modified: 
incubator/wave/trunk/src/org/waveprotocol/box/server/gxp/UserRegistrationPage.gxp
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/gxp/UserRegistrationPage.gxp?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- 
incubator/wave/trunk/src/org/waveprotocol/box/server/gxp/UserRegistrationPage.gxp
 (original)
+++ 
incubator/wave/trunk/src/org/waveprotocol/box/server/gxp/UserRegistrationPage.gxp
 Sat Jan  7 09:46:06 2012
@@ -12,6 +12,7 @@
   <gxp:param name='domain' type='String' />
   <gxp:param name='message' type='String' />
   <gxp:param name='responseType' type='String' />
+  <gxp:param name='disableRegistration' type='Boolean' />
 
 
   <html dir="ltr">
@@ -52,6 +53,10 @@
     </tr>
     <tr>
       <td id="wiab_loginbox_td" valign="top" align="center">
+      <gxp:if cond='disableRegistration == true'>
+      Registration disabled by administrator.
+      </gxp:if>
+      <gxp:if cond='disableRegistration == false'>
       <form id="regForm" name="regForm" method="post" action="">
       <table align="left">
         <tr>
@@ -102,6 +107,7 @@
         </tr>
       </table>
       </form>
+      </gxp:if>
       </td>
     </tr>
   </table>

Modified: 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/RobotAgentUtil.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/RobotAgentUtil.java?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/RobotAgentUtil.java
 (original)
+++ 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/RobotAgentUtil.java
 Sat Jan  7 09:46:06 2012
@@ -1,87 +1,107 @@
-/**
- * Copyright 2011 Google Inc.
- *
- * 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.waveprotocol.box.server.robots.agent;
-
-import com.google.wave.api.Blip;
-
-import org.waveprotocol.box.server.account.HumanAccountDataImpl;
-import org.waveprotocol.box.server.authentication.PasswordDigest;
-import org.waveprotocol.box.server.persistence.AccountStore;
-import org.waveprotocol.box.server.persistence.PersistenceException;
-import org.waveprotocol.wave.model.wave.ParticipantId;
-
-import javax.annotation.Nullable;
-
-/**
- * Util methods for the robot agents.
- * 
- * @author [email protected] (Yuri Zelikov)
- */
-public class RobotAgentUtil {
-  
-  public static final String CANNOT_CHANGE_PASSWORD_FOR_USER = "Cannot change 
password for user: ";
-
-  private RobotAgentUtil() {
-
-  }
-
-  /**
-   * Appends a message followed by a new line to the end of the blip.
-   * 
-   * @param blip the blip.
-   * @param msg the message.
-   */
-  public static void appendLine(Blip blip, String msg) {
-    blip.at(blip.getContent().length()).insert(msg + "\n");
-  }
-
-  /**
-   * Returns the last line of the content if it ends with "\n" or null
-   * otherwise.
-   */
-  public static String lastEnteredLineOf(@Nullable String blipContent) {
-    if (blipContent == null || blipContent.isEmpty() || 
!blipContent.endsWith("\n")) {
-      return null;
-    }
-    blipContent = blipContent.trim();
-    String[] split = blipContent.split("\n");
-    return split[split.length - 1];
-  }
-  
-  /**
-   * Changes the user password.
-   * 
-   * @param newPassword the new password of the user.
-   * @param participantId the user wave address.
-   * @param accountStore the account store with user accounts.
-   * @throws PersistenceException if the persistence layer fails.
-   * @throws IllegalArgumentException if the user doesn't exist.
-   */
-  public static void changeUserPassword(String newPassword, ParticipantId 
participantId,
-      AccountStore accountStore) throws PersistenceException, 
IllegalArgumentException {
-    PasswordDigest newPasswordDigest = new 
PasswordDigest(newPassword.toCharArray());
-    HumanAccountDataImpl account = new HumanAccountDataImpl(participantId, 
newPasswordDigest);
-    if (accountStore.getAccount(participantId) != null) {
-      accountStore.removeAccount(participantId);
-      accountStore.putAccount(account);
-    } else {
-      throw new IllegalArgumentException(String.format("User %s does not exist 
on this domain.",
-          participantId.getAddress()));
-    }
-  }
-}
+/**
+ * Copyright 2011 Google Inc.
+ *
+ * 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.waveprotocol.box.server.robots.agent;
+
+import com.google.wave.api.Blip;
+
+import org.waveprotocol.box.server.account.HumanAccountDataImpl;
+import org.waveprotocol.box.server.authentication.PasswordDigest;
+import org.waveprotocol.box.server.persistence.AccountStore;
+import org.waveprotocol.box.server.persistence.PersistenceException;
+import org.waveprotocol.wave.model.wave.ParticipantId;
+
+import javax.annotation.Nullable;
+
+/**
+ * Util methods for the robot agents.
+ *
+ * @author [email protected] (Yuri Zelikov)
+ */
+public class RobotAgentUtil {
+
+  public static final String CANNOT_CHANGE_PASSWORD_FOR_USER = "Cannot change 
password for user: ";
+  public static final String CANNOT_CREATE_USER = "Cannot create user: ";
+
+  private RobotAgentUtil() {
+
+  }
+
+  /**
+   * Appends a message followed by a new line to the end of the blip.
+   *
+   * @param blip the blip.
+   * @param msg the message.
+   */
+  public static void appendLine(Blip blip, String msg) {
+    blip.at(blip.getContent().length()).insert(msg + "\n");
+  }
+
+  /**
+   * Returns the last line of the content if it ends with "\n" or null
+   * otherwise.
+   */
+  public static String lastEnteredLineOf(@Nullable String blipContent) {
+    if (blipContent == null || blipContent.isEmpty() || 
!blipContent.endsWith("\n")) {
+      return null;
+    }
+    blipContent = blipContent.trim();
+    String[] split = blipContent.split("\n");
+    return split[split.length - 1];
+  }
+
+  /**
+   * Changes the user password.
+   *
+   * @param newPassword the new password of the user.
+   * @param participantId the user wave address.
+   * @param accountStore the account store with user accounts.
+   * @throws PersistenceException if the persistence layer fails.
+   * @throws IllegalArgumentException if the user doesn't exist.
+   */
+  public static void changeUserPassword(String newPassword, ParticipantId 
participantId,
+      AccountStore accountStore) throws PersistenceException, 
IllegalArgumentException {
+    PasswordDigest newPasswordDigest = new 
PasswordDigest(newPassword.toCharArray());
+    HumanAccountDataImpl account = new HumanAccountDataImpl(participantId, 
newPasswordDigest);
+    if (accountStore.getAccount(participantId) != null) {
+      accountStore.removeAccount(participantId);
+      accountStore.putAccount(account);
+    } else {
+      throw new IllegalArgumentException(String.format("User %s does not exist 
on this domain.",
+          participantId.getAddress()));
+    }
+  }
+
+  /**
+   * Creates a new user.
+   *
+   * @param accountStore the account store with user accounts.
+   * @param participantId requested user wave address.
+   * @param password requested user password
+   * @throws PersistenceException if the persistence layer fails.
+   * @throws IllegalArgumentException if the userId is already in use.
+   */
+  public static void createUser(AccountStore accountStore, ParticipantId 
participantId, String password)
+    throws PersistenceException, IllegalArgumentException {
+    if (accountStore.getAccount(participantId) != null) {
+      throw new IllegalArgumentException(String.format("User %s already exists 
on this domain.", participantId.getAddress()));
+    }
+
+    HumanAccountDataImpl account = new HumanAccountDataImpl(participantId, new 
PasswordDigest(password.toCharArray()));
+    accountStore.putAccount(account);
+  }
+}

Added: 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/RegistrationRobot.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/RegistrationRobot.java?rev=1228584&view=auto
==============================================================================
--- 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/RegistrationRobot.java
 (added)
+++ 
incubator/wave/trunk/src/org/waveprotocol/box/server/robots/agent/registration/RegistrationRobot.java
 Sat Jan  7 09:46:06 2012
@@ -0,0 +1,152 @@
+/**
+ * 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.waveprotocol.box.server.robots.agent.registration;
+
+import static 
org.waveprotocol.box.server.robots.agent.RobotAgentUtil.CANNOT_CREATE_USER;
+import static 
org.waveprotocol.box.server.robots.agent.RobotAgentUtil.createUser;
+
+import com.google.inject.Inject;
+import com.google.inject.Injector;
+import com.google.inject.Key;
+import com.google.inject.Singleton;
+import com.google.inject.name.Names;
+
+import org.apache.commons.cli.CommandLine;
+import org.waveprotocol.box.server.CoreSettings;
+import org.waveprotocol.box.server.persistence.AccountStore;
+import org.waveprotocol.box.server.persistence.PersistenceException;
+import org.waveprotocol.box.server.robots.agent.AbstractCliRobotAgent;
+import org.waveprotocol.wave.model.wave.InvalidParticipantAddress;
+import org.waveprotocol.wave.model.wave.ParticipantId;
+
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+/**
+ * Robot agent that handles the user registration by an admin
+ *
+ * @author [email protected] (Ali Lown)
+ */
+@SuppressWarnings("serial")
+@Singleton
+public final class RegistrationRobot extends AbstractCliRobotAgent {
+
+  private static final Logger LOG = 
Logger.getLogger(RegistrationRobot.class.getName());
+  public static final String ROBOT_URI = AGENT_PREFIX_URI + 
"/registration/admin";
+
+  /** The address of the admin user as defined in the server configuration. */
+  private final String serverAdminId;
+
+  /** Account store with user and robot accounts. */
+  private final AccountStore accountStore;
+
+  @Inject
+  public RegistrationRobot(Injector injector) {
+    super(injector);
+    serverAdminId =
+        injector.getInstance(Key.get(String.class, 
Names.named(CoreSettings.ADMIN_USER)));
+    accountStore = injector.getInstance(AccountStore.class);
+  }
+
+  @Override
+  protected String maybeExecuteCommand(CommandLine commandLine, String 
modifiedBy) {
+    String robotMessage = null;
+    String adminId = modifiedBy;
+    // Verify that the user that attempts to create a user has admin 
privileges.
+    if (!adminId.equals(serverAdminId)) {
+      robotMessage =
+          "User " + adminId + " is not authorized to use " + getCommandName() 
+ " command.";
+    } else {
+      String userId = null;
+      try {
+        String[] args = commandLine.getArgs();
+        userId = args[1];
+        String password = args[2];
+        // Add domain to the user id if needed.
+        userId = userId + (userId.contains("@") ? "" : "@" + getWaveDomain());
+        ParticipantId participantId = ParticipantId.of(userId);
+        createUser(accountStore, participantId, password);
+        robotMessage = String.format("Created user %s, the password is: %s\n", 
userId, password);
+        LOG.log(Level.INFO, "Created user " + userId + " by " + adminId);
+      } catch (IllegalArgumentException e) {
+        LOG.log(Level.SEVERE, userId, e);
+        robotMessage = e.getMessage();
+      } catch (PersistenceException e) {
+        robotMessage = CANNOT_CREATE_USER + userId;
+        LOG.log(Level.SEVERE, "userId: " + userId, e);
+      } catch (InvalidParticipantAddress e) {
+        robotMessage = CANNOT_CREATE_USER + userId;
+        LOG.log(Level.SEVERE, "userId: " + userId, e);
+      }
+    }
+
+    return robotMessage;
+  }
+
+  @Override
+  public int getMinNumOfArguments() {
+    return 2;
+  }
+
+  @Override
+  public int getMaxNumOfArguments() {
+    return 2;
+  }
+
+  @Override
+  public String getCommandName() {
+    return "register";
+  }
+
+  @Override
+  public String getFullDescription() {
+    return getShortDescription() + "\n" + getUsage() + "\nExample: " + 
getCommandName() + " "
+        + getExample();
+  }
+
+  @Override
+  public String getCmdLineSyntax() {
+    return "[OPTIONS] [USERNAME] [PASSWORD]";
+  }
+
+  @Override
+  public String getExample() {
+    return "user_id password";
+  }
+
+  @Override
+  public String getShortDescription() {
+    return "The command allows the admin to register other users. "
+    + "Please make sure to use it in a wave without other participants. "
+    + "It is also advised to remove yourself from the wave "
+    + "when you finished creating users.";
+  }
+
+  @Override
+  public String getRobotName() {
+    return "Registration-Bot";
+  }
+
+  @Override
+  public String getRobotUri() {
+    return ROBOT_URI;
+  }
+
+  @Override
+  public String getRobotId() {
+    return "registration-bot";
+  }
+}

Modified: 
incubator/wave/trunk/src/org/waveprotocol/box/server/rpc/UserRegistrationServlet.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/src/org/waveprotocol/box/server/rpc/UserRegistrationServlet.java?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- 
incubator/wave/trunk/src/org/waveprotocol/box/server/rpc/UserRegistrationServlet.java
 (original)
+++ 
incubator/wave/trunk/src/org/waveprotocol/box/server/rpc/UserRegistrationServlet.java
 Sat Jan  7 09:46:06 2012
@@ -43,7 +43,7 @@ import javax.servlet.http.HttpServletRes
 
 /**
  * The user registration servlet allows new users to register accounts.
- * 
+ *
  * @author [email protected] (Joseph Gentle)
  */
 @SuppressWarnings("serial")
@@ -53,15 +53,18 @@ public final class UserRegistrationServl
   private final AccountStore accountStore;
   private final String domain;
   private final WelcomeRobot welcomeBot;
+  private final boolean registrationDisabled;
 
   private final Log LOG = Log.get(UserRegistrationServlet.class);
 
   @Inject
   public UserRegistrationServlet(AccountStore accountStore,
-      @Named(CoreSettings.WAVE_SERVER_DOMAIN) String domain, WelcomeRobot 
welcomeBot) {
+      @Named(CoreSettings.WAVE_SERVER_DOMAIN) String domain, WelcomeRobot 
welcomeBot,
+      @Named(CoreSettings.DISABLE_REGISTRATION) boolean registrationDisabled) {
     this.accountStore = accountStore;
     this.domain = domain;
     this.welcomeBot = welcomeBot;
+    this.registrationDisabled = registrationDisabled;
   }
 
   @Override
@@ -72,17 +75,21 @@ public final class UserRegistrationServl
   @Override
   protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
     req.setCharacterEncoding("UTF-8");
-    String message =
-      
tryCreateUser(req.getParameter(HttpRequestBasedCallbackHandler.ADDRESS_FIELD),
-          req.getParameter(HttpRequestBasedCallbackHandler.PASSWORD_FIELD));
-    String responseType = AuthenticationServlet.RESPONSE_STATUS_SUCCESS;
 
-    if (message != null) {
+    String message = null;
+    String responseType;
+    if (!registrationDisabled) {
+    message = 
tryCreateUser(req.getParameter(HttpRequestBasedCallbackHandler.ADDRESS_FIELD),
+                  
req.getParameter(HttpRequestBasedCallbackHandler.PASSWORD_FIELD));
+    }
+
+    if (message != null || registrationDisabled) {
       resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
       responseType = AuthenticationServlet.RESPONSE_STATUS_FAILED;
     } else {
       message = "Registration complete.";
       resp.setStatus(HttpServletResponse.SC_OK);
+      responseType = AuthenticationServlet.RESPONSE_STATUS_SUCCESS;
     }
 
     writeRegistrationPage(message, responseType, req.getLocale(), resp);
@@ -155,6 +162,6 @@ public final class UserRegistrationServl
     dest.setCharacterEncoding("UTF-8");
     dest.setContentType("text/html;charset=utf-8");
     UserRegistrationPage.write(dest.getWriter(), new GxpContext(locale), 
domain, message,
-        responseType);
+        responseType, registrationDisabled);
   }
 }

Modified: 
incubator/wave/trunk/test/org/waveprotocol/box/server/rpc/UserRegistrationServletTest.java
URL: 
http://svn.apache.org/viewvc/incubator/wave/trunk/test/org/waveprotocol/box/server/rpc/UserRegistrationServletTest.java?rev=1228584&r1=1228583&r2=1228584&view=diff
==============================================================================
--- 
incubator/wave/trunk/test/org/waveprotocol/box/server/rpc/UserRegistrationServletTest.java
 (original)
+++ 
incubator/wave/trunk/test/org/waveprotocol/box/server/rpc/UserRegistrationServletTest.java
 Sat Jan  7 09:46:06 2012
@@ -18,6 +18,8 @@
 package org.waveprotocol.box.server.rpc;
 
 import static org.mockito.Matchers.eq;
+import static org.mockito.Mockito.atLeastOnce;
+import static org.mockito.Mockito.anyString;
 import static org.mockito.Mockito.mock;
 import static org.mockito.Mockito.verify;
 import static org.mockito.Mockito.when;
@@ -48,7 +50,6 @@ import javax.servlet.http.HttpServletRes
 public class UserRegistrationServletTest extends TestCase {
   private final AccountData account = new HumanAccountDataImpl(
       ParticipantId.ofUnsafe("[email protected]"), new 
PasswordDigest("password".toCharArray()));
-  private UserRegistrationServlet servlet;
   private AccountStore store;
 
   @Mock private HttpServletRequest req;
@@ -61,30 +62,38 @@ public class UserRegistrationServletTest
     MockitoAnnotations.initMocks(this);
     store = new MemoryStore();
     store.putAccount(account);
-    servlet = new UserRegistrationServlet(store, "example.com", welcomeBot);
 
   }
 
-  public void testRegisterNewUser() throws Exception {
-    attemptToRegister(req, resp, "[email protected]", "internet");
+  public void testRegisterNewUserEnabled() throws Exception {
+    attemptToRegister(req, resp, "[email protected]", "internet", false);
 
     verify(resp).setStatus(HttpServletResponse.SC_OK);
-    ParticipantId paraticipantId = ParticipantId.ofUnsafe("[email protected]");
-    AccountData account = store.getAccount(paraticipantId);
+    ParticipantId participantId = ParticipantId.ofUnsafe("[email protected]");
+    AccountData account = store.getAccount(participantId);
     assertNotNull(account);
     
assertTrue(account.asHuman().getPasswordDigest().verify("internet".toCharArray()));
-    verify(welcomeBot).greet(eq(paraticipantId));
+    verify(welcomeBot).greet(eq(participantId));
+  }
+
+  public void testRegisterNewUserDisabled() throws Exception {
+    attemptToRegister(req, resp, "[email protected]", "internet", true);
+
+    verify(resp).setStatus(HttpServletResponse.SC_FORBIDDEN);
+    ParticipantId participantId = ParticipantId.ofUnsafe("[email protected]");
+    AccountData account = store.getAccount(participantId);
+    assertNull(account);
   }
 
   public void testDomainInsertedAutomatically() throws Exception {
-    attemptToRegister(req, resp, "sam", "fdsa");
+    attemptToRegister(req, resp, "sam", "fdsa", false);
 
     verify(resp).setStatus(HttpServletResponse.SC_OK);
     
assertNotNull(store.getAccount(ParticipantId.ofUnsafe("[email protected]")));
   }
 
   public void testRegisterExistingUserThrowsError() throws Exception {
-    attemptToRegister(req, resp, "[email protected]", "asdf");
+    attemptToRegister(req, resp, "[email protected]", "asdf", false);
 
     verify(resp).setStatus(HttpServletResponse.SC_FORBIDDEN);
 
@@ -93,21 +102,21 @@ public class UserRegistrationServletTest
   }
 
   public void testRegisterUserAtForeignDomainThrowsError() throws Exception {
-    attemptToRegister(req, resp, "[email protected]", "fdsa");
+    attemptToRegister(req, resp, "[email protected]", "fdsa", false);
 
     verify(resp).setStatus(HttpServletResponse.SC_FORBIDDEN);
     assertNull(store.getAccount(ParticipantId.ofUnsafe("[email protected]")));
   }
 
   public void testUsernameTrimmed() throws Exception {
-    attemptToRegister(req, resp, " [email protected] ", "beetleguice");
+    attemptToRegister(req, resp, " [email protected] ", "beetleguice", false);
 
     verify(resp).setStatus(HttpServletResponse.SC_OK);
     
assertNotNull(store.getAccount(ParticipantId.ofUnsafe("[email protected]")));
   }
 
   public void testNullPasswordWorks() throws Exception {
-    attemptToRegister(req, resp, "[email protected]", null);
+    attemptToRegister(req, resp, "[email protected]", null, false);
 
     verify(resp).setStatus(HttpServletResponse.SC_OK);
     AccountData account = 
store.getAccount(ParticipantId.ofUnsafe("[email protected]"));
@@ -117,13 +126,23 @@ public class UserRegistrationServletTest
 
   public void attemptToRegister(
       HttpServletRequest req, HttpServletResponse resp, String address,
-      String password) throws IOException {
+      String password, boolean disabledRegistration) throws IOException {
+
+    UserRegistrationServlet enabledServlet = new 
UserRegistrationServlet(store, "example.com", welcomeBot, false);
+    UserRegistrationServlet disabledServlet = new 
UserRegistrationServlet(store, "example.com", welcomeBot, true);
+
     when(req.getParameter("address")).thenReturn(address);
     when(req.getParameter("password")).thenReturn(password);
     when(req.getLocale()).thenReturn(Locale.ENGLISH);
     PrintWriter writer = mock(PrintWriter.class);
-    when(resp.getWriter()).thenReturn(new PrintWriter(new StringWriter()));
+    when(resp.getWriter()).thenReturn(writer);
+
+    if (disabledRegistration) {
+      disabledServlet.doPost(req, resp);
+    } else {
+      enabledServlet.doPost(req, resp);
+    }
 
-    servlet.doPost(req, resp);
+    verify(writer, atLeastOnce()).append(anyString());
   }
 }


Reply via email to