Class FileHandler

java.lang.Object
org.apache.commons.configuration2.io.FileHandler

public class FileHandler extends Object

A class that manages persistence of an associated FileBased object.

Instances of this class can be used to load and save arbitrary objects implementing the FileBased interface in a convenient way from and to various locations. At construction time the FileBased object to manage is passed in. Basically, this object is assigned a location from which it is loaded and to which it can be saved. The following possibilities exist to specify such a location:

  • URLs: With the method setURL() a full URL to the configuration source can be specified. This is the most flexible way. Note that the save() methods support only file: URLs.
  • Files: The setFile() method allows to specify the configuration source as a file. This can be either a relative or an absolute file. In the former case the file is resolved based on the current directory.
  • As file paths in string form: With the setPath() method a full path to a configuration file can be provided as a string.
  • Separated as base path and file name: The base path is a string defining either a local directory or a URL. It can be set using the setBasePath() method. The file name, non surprisingly, defines the name of the configuration file.

An instance stores a location. The load() and save() methods that do not take an argument make use of this internal location. Alternatively, it is also possible to use overloaded variants of load() and save() which expect a location. In these cases the location specified takes precedence over the internal one; the internal location is not changed.

The actual position of the file to be loaded is determined by a FileLocationStrategy based on the location information that has been provided. By providing a custom location strategy the algorithm for searching files can be adapted. Save operations require more explicit information. They cannot rely on a location strategy because the file to be written may not yet exist. So there may be some differences in the way location information is interpreted by load and save operations. In order to avoid this, the following approach is recommended:

  • Use the desired setXXX() methods to define the location of the file to be loaded.
  • Call the locate() method. This method resolves the referenced file (if possible) and fills out all supported location information.
  • Later on, save() can be called. This method now has sufficient information to store the file at the correct location.

When loading or saving a FileBased object some additional functionality is performed if the object implements one of the following interfaces:

  • FileLocatorAware: In this case an object with the current file location is injected before the load or save operation is executed. This is useful for FileBased objects that depend on their current location, e.g. to resolve relative path names.
  • SynchronizerSupport: If this interface is implemented, load and save operations obtain a write lock on the FileBased object before they access it. (In case of a save operation, a read lock would probably be sufficient, but because of the possible injection of a FileLocator object it is not allowed to perform multiple save operations in parallel; therefore, by obtaining a write lock, we are on the safe side.)

This class is thread-safe.

Since:
2.0
  • Field Details

    • FILE_SCHEME

      private static final String FILE_SCHEME
      Constant for the URI scheme for files.
      See Also:
    • FILE_SCHEME_SLASH

      private static final String FILE_SCHEME_SLASH
      Constant for the URI scheme for files with slashes.
      See Also:
    • DUMMY_SYNC_SUPPORT

      private static final SynchronizerSupport DUMMY_SYNC_SUPPORT
      A dummy implementation of SynchronizerSupport. This object is used when the file handler's content does not implement the SynchronizerSupport interface. All methods are just empty dummy implementations.
    • content

      private final FileBased content
      The file-based object managed by this handler.
    • fileLocator

      private final AtomicReference<FileLocator> fileLocator
      A reference to the current FileLocator object.
    • listeners

      private final List<FileHandlerListener> listeners
      A collection with the registered listeners.
  • Constructor Details

    • FileHandler

      public FileHandler()
      Creates a new instance of FileHandler which is not associated with a FileBased object and thus does not have a content. Objects of this kind can be used to define a file location, but it is not possible to actually load or save data.
    • FileHandler

      public FileHandler(FileBased obj)
      Creates a new instance of FileHandler and sets the managed FileBased object.
      Parameters:
      obj - the file-based object to manage
    • FileHandler

      public FileHandler(FileBased obj, FileHandler c)
      Creates a new instance of FileHandler which is associated with the given FileBased object and the location defined for the given FileHandler object. A copy of the location of the given FileHandler is created. This constructor is a possibility to associate a file location with a FileBased object.
      Parameters:
      obj - the FileBased object to manage
      c - the FileHandler from which to copy the location (must not be null)
      Throws:
      IllegalArgumentException - if the FileHandler is null
    • FileHandler

      private FileHandler(FileBased obj, FileLocator locator)
      Creates a new instance of FileHandler based on the given FileBased and FileLocator objects.
      Parameters:
      obj - the FileBased object to manage
      locator - the FileLocator
  • Method Details

    • checkSourceHandler

      private static FileHandler checkSourceHandler(FileHandler c)
      Helper method for checking a file handler which is to be copied. Throws an exception if the handler is null.
      Parameters:
      c - the FileHandler from which to copy the location
      Returns:
      the same FileHandler
    • closeSilent

      private static void closeSilent(Closeable cl)
      A helper method for closing a stream. Occurring exceptions will be ignored.
      Parameters:
      cl - the stream to be closed (may be null)
    • createFile

      private static File createFile(FileLocator loc)
      Creates a File object from the content of the given FileLocator object. If the locator is not defined, result is null.
      Parameters:
      loc - the FileLocator
      Returns:
      a File object pointing to the associated file
    • emptyFileLocator

      private static FileLocator emptyFileLocator()
      Creates an uninitialized file locator.
      Returns:
      the locator
    • fromMap

      public static FileHandler fromMap(Map<String,?> map)
      Creates a new FileHandler instance from properties stored in a map. This method tries to extract a FileLocator from the map. A new FileHandler is created based on this FileLocator.
      Parameters:
      map - the map (may be null)
      Returns:
      the newly created FileHandler
      See Also:
    • normalizeFileURL

      private static String normalizeFileURL(String fileName)
      Normalizes URLs to files. Ensures that file URLs start with the correct protocol.
      Parameters:
      fileName - the string to be normalized
      Returns:
      the normalized file URL
    • addFileHandlerListener

      public void addFileHandlerListener(FileHandlerListener l)
      Adds a listener to this FileHandler. It is notified about property changes and IO operations.
      Parameters:
      l - the listener to be added (must not be null)
      Throws:
      IllegalArgumentException - if the listener is null
    • checkContent

      private void checkContent() throws ConfigurationException
      Checks whether a content object is available. If not, an exception is thrown. This method is called whenever the content object is accessed.
      Throws:
      ConfigurationException - if not content object is defined
    • checkContentAndGetLocator

      private FileLocator checkContentAndGetLocator() throws ConfigurationException
      Checks whether a content object is available and returns the current FileLocator. If there is no content object, an exception is thrown. This is a typical operation to be performed before a load() or save() operation.
      Returns:
      the current FileLocator to be used for the calling operation
      Throws:
      ConfigurationException - if not content object is defined
    • clearLocation

      public void clearLocation()
      Clears the location of this FileHandler. Afterwards this handler does not point to any valid file.
    • createLocatorWithFileName

      private FileLocator createLocatorWithFileName(String fileName, FileLocator locator)
      Creates a FileLocator which is a copy of the passed in one, but has the given file name set to reference the target file.
      Parameters:
      fileName - the file name
      locator - the FileLocator to copy
      Returns:
      the manipulated FileLocator with the file name
    • fetchSynchronizerSupport

      private SynchronizerSupport fetchSynchronizerSupport()
      Obtains a SynchronizerSupport for the current content. If the content implements this interface, it is returned. Otherwise, result is a dummy object. This method is called before load and save operations. The returned object is used for synchronization.
      Returns:
      the SynchronizerSupport for synchronization
    • fireLoadedEvent

      private void fireLoadedEvent()
      Notifies the registered listeners about a completed load operation.
    • fireLoadingEvent

      private void fireLoadingEvent()
      Notifies the registered listeners about the start of a load operation.
    • fireLocationChangedEvent

      private void fireLocationChangedEvent()
      Notifies the registered listeners about a property update.
    • fireSavedEvent

      private void fireSavedEvent()
      Notifies the registered listeners about a completed save operation.
    • fireSavingEvent

      private void fireSavingEvent()
      Notifies the registered listeners about the start of a save operation.
    • getBasePath

      public String getBasePath()
      Return the base path. If no base path is defined, but a URL, the base path is derived from there.
      Returns:
      the base path
    • getContent

      public final FileBased getContent()
      Gets the FileBased object associated with this FileHandler.
      Returns:
      the associated FileBased object
    • getEncoding

      public String getEncoding()
      Gets the encoding of the associated file. Result can be null if no encoding has been set.
      Returns:
      the encoding of the associated file
    • getFile

      public File getFile()
      Gets the location of the associated file as a File object. If the base path is a URL with a protocol different than "file", or the file is within a compressed archive, the return value will not point to a valid file object.
      Returns:
      the location as File object; this can be null
    • getFileLocator

      public FileLocator getFileLocator()
      Gets a FileLocator object with the specification of the file stored by this FileHandler. Note that this method returns the internal data managed by this FileHandler as it was defined. This is not necessarily the same as the data returned by the single access methods like getFileName() or getURL(): These methods try to derive missing data from other values that have been set.
      Returns:
      a FileLocator with the referenced file
    • getFileName

      public String getFileName()
      Return the name of the file. If only a URL is defined, the file name is derived from there.
      Returns:
      the file name
    • getFileSystem

      public FileSystem getFileSystem()
      Gets the FileSystem to be used by this object when locating files. Result is never null; if no file system has been set, the default file system is returned.
      Returns:
      the used FileSystem
    • getLocationStrategy

      public FileLocationStrategy getLocationStrategy()
      Gets the FileLocationStrategy to be applied when accessing the associated file. This method never returns null. If a FileLocationStrategy has been set, it is returned. Otherwise, result is the default FileLocationStrategy.
      Returns:
      the FileLocationStrategy to be used
    • getPath

      public String getPath()
      Gets the full path to the associated file. The return value is a valid File path only if this location is based on a file on the local disk. If the file was loaded from a packed archive, the returned value is the string form of the URL from which the file was loaded.
      Returns:
      the full path to the associated file
    • getURL

      public URL getURL()
      Gets the location of the associated file as a URL. If a URL is set, it is directly returned. Otherwise, an attempt to locate the referenced file is made.
      Returns:
      a URL to the associated file; can be null if the location is unspecified
    • injectFileLocator

      private void injectFileLocator(URL url)
      Injects a FileLocator pointing to the specified URL if the current FileBased object implements the FileLocatorAware interface.
      Parameters:
      url - the URL for the locator
    • injectNullFileLocator

      private void injectNullFileLocator()
      Checks whether the associated FileBased object implements the FileLocatorAware interface. If this is the case, a FileLocator instance is injected which returns only null values. This method is called if no file location is available (e.g. if data is to be loaded from a stream). The encoding of the injected locator is derived from this object.
    • isLocationDefined

      public boolean isLocationDefined()
      Tests whether a location is defined for this FileHandler.
      Returns:
      true if a location is defined, false otherwise
    • load

      public void load() throws ConfigurationException
      Loads the associated file from the underlying location. If no location has been set, an exception is thrown.
      Throws:
      ConfigurationException - if loading of the configuration fails
    • load

      public void load(File file) throws ConfigurationException
      Loads the associated file from the specified File.
      Parameters:
      file - the file to load
      Throws:
      ConfigurationException - if an error occurs
    • load

      private void load(FileLocator locator) throws ConfigurationException
      Internal helper method for loading the associated file from the location specified in the given FileLocator.
      Parameters:
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs
    • load

      public void load(InputStream in) throws ConfigurationException
      Loads the associated file from the specified stream, using the encoding returned by getEncoding().
      Parameters:
      in - the input stream
      Throws:
      ConfigurationException - if an error occurs during the load operation
    • load

      private void load(InputStream in, FileLocator locator) throws ConfigurationException
      Internal helper method for loading a file from the given input stream.
      Parameters:
      in - the input stream
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs
    • load

      public void load(InputStream in, String encoding) throws ConfigurationException
      Loads the associated file from the specified stream, using the specified encoding. If the encoding is null, the default encoding is used.
      Parameters:
      in - the input stream
      encoding - the encoding used, null to use the default encoding
      Throws:
      ConfigurationException - if an error occurs during the load operation
    • load

      public void load(Reader in) throws ConfigurationException
      Loads the associated file from the specified reader.
      Parameters:
      in - the reader
      Throws:
      ConfigurationException - if an error occurs during the load operation
    • load

      public void load(String fileName) throws ConfigurationException
      Loads the associated file from the given file name. The file name is interpreted in the context of the already set location (e.g. if it is a relative file name, a base path is applied if available). The underlying location is not changed.
      Parameters:
      fileName - the name of the file to be loaded
      Throws:
      ConfigurationException - if an error occurs
    • load

      private void load(String fileName, FileLocator locator) throws ConfigurationException
      Internal helper method for loading a file from a file name.
      Parameters:
      fileName - the file name
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs
    • load

      public void load(URL url) throws ConfigurationException
      Loads the associated file from the specified URL. The location stored in this object is not changed.
      Parameters:
      url - the URL of the file to be loaded
      Throws:
      ConfigurationException - if an error occurs
    • load

      private void load(URL url, FileLocator locator) throws ConfigurationException
      Internal helper method for loading a file from the given URL.
      Parameters:
      url - the URL
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs
    • loadFromReader

      private void loadFromReader(Reader in) throws ConfigurationException
      Internal helper method for loading a file from the given reader.
      Parameters:
      in - the reader
      Throws:
      ConfigurationException - if an error occurs
    • loadFromStream

      private void loadFromStream(InputStream in, String encoding, URL url) throws ConfigurationException
      Internal helper method for loading a file from an input stream.
      Parameters:
      in - the input stream
      encoding - the encoding
      url - the URL of the file to be loaded (if known)
      Throws:
      ConfigurationException - if an error occurs
    • loadFromStreamDirectly

      private void loadFromStreamDirectly(InputStream in) throws ConfigurationException
      Loads data from an input stream if the associated FileBased object implements the InputStreamSupport interface.
      Parameters:
      in - the input stream
      Throws:
      ConfigurationException - if an error occurs
    • loadFromTransformedStream

      private void loadFromTransformedStream(InputStream in, String encoding) throws ConfigurationException
      Internal helper method for transforming an input stream to a reader and reading its content.
      Parameters:
      in - the input stream
      encoding - the encoding
      Throws:
      ConfigurationException - if an error occurs
    • locate

      public boolean locate()
      Locates the referenced file if necessary and ensures that the associated FileLocator is fully initialized. When accessing the referenced file the information stored in the associated FileLocator is used. If this information is incomplete (e.g. only the file name is set), an attempt to locate the file may have to be performed on each access. By calling this method such an attempt is performed once, and the results of a successful localization are stored. Hence, later access to the referenced file can be more efficient. Also, all properties pointing to the referenced file in this object's FileLocator are set (i.e. the URL, the base path, and the file name). If the referenced file cannot be located, result is false. This means that the information in the current FileLocator is insufficient or wrong. If the FileLocator is already fully defined, it is not changed.
      Returns:
      a flag whether the referenced file could be located successfully
      See Also:
    • prepareNullLocatorBuilder

      private FileLocator.FileLocatorBuilder prepareNullLocatorBuilder()
      Prepares a builder for a FileLocator which does not have a defined file location. Other properties (e.g. encoding or file system) are initialized from the FileLocator associated with this object.
      Returns:
      the initialized builder for a FileLocator
    • removeFileHandlerListener

      public void removeFileHandlerListener(FileHandlerListener l)
      Removes the specified listener from this object.
      Parameters:
      l - the listener to be removed
    • resetFileSystem

      public void resetFileSystem()
      Resets the FileSystem used by this object. It is set to the default file system.
    • save

      public void save() throws ConfigurationException
      Saves the associated file to the current location set for this object. Before this method can be called a valid location must have been set.
      Throws:
      ConfigurationException - if an error occurs or no location has been set yet
    • save

      public void save(File file) throws ConfigurationException
      Saves the associated file to the specified File. The file is created automatically if it doesn't exist. This does not change the location of this object (use setFile(java.io.File) if you need it).
      Parameters:
      file - the target file
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      private void save(File file, FileLocator locator) throws ConfigurationException
      Internal helper method for saving data to the given File.
      Parameters:
      file - the target file
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      private void save(FileLocator locator) throws ConfigurationException
      Internal helper method for saving data to the internal location stored for this object.
      Parameters:
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      public void save(OutputStream out) throws ConfigurationException
      Saves the associated file to the specified stream using the encoding returned by getEncoding().
      Parameters:
      out - the output stream
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      private void save(OutputStream out, FileLocator locator) throws ConfigurationException
      Internal helper method for saving a file to the given output stream.
      Parameters:
      out - the output stream
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      public void save(OutputStream out, String encoding) throws ConfigurationException
      Saves the associated file to the specified stream using the specified encoding. If the encoding is null, the default encoding is used.
      Parameters:
      out - the output stream
      encoding - the encoding to be used, null to use the default encoding
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      public void save(String fileName) throws ConfigurationException
      Saves the associated file to the specified file name. This does not change the location of this object (use setFileName(String) if you need it).
      Parameters:
      fileName - the file name
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      private void save(String fileName, FileLocator locator) throws ConfigurationException
      Internal helper method for saving data to the given file name.
      Parameters:
      fileName - the path to the target file
      locator - the current FileLocator
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      public void save(URL url) throws ConfigurationException
      Saves the associated file to the specified URL. This does not change the location of this object (use setURL(URL) if you need it).
      Parameters:
      url - the URL
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      private void save(URL url, FileLocator locator) throws ConfigurationException
      Internal helper method for saving data to the given URL.
      Parameters:
      url - the target URL
      locator - the FileLocator
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • save

      public void save(Writer out) throws ConfigurationException
      Saves the associated file to the given Writer.
      Parameters:
      out - the Writer
      Throws:
      ConfigurationException - if an error occurs during the save operation
    • saveToStream

      private void saveToStream(OutputStream out, String encoding, URL url) throws ConfigurationException
      Internal helper method for saving a file to the given stream.
      Parameters:
      out - the output stream
      encoding - the encoding
      url - the URL of the output file if known
      Throws:
      ConfigurationException - if an error occurs
    • saveToWriter

      private void saveToWriter(Writer out) throws ConfigurationException
      Internal helper method for saving a file into the given writer.
      Parameters:
      out - the writer
      Throws:
      ConfigurationException - if an error occurs
    • setBasePath

      public void setBasePath(String basePath)
      Sets the base path. The base path is typically either a path to a directory or a URL. Together with the value passed to the setFileName() method it defines the location of the configuration file to be loaded. The strategies for locating the file are quite tolerant. For instance if the file name is already an absolute path or a fully defined URL, the base path will be ignored. The base path can also be a URL, in which case the file name is interpreted in this URL's context. If other methods are used for determining the location of the associated file (e.g. setFile() or setURL()), the base path is automatically set. Setting the base path using this method automatically sets the URL to null because it has to be determined anew based on the file name and the base path.
      Parameters:
      basePath - the base path.
    • setEncoding

      public void setEncoding(String encoding)
      Sets the encoding of the associated file. The encoding applies if binary files are loaded. Note that in this case setting an encoding is recommended; otherwise the platform's default encoding is used.
      Parameters:
      encoding - the encoding of the associated file
    • setFile

      public void setFile(File file)
      Sets the location of the associated file as a File object. The passed in File is made absolute if it is not yet. Then the file's path component becomes the base path and its name component becomes the file name.
      Parameters:
      file - the location of the associated file
    • setFileLocator

      public void setFileLocator(FileLocator locator)
      Sets the file to be accessed by this FileHandler as a FileLocator object.
      Parameters:
      locator - the FileLocator with the definition of the file to be accessed (must not be null
      Throws:
      IllegalArgumentException - if the FileLocator is null
    • setFileName

      public void setFileName(String fileName)
      Set the name of the file. The passed in file name can contain a relative path. It must be used when referring files with relative paths from classpath. Use setPath() to set a full qualified file name. The URL is set to null as it has to be determined anew based on the file name and the base path.
      Parameters:
      fileName - the name of the file
    • setFileSystem

      public void setFileSystem(FileSystem fileSystem)
      Sets the FileSystem to be used by this object when locating files. If a null value is passed in, the file system is reset to the default file system.
      Parameters:
      fileSystem - the FileSystem
    • setLocationStrategy

      public void setLocationStrategy(FileLocationStrategy strategy)
      Sets the FileLocationStrategy to be applied when accessing the associated file. The strategy is stored in the underlying FileLocator. The argument can be null; this causes the default FileLocationStrategy to be used.
      Parameters:
      strategy - the FileLocationStrategy
      See Also:
    • setPath

      public void setPath(String path)
      Sets the location of the associated file as a full or relative path name. The passed in path should represent a valid file name on the file system. It must not be used to specify relative paths for files that exist in classpath, either plain file system or compressed archive, because this method expands any relative path to an absolute one which may end in an invalid absolute path for classpath references.
      Parameters:
      path - the full path name of the associated file
    • setURL

      public void setURL(URL url)
      Sets the location of the associated file as a URL. For loading this can be an arbitrary URL with a supported protocol. If the file is to be saved, too, a URL with the "file" protocol should be provided. This method sets the file name and the base path to null. They have to be determined anew based on the new URL.
      Parameters:
      url - the location of the file as URL
    • setURL

      public void setURL(URL url, URLConnectionOptions urlConnectionOptions)
      Sets the location of the associated file as a URL. For loading this can be an arbitrary URL with a supported protocol. If the file is to be saved, too, a URL with the "file" protocol should be provided. This method sets the file name and the base path to null. They have to be determined anew based on the new URL.
      Parameters:
      url - the location of the file as URL
      urlConnectionOptions - URL connection options
      Since:
      2.8.0