All Downloads are FREE. Search and download functionalities are using the official Maven repository.

loci.common.services.ServiceFactory Maven / Gradle / Ivy

The newest version!
/*
 * #%L
 * Common package for I/O and related utilities
 * %%
 * Copyright (C) 2005 - 2016 Open Microscopy Environment:
 *   - Board of Regents of the University of Wisconsin-Madison
 *   - Glencoe Software, Inc.
 *   - University of Dundee
 * %%
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * 
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 *    this list of conditions and the following disclaimer in the documentation
 *    and/or other materials provided with the distribution.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 * #L%
 */

package loci.common.services;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Runtime instantiation of services.
 */
public class ServiceFactory {

  /** Logger for this class. */
  private static final Logger LOGGER =
    LoggerFactory.getLogger(ServiceFactory.class);

  /** Default service properties file. */
  private static final String DEFAULT_PROPERTIES_FILE = "services.properties";

  /** Constructor cache. */
  private static Map, Constructor>
    constructorCache =
      new HashMap, Constructor>();

  /**
   *  Set of available services.
   *
   *  This field is initialized on first usage since if this class has been deserialized,
   *  the transient flag will have led to it being null again.
   */
  private transient Map, Class>
    services = null;

  /**
   * Constructor argument passed.
   *
   * If null, then the default constructor was used. This information is used to
   * recreate the services instance.
   */
  private String path;

  /** Default service factory. */
  private static ServiceFactory defaultFactory;

  /**
   * Constructor loading service configuration from the default location.
   * @throws DependencyException If there is an error locating or reading from
   * the default configuration location.
   */
  public ServiceFactory() throws DependencyException {
    this.path = null;
    if (defaultFactory == null) {
      defaultFactory = new ServiceFactory(DEFAULT_PROPERTIES_FILE);
    }
    services();
  }

  /**
   * Constructor loading service configuration from a given location.
   * @param path Location to load service configuration from.
   * @throws DependencyException If there is an error locating or reading from
   * path.
   */
  public ServiceFactory(String path) throws DependencyException {
    this.path = path;
    services();
  }

  /**
   * Common constructor code which dispatches based on the state of
   * the path field. This is *not* called during construction, but
   * rather on the first call to services() since the same logic is
   * needed in the deserialization code path. This way, it's only called
   * once.
   */
  private static void init(String path,
    Map, Class> services)
      throws DependencyException {

    // Matches the default constructor
    if (path == null) {
      synchronized (defaultFactory) {
        services.putAll(defaultFactory.services);
      }
      return; // EARLY EXIT
    }

    // Now handle the (String path) constructor.

    InputStream stream = ServiceFactory.class.getResourceAsStream(path);
    Properties properties = new Properties();
    if (stream == null) {
      throw new DependencyException(path + " not found on CLASSPATH");
    }
    try {
      properties.load(stream);
      LOGGER.debug("Loaded properties from: {}", path);
    } catch (Throwable t) {
      throw new DependencyException(t);
    }
    finally {
      try {
        stream.close();
      }
      catch (IOException e) {
        LOGGER.warn("Error closing properties file stream.", e);
      }
    }
    Set> entries = properties.entrySet();
    for (Entry entry : entries) {
      String interfaceName = (String) entry.getKey();
      String implementationName = (String) entry.getValue();
      Class interfaceClass = null;
      Class implementationClass = null;
      ClassLoader loader = ServiceFactory.class.getClassLoader();
      try {
        interfaceClass = (Class)
          Class.forName(interfaceName, false, loader);
      }
      catch (Throwable t) {
        LOGGER.debug("CLASSPATH missing interface: {}", interfaceName, t);
        continue;
      }
      try {
        implementationClass = (Class)
          Class.forName(implementationName, false, loader);
      }
      catch (Throwable t) {
        LOGGER.debug(
          "CLASSPATH missing implementation or implementation dependency: {}",
          implementationName, t);
      }
      services.put(interfaceClass, implementationClass);
      LOGGER.debug("Added interface {} and implementation {}",
        interfaceClass, implementationClass);
    }
  }

  /**
   * Retrieves an instance of a given service.
   * @param  generic service type
   * @param type Interface type of the service.
   * @return A newly instantiated service.
   * @throws DependencyException If there is an error instantiating the
   * service instance requested.
   */
  public  T getInstance(Class type)
    throws DependencyException
  {
    Class impl = (Class) services().get(type);
    if (impl == null && services().containsKey(type)) {
      throw new DependencyException(
          "Unable to instantiate service. Missing implementation or " +
          "implementation dependency", type);
    }
    if (impl == null) {
      throw new DependencyException("Unknown service type: " + type);
    }
    Constructor constructor = getConstructor(impl);
    try {
      return constructor.newInstance();
    } catch (Throwable t) {
      throw new DependencyException("Unable to instantiate service", type, t);
    }
  }

  /**
   * Retrieves a constructor for a given class from the constructor cache if
   * possible.
   * @param klass Class to retrieve a constructor for.
   * @return See above.
   * @throws DependencyException If there is an error retrieving the
   * constructor.
   */
  private  Constructor getConstructor(Class klass)
    throws DependencyException
  {
    synchronized (constructorCache) {
      Constructor constructor =
        constructorCache.get(klass);
      if (constructor == null) {
        try {
          Class concreteClass = (Class) Class.forName(klass.getName());
          constructor = concreteClass.getDeclaredConstructor();
          constructorCache.put(klass, constructor);
        }
        catch (Throwable t) {
          throw new DependencyException(
              "Unable to retrieve constructor", klass, t);
        }
      }
      return (Constructor) constructor;
    }
  }

  /**
   * Called by all *users* of the services field in order to handle field initialization.
   * @return never null
   * @throws DependencyException
   */
  private Map, Class> services() throws DependencyException {

    // double-locking pattern
    Map, Class> copy = services;
    if (null == copy) {
      synchronized (this) {
        copy = services; // recheck
        if (copy == null) {
          copy = new HashMap<>();
          init(path, copy);
          services = copy;
        }
      }
    }
    return copy;
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy