JAL-3261 tidy up get/set properties in Cache, Javadoc, tests
[jalview.git] / src / jalview / bin / Cache.java
index b2f6e95..07e346f 100755 (executable)
@@ -20,8 +20,9 @@
  */
 package jalview.bin;
 
+import jalview.bin.ApplicationSingletonProvider.ApplicationSingletonI;
 import jalview.datamodel.PDBEntry;
-import jalview.gui.UserDefinedColours;
+import jalview.gui.Preferences;
 import jalview.schemes.ColourSchemeLoader;
 import jalview.schemes.ColourSchemes;
 import jalview.schemes.UserColourScheme;
@@ -32,6 +33,7 @@ import jalview.util.Platform;
 import jalview.ws.sifts.SiftsSettings;
 
 import java.awt.Color;
+import java.awt.Dimension;
 import java.io.BufferedReader;
 import java.io.File;
 import java.io.FileInputStream;
@@ -204,13 +206,14 @@ import org.apache.log4j.SimpleLayout;
  * panel in web service preferences</li>
  * </ul>
  * 
- * @author $author$
- * @version $Revision$
  */
-public class Cache
+public class Cache implements ApplicationSingletonI
 {
 
-  static Cache instance;
+  private Cache()
+  {
+    // private singleton
+  }
 
   /**
    * In Java, this will be a static field instance, which will be
@@ -221,36 +224,7 @@ public class Cache
    */
   public static Cache getInstance()
   {
-
-    // BH 2019.05.08 need to isolate static fields in JavaScript
-
-    Cache i = instance;
-    @SuppressWarnings("unused")
-    ThreadGroup g = null;
-    if (Platform.isJS())
-    {
-      g = Thread.currentThread().getThreadGroup();
-      /**
-       * @j2sNative i = g._jalviewCacheInstance;
-       * 
-       */
-    }
-    if (i == null)
-    {
-      i = new Cache();
-      if (Platform.isJS())
-      {
-        /**
-         * @j2sNative g._jalviewCacheInstance = i;
-         * 
-         */
-      }
-      else
-      {
-        instance = i;
-      }
-    }
-    return i;
+    return (Cache) ApplicationSingletonProvider.getInstance(Cache.class);
   }
 
   /**
@@ -308,15 +282,10 @@ public class Cache
    */
   public static Logger log;
 
-  private Cache()
-  {
-    // inaccessible
-  }
-
   /** Jalview Properties */
   // BH 2019.05.08 was static
   @SuppressWarnings("serial")
-  private Properties applicationProperties = new Properties()
+  public Properties applicationProperties = new Properties()
   {
     // override results in properties output in alphabetical order
     @Override
@@ -327,8 +296,7 @@ public class Cache
   };
 
   /** Default file is ~/.jalview_properties */
-  // BH 2019.05.07 note: Instances of Jalview will share this file.
-  static String propertiesFile;
+  private String propertiesFile;
 
   /**
    * flag to possibly allow properties to be written to a property file
@@ -358,14 +326,14 @@ public class Cache
       jalview.bin.Cache.log = Logger.getLogger("jalview.bin.Jalview");
 
       laxis.setLevel(Level.toLevel(
-              Cache.getDefault("logs.Axis.Level", Level.INFO.toString())));
-      lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
-              Level.INFO.toString())));
+              getDefault("logs.Axis.Level", Level.INFO.toString())));
+      lcastor.setLevel(Level.toLevel(
+              getDefault("logs.Castor.Level", Level.INFO.toString())));
       lcastor = Logger.getLogger("org.exolab.castor.xml");
-      lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
-              Level.INFO.toString())));
+      lcastor.setLevel(Level.toLevel(
+              getDefault("logs.Castor.Level", Level.INFO.toString())));
       // lcastor = Logger.getLogger("org.exolab.castor.xml.Marshaller");
-      // lcastor.setLevel(Level.toLevel(Cache.getDefault("logs.Castor.Level",
+      // lcastor.setLevel(Level.toLevel(getDefault("logs.Castor.Level",
       // Level.INFO.toString())));
       jalview.bin.Cache.log.setLevel(Level.toLevel(Cache
               .getDefault("logs.Jalview.level", Level.INFO.toString())));
@@ -528,21 +496,20 @@ public class Cache
     }
     new BuildDetails(codeVersion, null, codeInstallation);
 
-    SiftsSettings
-            .setMapWithSifts(Cache.getDefault("MAP_WITH_SIFTS", false));
+    SiftsSettings.setMapWithSifts(getDefault("MAP_WITH_SIFTS", false));
 
     SiftsSettings.setSiftDownloadDirectory(jalview.bin.Cache
             .getDefault("sifts_download_dir", DEFAULT_SIFTS_DOWNLOAD_DIR));
 
     SiftsSettings.setFailSafePIDThreshold(
-            jalview.bin.Cache.getDefault("sifts_fail_safe_pid_threshold",
+            getDefault("sifts_fail_safe_pid_threshold",
                     DEFAULT_FAIL_SAFE_PID_THRESHOLD));
 
     SiftsSettings.setCacheThresholdInDays(
-            jalview.bin.Cache.getDefault("sifts_cache_threshold_in_days",
+            getDefault("sifts_cache_threshold_in_days",
                     DEFAULT_CACHE_THRESHOLD_IN_DAYS));
 
-    IdOrgSettings.setUrl(getDefault("ID_ORG_HOSTURL",
+    IdOrgSettings.setUrl(getDefault(Preferences.ID_ORG_HOSTURL,
             "http://www.jalview.org/services/identifiers"));
     IdOrgSettings.setDownloadLocation(ID_ORG_FILE);
 
@@ -550,11 +517,11 @@ public class Cache
             .println("Jalview Version: " + codeVersion + codeInstallation);
 
     StructureImportSettings.setDefaultStructureFileFormat(jalview.bin.Cache
-            .getDefault("PDB_DOWNLOAD_FORMAT", PDB_DOWNLOAD_FORMAT));
+            .getDefault(Preferences.PDB_DOWNLOAD_FORMAT, PDB_DOWNLOAD_FORMAT));
     StructureImportSettings
             .setDefaultPDBFileParser(DEFAULT_PDB_FILE_PARSER);
     // StructureImportSettings
-    // .setDefaultPDBFileParser(jalview.bin.Cache.getDefault(
+    // .setDefaultPDBFileParser(jalview.bin.getDefault(
     // "DEFAULT_PDB_FILE_PARSER", DEFAULT_PDB_FILE_PARSER));
     // jnlpVersion will be null if we're using InstallAnywhere
     // Dont do this check if running in headless mode
@@ -630,13 +597,9 @@ public class Cache
     setProperty("VERSION", codeVersion);
 
     // LOAD USERDEFINED COLOURS
-    jalview.bin.Cache
-            .initUserColourSchemes(getProperty("USER_DEFINED_COLOURS"));
-    jalview.io.PIRFile.useModellerOutput = Cache.getDefault("PIR_MODELLER",
-            false);
+    initUserColourSchemes(getProperty(Preferences.USER_DEFINED_COLOURS));
   }
 
-
   private void deleteBuildProperties()
   {
     applicationProperties.remove("LATEST_VERSION");
@@ -659,59 +622,93 @@ public class Cache
    */
   public static String getProperty(String key)
   {
-    return getInstance().getPropertyImpl(key);
+    return getInstance().applicationProperties.getProperty(key);
   }
 
-  private String getPropertyImpl(String key)
+  /**
+   * Returns the boolean property value for the given property name. If the
+   * value is absent then the default value is returned instead.
+   * 
+   * @param property
+   * @param def
+   * @return
+   */
+  public static boolean getDefault(String property, final boolean def)
   {
-    String prop = applicationProperties.getProperty(key);
-    if (prop == null && Platform.isJS())
-    {
-      prop = applicationProperties.getProperty(Platform.getUniqueAppletID()
-              + "_" + JS_PROPERTY_PREFIX + key);
-    }
-    return prop;
+    String string = getProperty(property);
+    return string == null ? def : Boolean.parseBoolean(string);
   }
 
   /**
-   * These methods are used when checking if the saved preference is different
-   * to the default setting
+   * Returns the integer property value for the given property name. If the
+   * value is absent, or malformed (not an integer), then the default value is
+   * returned instead.
+   * 
+   * @param property
+   * @param def
+   * @return
    */
-
-  public static boolean getDefault(String property, boolean def)
+  public static int getDefault(String property, final int def)
   {
     String string = getProperty(property);
     if (string != null)
     {
-      def = Boolean.valueOf(string).booleanValue();
+      try
+      {
+        return Integer.parseInt(string);
+      } catch (NumberFormatException e)
+      {
+        System.out.println("Error parsing int property '" + property
+                + "' with value '" + string + "'");
+      }
     }
 
     return def;
   }
 
-  public static int getDefault(String property, int def)
+  /**
+   * retrieve a dimension, such as for Jmol
+   * 
+   * @param property
+   * @param def
+   * @return
+   */
+  public static Dimension getDefaultDim(String property, Dimension def)
   {
-    String string = getProperty(property);
-    if (string != null)
+    String s = getProperty(property);
+    if (s != null)
     {
+      if (s.indexOf(',') < 0)
+      {
+        s = s.trim().replace(' ', ',');
+        if (s.indexOf(',') < 0)
+        {
+          s += "," + s;
+        }
+      }
       try
       {
-        def = Integer.parseInt(string);
+        int pt = s.indexOf(",");
+        return new Dimension(Integer.parseInt(s.substring(0, pt)),
+                Integer.parseInt(s.substring(pt + 1)));
       } catch (NumberFormatException e)
       {
-        System.out.println("Error parsing int property '" + property
-                + "' with value '" + string + "'");
+        System.out.println("Error parsing Dimension property '" + property
+                + "' with value '" + s + "'");
       }
     }
-
     return def;
   }
 
   /**
-   * Answers the value of the given property, or the supplied default value if
+   * Returns the value of the given property, or the supplied default value if
    * the property is not set
+   * 
+   * @param property
+   * @param def
+   * @return
    */
-  public static String getDefault(String property, String def)
+  public static String getDefault(String property, final String def)
   {
     String value = getProperty(property);
     return value == null ? def : value;
@@ -732,18 +729,34 @@ public class Cache
     return getInstance().setPropertyImpl(key, obj, true);
   }
 
+  /**
+   * Sets a property value for the running application, without saving it to the
+   * properties file
+   * 
+   * @param key
+   * @param obj
+   */
   public static void setPropertyNoSave(String key, String obj)
   {
     getInstance().setPropertyImpl(key, obj, false);
   }
 
+  /**
+   * Sets a property value, and optionally also saves the current properties to
+   * file
+   * 
+   * @param key
+   * @param obj
+   * @param andSave
+   * @return
+   */
   private Object setPropertyImpl(String key, String obj, boolean andSave)
   {
     Object oldValue = null;
     try
     {
       oldValue = applicationProperties.setProperty(key, obj);
-      if (andSave && !propsAreReadOnly)
+      if (andSave && !propsAreReadOnly && propertiesFile != null)
       {
         FileOutputStream out = new FileOutputStream(propertiesFile);
         applicationProperties.store(out, "---JalviewX Properties File---");
@@ -758,7 +771,7 @@ public class Cache
   }
 
   /**
-   * remove the specified property from the jalview properties file
+   * Removes the specified property from the jalview properties file
    * 
    * @param key
    */
@@ -767,11 +780,24 @@ public class Cache
     getInstance().removePropertyImpl(key, true);
   }
 
+  /**
+   * Removes the named property for the running application, without saving the
+   * properties file
+   * 
+   * @param key
+   */
   public static void removePropertyNoSave(String key)
   {
     getInstance().removePropertyImpl(key, false);
   }
 
+  /**
+   * Removes the named property, and optionally saves the current properties to
+   * file
+   * 
+   * @param key
+   * @param andSave
+   */
   private void removePropertyImpl(String key, boolean andSave)
   {
     applicationProperties.remove(key);
@@ -781,6 +807,9 @@ public class Cache
     }
   }
 
+  /**
+   * Saves the current properties to file
+   */
   public static void saveProperties()
   {
     getInstance().savePropertiesImpl();
@@ -947,8 +976,7 @@ public class Cache
                 .newInstance(new Object[]
                 { "Jalview Desktop",
                     (vrs = jalview.bin.Cache.getProperty("VERSION") + "_"
-                            + jalview.bin.Cache.getDefault("BUILD_DATE",
-                                    "unknown")),
+                            + getDefault("BUILD_DATE", "unknown")),
                     "UA-9060947-1" });
         jgoogleanalyticstracker
                 .getMethod("trackAsynchronously", new Class[]
@@ -1025,18 +1053,24 @@ public class Cache
   }
 
   /**
-   * get the user's default colour if available
+   * Returns the Color value of the given property's value, or the supplied
+   * default colour if no property is found, or it cannot be parsed to a colour.
+   * Colours are normally saved as hex rgb values, though other formats may be
+   * parseable.
    * 
    * @param property
-   * @param defcolour
+   * @param defaultColour
    * @return
+   * @see Cache#setColourPropertyNoSave(String, Color)
+   * @see ColorUtils#parseColourString(String)
    */
-  public static Color getDefaultColour(String property, Color defcolour)
+  public static Color getDefaultColour(String property,
+          final Color defaultColour)
   {
     String colprop = getProperty(property);
     if (colprop == null)
     {
-      return defcolour;
+      return defaultColour;
     }
     Color col = ColorUtils.parseColourString(colprop);
     if (col == null)
@@ -1044,22 +1078,24 @@ public class Cache
       log.warn("Couldn't parse '" + colprop + "' as a colour for "
               + property);
     }
-    return (col == null) ? defcolour : col;
+    return (col == null) ? defaultColour : col;
   }
 
   /**
-   * store a colour as a Jalview user default property
+   * Stores a colour as a Jalview property, converted to hex values for rgb.
+   * Properties are not saved to file.
    * 
    * @param property
    * @param colour
    */
-  public static void setColourProperty(String property, Color colour)
+  public static void setColourPropertyNoSave(String property, Color colour)
   {
     setProperty(property, jalview.util.Format.getHexString(colour));
   }
 
   /**
    * Stores a formatted date in a jalview property, using a fixed locale.
+   * Updated properties are written out to the properties file.
    * 
    * @param propertyName
    * @param date
@@ -1185,13 +1221,13 @@ public class Cache
     {
       if (coloursFound.toString().length() > 1)
       {
-        setProperty(UserDefinedColours.USER_DEFINED_COLOURS,
+        setProperty(Preferences.USER_DEFINED_COLOURS,
                 coloursFound.toString());
       }
       else
       {
         getInstance().applicationProperties
-                .remove(UserDefinedColours.USER_DEFINED_COLOURS);
+                .remove(Preferences.USER_DEFINED_COLOURS);
       }
     }
   }