Browse Source

TimeDuration refactoring and fixes.

Jason Rivard 8 năm trước cách đây
mục cha
commit
0e2b9e66c2

+ 1 - 0
src/main/java/password/pwm/AppProperty.java

@@ -145,6 +145,7 @@ public enum     AppProperty {
     LOCALDB_AGGRESSIVE_COMPACT_ENABLED              ("localdb.aggressiveCompact.enabled"),
     LOCALDB_IMPLEMENTATION                          ("localdb.implementation"),
     LOCALDB_INIT_STRING                             ("localdb.initParameters"),
+    LOCALDB_LOCATION                                ("localdb.location"),
     LOCALDB_LOGWRITER_BUFFER_SIZE                   ("localdb.logWriter.bufferSize"),
     LOCALDB_LOGWRITER_MAX_BUFFER_WAIT_MS            ("localdb.logWriter.maxBufferWaitMs"),
     LOCALDB_LOGWRITER_MAX_TRIM_SIZE                 ("localdb.logWriter.maxTrimSize"),

+ 1 - 1
src/main/java/password/pwm/PwmApplication.java

@@ -702,7 +702,7 @@ public class PwmApplication {
             final File databaseDirectory;
             // see if META-INF isn't already there, then use WEB-INF.
             try {
-                final String localDBLocationSetting = pwmApplication.getConfig().readSettingAsString(PwmSetting.PWMDB_LOCATION);
+                final String localDBLocationSetting = pwmApplication.getConfig().readAppProperty(AppProperty.LOCALDB_LOCATION);
                 databaseDirectory = FileSystemUtility.figureFilepath(localDBLocationSetting, pwmApplication.pwmEnvironment.getApplicationPath());
             } catch (Exception e) {
                 pwmApplication.lastLocalDBFailure = new ErrorInformation(PwmError.ERROR_LOCALDB_UNAVAILABLE,"error locating configured LocalDB directory: " + e.getMessage());

+ 0 - 3
src/main/java/password/pwm/config/PwmSetting.java

@@ -1131,9 +1131,6 @@ public enum PwmSetting {
             "recovery.require.otp", PwmSettingSyntax.BOOLEAN, PwmSettingCategory.RECOVERY_SETTINGS),
     HELPDESK_ENABLE_OTP_VERIFY(
             "helpdesk.otp.verify", PwmSettingSyntax.BOOLEAN, PwmSettingCategory.HELPDESK_BASE),
-    PWMDB_LOCATION(
-            "pwmDb.location", PwmSettingSyntax.STRING, PwmSettingCategory.GENERAL),
-
 
 
     ;

+ 3 - 3
src/main/java/password/pwm/config/profile/NewUserProfile.java

@@ -39,7 +39,7 @@ import password.pwm.error.PwmUnrecoverableException;
 import password.pwm.util.java.TimeDuration;
 import password.pwm.util.operations.PasswordUtility;
 
-import java.util.Date;
+import java.time.Instant;
 import java.util.HashMap;
 import java.util.Locale;
 import java.util.Map;
@@ -48,7 +48,7 @@ public class NewUserProfile extends AbstractProfile {
 
     private static final ProfileType PROFILE_TYPE = ProfileType.NewUser;
 
-    private Date newUserPasswordPolicyCacheTime;
+    private Instant newUserPasswordPolicyCacheTime;
     private final Map<Locale,PwmPasswordPolicy> newUserPasswordPolicyCache = new HashMap<>();
 
     protected NewUserProfile(final String identifier, final Map<PwmSetting, StoredValue> storedValueMap) {
@@ -78,7 +78,7 @@ public class NewUserProfile extends AbstractProfile {
         final Configuration config = pwmApplication.getConfig();
         final long maxNewUserCacheMS = Long.parseLong(pwmApplication.getConfig().readAppProperty(AppProperty.CONFIG_NEWUSER_PASSWORD_POLICY_CACHE_MS));
         if (newUserPasswordPolicyCacheTime != null && TimeDuration.fromCurrent(newUserPasswordPolicyCacheTime).isLongerThan(maxNewUserCacheMS)) {
-            newUserPasswordPolicyCacheTime = new Date();
+            newUserPasswordPolicyCacheTime = Instant.now();
             newUserPasswordPolicyCache.clear();
         }
 

+ 6 - 26
src/main/java/password/pwm/http/bean/PwmSessionBean.java

@@ -22,13 +22,17 @@
 
 package password.pwm.http.bean;
 
+import lombok.Getter;
+import lombok.Setter;
 import password.pwm.config.option.SessionBeanMode;
 import password.pwm.error.ErrorInformation;
 
 import java.io.Serializable;
-import java.util.Date;
+import java.time.Instant;
 import java.util.Set;
 
+@Getter
+@Setter
 public abstract class PwmSessionBean implements Serializable {
     public enum Type {
         PUBLIC,
@@ -36,33 +40,9 @@ public abstract class PwmSessionBean implements Serializable {
     }
 
     private String guid;
-    private Date timestamp;
+    private Instant timestamp;
     private ErrorInformation lastError;
 
-    public String getGuid() {
-        return guid;
-    }
-
-    public void setGuid(final String guid) {
-        this.guid = guid;
-    }
-
-    public Date getTimestamp() {
-        return timestamp;
-    }
-
-    public void setTimestamp(final Date timestamp) {
-        this.timestamp = timestamp;
-    }
-
-    public ErrorInformation getLastError() {
-        return lastError;
-    }
-
-    public void setLastError(final ErrorInformation lastError) {
-        this.lastError = lastError;
-    }
-
     public abstract Type getType();
 
     public abstract Set<SessionBeanMode> supportedModes();

+ 2 - 2
src/main/java/password/pwm/http/state/SessionStateService.java

@@ -35,7 +35,7 @@ import password.pwm.svc.PwmService;
 import password.pwm.util.java.JavaHelper;
 import password.pwm.util.logging.PwmLogger;
 
-import java.util.Date;
+import java.time.Instant;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -179,7 +179,7 @@ public class SessionStateService implements PwmService {
         try {
             final E newBean = theClass.newInstance();
             newBean.setGuid(sessionGuid);
-            newBean.setTimestamp(new Date());
+            newBean.setTimestamp(Instant.now());
             return newBean;
         } catch (Exception e) {
             final String errorMsg = "unexpected error trying to instantiate bean class " + theClass.getName() + ": " + e.getMessage();

+ 4 - 3
src/main/java/password/pwm/ldap/auth/LDAPAuthenticationRequest.java

@@ -383,9 +383,10 @@ class LDAPAuthenticationRequest implements AuthenticationRequest {
             );
 
             // create random password for user
-            final RandomPasswordGenerator.RandomGeneratorConfig randomGeneratorConfig = new RandomPasswordGenerator.RandomGeneratorConfig();
-            randomGeneratorConfig.setSeedlistPhrases(RandomPasswordGenerator.DEFAULT_SEED_PHRASES);
-            randomGeneratorConfig.setPasswordPolicy(passwordPolicy);
+            final RandomPasswordGenerator.RandomGeneratorConfig randomGeneratorConfig = RandomPasswordGenerator.RandomGeneratorConfig.builder()
+                    .seedlistPhrases(RandomPasswordGenerator.DEFAULT_SEED_PHRASES)
+                    .passwordPolicy(passwordPolicy)
+                    .build();
 
             final PasswordData currentPass = RandomPasswordGenerator.createRandomPassword(sessionLabel, randomGeneratorConfig, pwmApplication);
 

+ 6 - 6
src/main/java/password/pwm/svc/wordlist/AbstractWordlist.java

@@ -331,7 +331,7 @@ abstract class AbstractWordlist implements Wordlist, PwmService {
         if (storedValue != null) {
             return storedValue;
         }
-        return new StoredWordlistDataBean.Builder().create();
+        return StoredWordlistDataBean.builder().build();
     }
 
     void writeMetadata(final StoredWordlistDataBean metadataBean) {
@@ -367,7 +367,7 @@ abstract class AbstractWordlist implements Wordlist, PwmService {
         if (wlStatus == STATUS.OPEN) {
             executorService.schedule(() -> {
                 try {
-                    writeMetadata(new StoredWordlistDataBean.Builder().create());
+                    writeMetadata(StoredWordlistDataBean.builder().build());
                     populationManager.checkPopulation();
                 } catch (Exception e) {
                     LOGGER.error("error during clear operation: " + e.getMessage());
@@ -407,7 +407,7 @@ abstract class AbstractWordlist implements Wordlist, PwmService {
             } else {
                 if (readMetadata().getSource() == StoredWordlistDataBean.Source.AutoImport) {
                     LOGGER.trace("source list is from auto-import, but not currently configured for auto-import; clearing stored data");
-                    writeMetadata(new StoredWordlistDataBean.Builder().create()); // clear previous auto-import wll
+                    writeMetadata(StoredWordlistDataBean.builder().build()); // clear previous auto-import wll
                 }
             }
 
@@ -462,9 +462,9 @@ abstract class AbstractWordlist implements Wordlist, PwmService {
                 }
 
                 { // reset the wordlist metadata
-                    final StoredWordlistDataBean storedWordlistDataBean = new StoredWordlistDataBean.Builder()
-                            .setSource(source)
-                            .create();
+                    final StoredWordlistDataBean storedWordlistDataBean = StoredWordlistDataBean.builder()
+                            .source(source)
+                            .build();
                     writeMetadata(storedWordlistDataBean);
                 }
 

+ 9 - 8
src/main/java/password/pwm/svc/wordlist/Populator.java

@@ -39,6 +39,7 @@ import java.io.IOException;
 import java.io.InputStream;
 import java.text.DecimalFormat;
 import java.text.NumberFormat;
+import java.time.Instant;
 import java.util.Date;
 import java.util.Map;
 import java.util.TreeMap;
@@ -139,7 +140,7 @@ class Populator {
 
     void populate() throws IOException, LocalDBException, PwmUnrecoverableException {
         try {
-            rootWordlist.writeMetadata(new StoredWordlistDataBean.Builder().setSource(source).create());
+            rootWordlist.writeMetadata(StoredWordlistDataBean.builder().source(source).build());
             running = true;
             init();
 
@@ -240,13 +241,13 @@ class Populator {
         sb.append(" population complete, added ").append(wordlistSize);
         sb.append(" total words in ").append(new TimeDuration(overallStats.getElapsedSeconds() * 1000).asCompactString());
         {
-            final StoredWordlistDataBean storedWordlistDataBean = new StoredWordlistDataBean.Builder()
-                    .setSha1hash(JavaHelper.binaryArrayToHex(checksumInputStream.closeAndFinalChecksum()))
-                    .setSize(wordlistSize)
-                    .setStoreDate(new Date())
-                    .setSource(source)
-                    .setCompleted(!abortFlag)
-                    .create();
+            final StoredWordlistDataBean storedWordlistDataBean = StoredWordlistDataBean.builder()
+                    .sha1hash(JavaHelper.binaryArrayToHex(checksumInputStream.closeAndFinalChecksum()))
+                    .size(wordlistSize)
+                    .storeDate(Instant.now())
+                    .source(source)
+                    .completed(!abortFlag)
+                    .build();
             rootWordlist.writeMetadata(storedWordlistDataBean);
         }
         LOGGER.info(sb.toString());

+ 7 - 78
src/main/java/password/pwm/svc/wordlist/StoredWordlistDataBean.java

@@ -22,13 +22,18 @@
 
 package password.pwm.svc.wordlist;
 
+import lombok.Builder;
+import lombok.Getter;
+
 import java.io.Serializable;
-import java.util.Date;
+import java.time.Instant;
 
+@Getter
+@Builder
 public class StoredWordlistDataBean implements Serializable {
     private boolean completed;
     private Source source;
-    private Date storeDate;
+    private Instant storeDate;
     private String sha1hash;
     private int size;
 
@@ -49,80 +54,4 @@ public class StoredWordlistDataBean implements Serializable {
             return label;
         }
     }
-
-    public boolean isCompleted() {
-        return completed;
-    }
-
-    public Source getSource() {
-        return source;
-    }
-
-    public Date getStoreDate() {
-        return storeDate;
-    }
-
-    public String getSha1hash() {
-        return sha1hash;
-    }
-
-    public int getSize() {
-        return size;
-    }
-
-    public StoredWordlistDataBean(final boolean completed, final Source source, final Date storeDate, final String sha1hash, final int size) {
-        this.completed = completed;
-        this.source = source;
-        this.storeDate = storeDate;
-        this.sha1hash = sha1hash;
-        this.size = size;
-    }
-
-    public static class Builder {
-        private boolean completed;
-        private Source source;
-        private Date storeDate;
-        private String sha1hash;
-        private int size;
-
-        public Builder() {
-        }
-
-        public Builder(final StoredWordlistDataBean source) {
-            this.completed = source.completed;
-            this.source = source.source;
-            this.storeDate = source.storeDate;
-            this.sha1hash = source.sha1hash;
-            this.size = source.size;
-        }
-
-        public Builder setCompleted(final boolean completed) {
-            this.completed = completed;
-            return this;
-        }
-
-        public Builder setSource(final Source source) {
-            this.source = source;
-            return this;
-        }
-
-        public Builder setStoreDate(final Date storeDate) {
-            this.storeDate = storeDate;
-            return this;
-        }
-
-        public Builder setSha1hash(final String sha1hash) {
-            this.sha1hash = sha1hash;
-            return this;
-        }
-
-        public Builder setSize(final int size) {
-            this.size = size;
-            return this;
-        }
-
-        public StoredWordlistDataBean create() {
-            return new StoredWordlistDataBean(completed, source, storeDate, sha1hash, size);
-        }
-    }
 }

+ 2 - 2
src/main/java/password/pwm/util/cli/MainClass.java

@@ -27,12 +27,12 @@ import org.apache.log4j.EnhancedPatternLayout;
 import org.apache.log4j.Layout;
 import org.apache.log4j.Logger;
 import org.apache.log4j.varia.NullAppender;
+import password.pwm.AppProperty;
 import password.pwm.PwmApplication;
 import password.pwm.PwmApplicationMode;
 import password.pwm.PwmConstants;
 import password.pwm.PwmEnvironment;
 import password.pwm.config.Configuration;
-import password.pwm.config.PwmSetting;
 import password.pwm.config.stored.ConfigurationReader;
 import password.pwm.error.ErrorInformation;
 import password.pwm.error.PwmError;
@@ -384,7 +384,7 @@ public class MainClass {
             throws Exception
     {
         final File databaseDirectory;
-        final String pwmDBLocationSetting = config.readSettingAsString(PwmSetting.PWMDB_LOCATION);
+        final String pwmDBLocationSetting = config.readAppProperty(AppProperty.LOCALDB_LOCATION);
         databaseDirectory = FileSystemUtility.figureFilepath(pwmDBLocationSetting, applicationPath);
         return LocalDBFactory.getInstance(databaseDirectory, readonly, null, config);
     }

+ 3 - 3
src/main/java/password/pwm/util/java/TimeDuration.java

@@ -52,7 +52,7 @@ public class TimeDuration implements Comparable, Serializable {
     public static final TimeDuration ZERO = new TimeDuration(0);
     public static final TimeDuration MILLISECOND = new TimeDuration(1, TimeUnit.MILLISECONDS);
     public static final TimeDuration SECOND = new TimeDuration(1, TimeUnit.SECONDS);
-    public static final TimeDuration SECONDS_10 = new TimeDuration(30, TimeUnit.SECONDS);
+    public static final TimeDuration SECONDS_10 = new TimeDuration(10, TimeUnit.SECONDS);
     public static final TimeDuration SECONDS_30 = new TimeDuration(30, TimeUnit.SECONDS);
     public static final TimeDuration MINUTE = new TimeDuration(1, TimeUnit.MINUTES);
     public static final TimeDuration HOUR = new TimeDuration(1, TimeUnit.HOURS);
@@ -92,8 +92,8 @@ public class TimeDuration implements Comparable, Serializable {
         return new TimeDuration(System.currentTimeMillis(), instant.toEpochMilli());
     }
 
-    public static String compactFromCurrent(final long ms) {
-        return new TimeDuration(System.currentTimeMillis(), ms).asCompactString();
+    public static String compactFromCurrent(final Instant instant) {
+        return TimeDuration.fromCurrent(instant).asCompactString();
     }
 
     public static String asCompactString(final long ms) {

+ 3 - 2
src/main/java/password/pwm/util/localdb/Derby_LocalDB.java

@@ -35,6 +35,7 @@ import java.sql.Connection;
 import java.sql.Driver;
 import java.sql.DriverManager;
 import java.sql.SQLException;
+import java.time.Instant;
 import java.util.Map;
 import java.util.Properties;
 
@@ -142,7 +143,7 @@ public class Derby_LocalDB extends AbstractJDBC_LocalDB {
     }
 
     private void reclaimAllSpace(final Connection dbConnection) {
-        final java.util.Date startTime = new java.util.Date();
+        final Instant startTime = Instant.now();
         final long startSize = FileSystemUtility.getFileDirectorySize(dbDirectory);
         LOGGER.debug("beginning reclaim space in all tables startSize=" + StringUtil.formatDiskSize(startSize));
         for (final LocalDB.DB db : LocalDB.DB.values()) {
@@ -150,7 +151,7 @@ public class Derby_LocalDB extends AbstractJDBC_LocalDB {
         }
         final long completeSize = FileSystemUtility.getFileDirectorySize(dbDirectory);
         final long sizeDifference = startSize - completeSize;
-        LOGGER.debug("completed reclaim space in all tables; duration=" + TimeDuration.fromCurrent(startTime).asCompactString()
+        LOGGER.debug("completed reclaim space in all tables; duration=" + TimeDuration.compactFromCurrent(startTime)
                 + ", startSize=" + StringUtil.formatDiskSize(startSize)
                 + ", completeSize=" + StringUtil.formatDiskSize(completeSize)
                 + ", sizeDifference=" + StringUtil.formatDiskSize(sizeDifference)

+ 1 - 0
src/main/resources/password/pwm/AppProperty.properties

@@ -180,6 +180,7 @@ ldap.oracle.postTempPasswordUseCurrentTime=false
 localdb.aggressiveCompact.enabled=false
 localdb.implementation=password.pwm.util.localdb.Xodus_LocalDB
 localdb.initParameters=
+localdb.location=LocalDB
 localdb.logWriter.bufferSize=500
 localdb.logWriter.maxBufferWaitMs=60000
 localdb.logWriter.maxTrimSize=5001

+ 0 - 5
src/main/resources/password/pwm/config/PwmSetting.xml

@@ -3678,11 +3678,6 @@
             <value>false</value>
         </default>
     </setting>
-    <setting hidden="true" key="pwmDb.location" level="2" required="true">
-        <default>
-            <value><![CDATA[LocalDB]]></value>
-        </default>
-    </setting>
     <!-- DEPRECATED SETTINGS -->
     <category hidden="false" key="TEMPLATES">
     </category>

+ 0 - 2
src/main/resources/password/pwm/i18n/PwmSetting.properties

@@ -570,7 +570,6 @@ Setting_Description_peopleSearch.searchFilter=Specify the LDAP search filter the
 Setting_Description_peopleSearch.useProxy=Enable this option to use the LDAP proxy account to perform searches. For proper security in most environments, do <b>not</b> enable this setting.
 Setting_Description_pwmAdmin.queryMatch=Specify the permissions @PwmAppName@ uses to determine if it grants a user administrator rights.
 Setting_Description_pwm.appProperty.overrides=(Troubleshooting only) Specify an override application properties value.  Do not use unless directed to by a support expert.
-Setting_Description_pwmDb.location=Specify the location of the LocalDB directory. If the specified path is relative, @PwmAppName@ considers the path relative to the servlet's <i>WEB-INF</i> directory.
 Setting_Description_pwm.forwardURL=Specify a URL that @PwmAppName@ forwards users to after the users complete any activity which does not require a log out.<br/><br/>You can override this setting for any given user session by adding a <i>forwardURL</i> parameter to any HTTP request. If blank, the system forwards the user to the @PwmAppName@ menu.
 Setting_Description_pwm.homeURL=Specify the URL to redirect the user to upon clicking the home button. If blank, the home button returns the user to the application context URL.
 Setting_Description_pwmInstanceName=Specify the name of this application instance. If blank, @PwmAppName@ uses a persistent, randomly generated value. The recommended value is blank.
@@ -1043,7 +1042,6 @@ Setting_Label_peopleSearch.searchFilter=People Search LDAP Filter
 Setting_Label_peopleSearch.useProxy=Use Proxy Account
 Setting_Label_pwmAdmin.queryMatch=Administrator Permission
 Setting_Label_pwm.appProperty.overrides=App Property Overrides
-Setting_Label_pwmDb.location=LocalDB Location
 Setting_Label_pwm.forwardURL=Forward URL
 Setting_Label_pwm.homeURL=Home URL
 Setting_Label_pwmInstanceName=Instance Name