From 8828e7927bbb9ce67d1be1606aa1a5b81f068b4f Mon Sep 17 00:00:00 2001
From: brinn <brinn>
Date: Thu, 24 Jan 2013 14:34:00 +0000
Subject: [PATCH] Change PasswordEditorCommand such that it can work with
 password cache files.

SVN: 28189
---
 .../file/CachingAuthenticationService.java    |  12 +-
 .../file/FileAuthenticationService.java       |  29 +-
 .../cisd/authentication/file/Parameters.java  |  21 +-
 .../file/PasswordEditorCommand.java           | 329 ++++++++++++------
 4 files changed, 264 insertions(+), 127 deletions(-)

diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/file/CachingAuthenticationService.java b/authentication/source/java/ch/systemsx/cisd/authentication/file/CachingAuthenticationService.java
index af4294eb60a..e9fa9528e68 100644
--- a/authentication/source/java/ch/systemsx/cisd/authentication/file/CachingAuthenticationService.java
+++ b/authentication/source/java/ch/systemsx/cisd/authentication/file/CachingAuthenticationService.java
@@ -354,8 +354,18 @@ public class CachingAuthenticationService implements IAuthenticationService
         {
             return null;
         }
+        return createUserStore(new File(passwordCacheFileName));
+    }
+
+    static IUserStore<UserCacheEntry> createUserStore(
+            final File passwordCacheFile)
+    {
+        if (passwordCacheFile == null)
+        {
+            return null;
+        }
         final ILineStore lineStore =
-                new FileBasedLineStore(new File(passwordCacheFileName), "Password cache file");
+                new FileBasedLineStore(passwordCacheFile, "Password cache file");
         return new LineBasedUserStore<UserCacheEntry>(lineStore,
                 new IUserEntryFactory<UserCacheEntry>()
                     {
diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/file/FileAuthenticationService.java b/authentication/source/java/ch/systemsx/cisd/authentication/file/FileAuthenticationService.java
index d8fefeee771..81e4d486938 100644
--- a/authentication/source/java/ch/systemsx/cisd/authentication/file/FileAuthenticationService.java
+++ b/authentication/source/java/ch/systemsx/cisd/authentication/file/FileAuthenticationService.java
@@ -28,6 +28,7 @@ import ch.systemsx.cisd.common.exceptions.ConfigurationFailureException;
 import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException;
 import ch.systemsx.cisd.common.logging.LogCategory;
 import ch.systemsx.cisd.common.logging.LogFactory;
+import ch.systemsx.cisd.common.shared.basic.string.StringUtils;
 
 /**
  * An implementation of {@link IAuthenticationService} that gets the authentication information from
@@ -51,24 +52,38 @@ public class FileAuthenticationService implements IAuthenticationService
     private static final Logger operationLog =
             LogFactory.getLogger(LogCategory.OPERATION, FileAuthenticationService.class);
 
-    private final IUserStore<? extends UserEntry> userStore;
+    private final IUserStore<UserEntry> userStore;
 
     private final IAuthenticationService listingServiceOrNull;
 
-    private static IUserStore<? extends UserEntry> createUserStore(final String passwordFileName)
+    /**
+     * Returns a "standard" line-based user store for {@link UserEntry}s.
+     */
+    static IUserStore<UserEntry> createUserStore(final String passwordFileName)
     {
-        if (passwordFileName == null)
+        if (StringUtils.isBlank(passwordFileName))
         {
             return null;
         }
-        final ILineStore lineStore =
-                new FileBasedLineStore(new File(passwordFileName), "Password file");
-        return createUserStore(lineStore);
+        return createUserStore(new File(passwordFileName));
     }
 
     /**
      * Returns a "standard" line-based user store for {@link UserEntry}s.
      */
+    static IUserStore<UserEntry> createUserStore(final File passwordFile)
+    {
+        if (passwordFile == null)
+        {
+            return null;
+        }
+        final ILineStore lineStore = new FileBasedLineStore(passwordFile, "Password file");
+        return createUserStore(lineStore);
+    }
+
+    /**
+     * For unit tests.
+     */
     static IUserStore<UserEntry> createUserStore(final ILineStore lineStore)
     {
         return new LineBasedUserStore<UserEntry>(lineStore, new IUserEntryFactory<UserEntry>()
@@ -86,7 +101,7 @@ public class FileAuthenticationService implements IAuthenticationService
         this(createUserStore(passwordFileName), null);
     }
 
-    public FileAuthenticationService(IUserStore<? extends UserEntry> userStore,
+    public FileAuthenticationService(IUserStore<UserEntry> userStore,
             IAuthenticationService listingServiceOrNull)
     {
         this.userStore = userStore;
diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/file/Parameters.java b/authentication/source/java/ch/systemsx/cisd/authentication/file/Parameters.java
index d43daab8180..b7be6af9f9b 100644
--- a/authentication/source/java/ch/systemsx/cisd/authentication/file/Parameters.java
+++ b/authentication/source/java/ch/systemsx/cisd/authentication/file/Parameters.java
@@ -58,6 +58,8 @@ final class Parameters
     private final IExitHandler exitHandler;
 
     private final Command command;
+    
+    private final boolean cache;
 
     private String userId;
 
@@ -87,23 +89,30 @@ final class Parameters
     @Option(longName = "help", skipForExample = true, usage = "Prints out a description of the options.")
     void printHelp(boolean exit)
     {
-        parser.printHelp("passwd",
-                "list | [remove|show|test] <user> | [add|change] <user> [option [...]]", "",
-                ExampleMode.NONE);
+        if (cache)
+        {
+            System.err.println("passwd_cache list | [remove|show|test] <user>");
+        } else
+        {
+            parser.printHelp("passwd",
+                    "list | [remove|show|test] <user> | [add|change] <user> [option [...]]", "",
+                    ExampleMode.NONE);
+        }
         if (exit)
         {
             exitHandler.exit(0);
         }
     }
 
-    Parameters(String[] args)
+    Parameters(String[] args, boolean cache)
     {
-        this(args, SystemExit.SYSTEM_EXIT);
+        this(args, cache, SystemExit.SYSTEM_EXIT);
     }
 
-    Parameters(String[] args, IExitHandler systemExitHandler)
+    Parameters(String[] args, boolean cache, IExitHandler systemExitHandler)
     {
         this.exitHandler = systemExitHandler;
+        this.cache = cache;
         try
         {
             parser.parseArgument(args);
diff --git a/authentication/source/java/ch/systemsx/cisd/authentication/file/PasswordEditorCommand.java b/authentication/source/java/ch/systemsx/cisd/authentication/file/PasswordEditorCommand.java
index dfdaaa6ebe8..9a4b7e97146 100644
--- a/authentication/source/java/ch/systemsx/cisd/authentication/file/PasswordEditorCommand.java
+++ b/authentication/source/java/ch/systemsx/cisd/authentication/file/PasswordEditorCommand.java
@@ -18,11 +18,15 @@ package ch.systemsx.cisd.authentication.file;
 
 import java.io.File;
 import java.io.IOException;
+import java.util.Date;
+
+import org.apache.commons.lang.StringUtils;
 
 import jline.ConsoleReader;
 
 import ch.systemsx.cisd.common.exceptions.EnvironmentFailureException;
 import ch.systemsx.cisd.common.exceptions.HighLevelException;
+import ch.systemsx.cisd.common.time.DateFormatThreadLocal;
 
 /**
  * A class to create and edit password entries.
@@ -38,6 +42,9 @@ public class PasswordEditorCommand
 
     private final static File PASSWORD_FILE = new File("etc/passwd");
 
+    private static final boolean isCacheFile = StringUtils.isNotEmpty(System
+            .getProperty("PASSWORD_CACHE_FILE"));
+
     private static ConsoleReader consoleReader;
 
     /** Returns a <code>ConsoleReader</code> instance after having lazily instantiated it. */
@@ -73,6 +80,10 @@ public class PasswordEditorCommand
 
     private static File getPasswordFile()
     {
+        if (isCacheFile)
+        {
+            return new File(System.getProperty("PASSWORD_CACHE_FILE"));
+        }
         if (System.getProperty("PASSWORD_FILE") != null)
         {
             return new File(System.getProperty("PASSWORD_FILE"));
@@ -88,130 +99,222 @@ public class PasswordEditorCommand
                 user.getLastName(), user.getEmail());
     }
 
+    private static void printUserCache(final UserCacheEntry user)
+    {
+        System.out.printf("%-20s  %-20s  %-20s  %-30s  %-20s\n", user.getUserId(), user
+                .getFirstName(), user.getLastName(), user.getEmail(),
+                DateFormatThreadLocal.DATE_FORMAT.get().format(new Date(user.getCachedAt())));
+    }
+
     private static void printHeader()
     {
         System.out.printf("%-20s  %-20s  %-20s  %-20s\n", "User ID", "First Name", "Last Name",
                 "Email");
     }
 
+    private static void printHeaderCache()
+    {
+        System.out.printf("%-20s  %-20s  %-20s  %-30s  %-20s\n", "User ID", "First Name",
+                "Last Name", "Email", "Cached At");
+    }
+
+    private static void execute(Parameters params)
+    {
+        final IUserStore<UserEntry> userStore =
+                FileAuthenticationService.createUserStore(getPasswordFile());
+        switch (params.getCommand())
+        {
+            case ADD:
+            {
+                final String userId = params.getUserId();
+                final UserEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull != null)
+                {
+                    System.err.printf("User '%s' already exists.\n", userId);
+                    System.exit(1);
+                }
+                final String password;
+                if (params.tryGetPassword() != null)
+                {
+                    password = params.tryGetPassword();
+                } else
+                {
+                    password = readPassword(ENTER_NEW_PASSWORD_MSG);
+                }
+                final UserEntry user =
+                        new UserEntry(params.getUserId(), params.getEmail(), params
+                                .getFirstName(), params.getLastName(), password);
+                userStore.addOrUpdateUser(user);
+                break;
+            }
+            case CHANGE:
+            {
+                final String userId = params.getUserId();
+                final UserEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull == null)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                    return; // Fake: convince compiler that it is save to dereference userOrNull
+                }
+                if (params.getFirstName() != null)
+                {
+                    userOrNull.setFirstName(params.getFirstName());
+                }
+                if (params.getLastName() != null)
+                {
+                    userOrNull.setLastName(params.getLastName());
+                }
+                if (params.getEmail() != null)
+                {
+                    userOrNull.setEmail(params.getEmail());
+                }
+                if (params.tryGetPassword() != null)
+                {
+                    userOrNull.setPassword(params.tryGetPassword());
+                } else if (params.isChangePassword())
+                {
+                    userOrNull.setPassword(readPassword(ENTER_NEW_PASSWORD_MSG));
+                }
+                userStore.addOrUpdateUser(userOrNull);
+                break;
+            }
+            case LIST:
+            {
+                printHeader();
+                for (UserEntry user : userStore.listUsers())
+                {
+                    printUser(user);
+                }
+                break;
+            }
+            case REMOVE:
+            {
+                final String userId = params.getUserId();
+                if (userStore.removeUser(userId) == false)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                }
+                break;
+            }
+            case SHOW:
+            {
+                final String userId = params.getUserId();
+                final UserEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull == null)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                    return; // Fake: convince compiler that it is save to dereference userOrNull
+                }
+                printHeader();
+                printUser(userOrNull);
+                break;
+            }
+            case TEST:
+            {
+                final String userId = params.getUserId();
+                final UserEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull == null)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                    return; // Fake: convince compiler that it is save to dereference userOrNull
+                }
+                final String password = readPassword(ENTER_PASSWORD_MSG);
+                if (userStore.isPasswordCorrect(userId, password))
+                {
+                    System.out.printf("User '%s' successfully authenticated.\n", userId);
+                } else
+                {
+                    System.out.printf("User '%s' authentication failed.\n", userId);
+                }
+                break;
+            }
+        }
+    }
+
+    private static void executeCache(Parameters params)
+    {
+        final IUserStore<UserCacheEntry> userStore =
+                CachingAuthenticationService.createUserStore(getPasswordFile());
+        switch (params.getCommand())
+        {
+            case ADD:
+            case CHANGE:
+            {
+                System.err.println(params.getCommand() + " not supported on password cache files.");
+                System.exit(1);
+                break; // to satisfy the compiler
+            }
+            case LIST:
+            {
+                printHeaderCache();
+                for (UserCacheEntry user : userStore.listUsers())
+                {
+                    printUserCache(user);
+                }
+                break;
+            }
+            case REMOVE:
+            {
+                final String userId = params.getUserId();
+                if (userStore.removeUser(userId) == false)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                }
+                break;
+            }
+            case SHOW:
+            {
+                final String userId = params.getUserId();
+                final UserCacheEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull == null)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                    return; // Fake: convince compiler that it is save to dereference userOrNull
+                }
+                printHeader();
+                printUserCache(userOrNull);
+                break;
+            }
+            case TEST:
+            {
+                final String userId = params.getUserId();
+                final UserCacheEntry userOrNull = userStore.tryGetUserById(userId);
+                if (userOrNull == null)
+                {
+                    System.err.printf("User '%s' does not exist.\n", userId);
+                    System.exit(1);
+                    return; // Fake: convince compiler that it is save to dereference userOrNull
+                }
+                final String password = readPassword(ENTER_PASSWORD_MSG);
+                if (userStore.isPasswordCorrect(userId, password))
+                {
+                    System.out.printf("User '%s' successfully authenticated.\n", userId);
+                } else
+                {
+                    System.out.printf("User '%s' authentication failed.\n", userId);
+                }
+                break;
+            }
+        }
+    }
+
     public static void main(String[] args)
     {
         try
         {
-            final Parameters params = new Parameters(args);
-            final ILineStore lineStore = new FileBasedLineStore(getPasswordFile(), "Password file");
-            final IUserStore<UserEntry> userStore =
-                    FileAuthenticationService.createUserStore(lineStore);
-            switch (params.getCommand())
+            final Parameters params = new Parameters(args, isCacheFile);
+            if (isCacheFile)
             {
-                case ADD:
-                {
-                    final String userId = params.getUserId();
-                    final UserEntry userOrNull = userStore.tryGetUserById(userId);
-                    if (userOrNull != null)
-                    {
-                        System.err.printf("User '%s' already exists.\n", userId);
-                        System.exit(1);
-                    }
-                    final String password;
-                    if (params.tryGetPassword() != null)
-                    {
-                        password = params.tryGetPassword();
-                    } else
-                    {
-                        password = readPassword(ENTER_NEW_PASSWORD_MSG);
-                    }
-                    final UserEntry user =
-                            new UserEntry(params.getUserId(), params.getEmail(), params
-                                    .getFirstName(), params.getLastName(), password);
-                    userStore.addOrUpdateUser(user);
-                    break;
-                }
-                case CHANGE:
-                {
-                    final String userId = params.getUserId();
-                    final UserEntry userOrNull = userStore.tryGetUserById(userId);
-                    if (userOrNull == null)
-                    {
-                        System.err.printf("User '%s' does not exist.\n", userId);
-                        System.exit(1);
-                        return; // Fake: convince compiler that it is save to dereference userOrNull
-                    }
-                    if (params.getFirstName() != null)
-                    {
-                        userOrNull.setFirstName(params.getFirstName());
-                    }
-                    if (params.getLastName() != null)
-                    {
-                        userOrNull.setLastName(params.getLastName());
-                    }
-                    if (params.getEmail() != null)
-                    {
-                        userOrNull.setEmail(params.getEmail());
-                    }
-                    if (params.tryGetPassword() != null)
-                    {
-                        userOrNull.setPassword(params.tryGetPassword());
-                    } else if (params.isChangePassword())
-                    {
-                        userOrNull.setPassword(readPassword(ENTER_NEW_PASSWORD_MSG));
-                    }
-                    userStore.addOrUpdateUser(userOrNull);
-                    break;
-                }
-                case LIST:
-                {
-                    printHeader();
-                    for (UserEntry user : userStore.listUsers())
-                    {
-                        printUser(user);
-                    }
-                    break;
-                }
-                case REMOVE:
-                {
-                    final String userId = params.getUserId();
-                    if (userStore.removeUser(userId) == false)
-                    {
-                        System.err.printf("User '%s' does not exist.\n", userId);
-                        System.exit(1);
-                    }
-                    break;
-                }
-                case SHOW:
-                {
-                    final String userId = params.getUserId();
-                    final UserEntry userOrNull = userStore.tryGetUserById(userId);
-                    if (userOrNull == null)
-                    {
-                        System.err.printf("User '%s' does not exist.\n", userId);
-                        System.exit(1);
-                        return; // Fake: convince compiler that it is save to dereference userOrNull
-                    }
-                    printHeader();
-                    printUser(userOrNull);
-                    break;
-                }
-                case TEST:
-                {
-                    final String userId = params.getUserId();
-                    final UserEntry userOrNull = userStore.tryGetUserById(userId);
-                    if (userOrNull == null)
-                    {
-                        System.err.printf("User '%s' does not exist.\n", userId);
-                        System.exit(1);
-                        return; // Fake: convince compiler that it is save to dereference userOrNull
-                    }
-                    final String password = readPassword(ENTER_PASSWORD_MSG);
-                    if (userStore.isPasswordCorrect(userId, password))
-                    {
-                        System.out.printf("User '%s' successfully authenticated.\n", userId);
-                    } else
-                    {
-                        System.out.printf("User '%s' authentication failed.\n", userId);
-                    }
-                    break;
-                }
+                executeCache(params);
+            } else
+            {
+                execute(params);
             }
         } catch (HighLevelException ex)
         {
-- 
GitLab