Exemple #1
0
  /**
   * Utility method which loads the given properties file and returns a Properties object containing
   * the key,value pairs in that file. The properties files should be in the class path as this
   * method looks to the thread context class loader (TCL) to locate the resource. If the TCL is a
   * URLClassLoader the findResource(String) method is first tried. If this fails or the TCL is not
   * a URLClassLoader getResource(String) is tried. If not, an absolute path is tried.
   *
   * @param propertiesName - the name of the properties file resource
   * @return the loaded properties file if found
   * @exception java.io.IOException thrown if the properties file cannot be found or loaded
   */
  static Properties loadProperties(String propertiesName) throws IOException {
    Properties bundle = null;
    ClassLoader loader = SecurityActions.getContextClassLoader();
    URL url = null;
    // First check for local visibility via a URLClassLoader.findResource
    if (loader instanceof URLClassLoader) {
      URLClassLoader ucl = (URLClassLoader) loader;
      url = SecurityActions.findResource(ucl, propertiesName);
      PicketBoxLogger.LOGGER.traceAttemptToLoadResource(propertiesName);
    }
    // Do a general resource search
    if (url == null) {
      url = loader.getResource(propertiesName);
      if (url == null) {
        try {
          url = new URL(propertiesName);
        } catch (MalformedURLException mue) {
          PicketBoxLogger.LOGGER.debugFailureToOpenPropertiesFromURL(mue);
          File tmp = new File(propertiesName);
          if (tmp.exists()) url = tmp.toURI().toURL();
        }
      }
    }
    if (url == null) {
      throw PicketBoxMessages.MESSAGES.unableToFindPropertiesFile(propertiesName);
    }

    Properties defaults = new Properties();
    bundle = new Properties(defaults);
    if (url != null) {
      InputStream is = null;
      try {
        is = SecurityActions.openStream(url);
      } catch (PrivilegedActionException e) {
        throw new IOException(e.getLocalizedMessage());
      }
      if (is != null) {
        try {
          bundle.load(is);
        } finally {
          safeClose(is);
        }
      } else {
        throw PicketBoxMessages.MESSAGES.unableToLoadPropertiesFile(propertiesName);
      }
      PicketBoxLogger.LOGGER.tracePropertiesFileLoaded(propertiesName, bundle.keySet());
    }

    return bundle;
  }