package de.renew.remote;

import java.rmi.server.RMISocketFactory;

import de.renew.plugin.PluginManager;


/**
 * Determines the RMI socket factory to be used for the remote package.
 * If the de.renew.remote.socketFactory Java VM property is specified,
 * this class is used, otherwise, the default factory is used.
 */
public class SocketFactoryDeterminer {

    /**
     * A Logger instance used for logging messages within the
     * {@link SocketFactoryDeterminer} class. This Logger is configured
     * to log messages related to the determination and instantiation
     * of custom RMI socket factories and other related processes.
     * It provides a consistent mechanism for capturing errors, debug
     * information, and other runtime messages that arise during the
     * factory determination process.
     */
    public static final org.apache.log4j.Logger LOGGER =
        org.apache.log4j.Logger.getLogger(SocketFactoryDeterminer.class);

    /**
     * The determined factory.
     */
    private static RMISocketFactory _factory = null;

    /**
     * Whether the socket factory property has already been read.
     */
    private static boolean _propertyRead = false;

    /**
     * Determines the RMI socket factory to be used for the remote package.
     * @return The determined factory.
     */
    public static RMISocketFactory getInstance() {
        if (!_propertyRead) {
            _propertyRead = true;
            String socketFactoryClassName = System.getProperty("de.renew.remote.socketFactory");
            if (socketFactoryClassName != null) {
                try {
                    _factory = (RMISocketFactory) Class.forName(
                        socketFactoryClassName, true,
                        PluginManager.getInstance().getBottomClassLoader()).newInstance();
                } catch (Exception e) {
                    LOGGER.error(
                        "Cannot instantiate custom socket factory " + socketFactoryClassName + ": "
                            + e + "\nUsing default factory.");
                }
            }
        }

        return _factory;
    }
}