package nl.tudelft.simulation.naming; import java.net.InetAddress; import java.net.URL; import java.rmi.ConnectException; import java.rmi.NotBoundException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.util.Hashtable; import java.util.Iterator; import javax.naming.Context; import javax.naming.event.EventContext; import javax.naming.spi.InitialContextFactory; import org.djutils.logger.CategoryLogger; /** * A factory for RemoteContextClient instances, automatically invoked by JNDI when the correct jndi.properties file has been * used. *
* Copyright (c) 2002-2019 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See * for project information https://simulation.tudelft.nl. The DSOL * project is distributed under a three-clause BSD-style license, which can be found at * * https://simulation.tudelft.nl/dsol/3.0/license.html. *
* @author Peter Jacobs * @author Alexander Verbraeck */ public class RemoteContextFactory implements InitialContextFactory { /** context refers to the static RemoteContextClient. */ private static RemoteContextClient context = null; /** {@inheritDoc} */ @Override public synchronized Context getInitialContext(final Hashtable extends Object, ? extends Object> environment) { // If the context is already looked up, let's return immediately if (RemoteContextFactory.context != null) { return RemoteContextFactory.context; } // Let's look for our remote partner try { URL url = new URL(environment.get(Context.PROVIDER_URL).toString()); Registry registry = LocateRegistry.getRegistry(url.getHost(), url.getPort()); // If there is no registry, registry!=null, so we have to test the // registry // to make sure whether there is one or not. We test by requesting a // list. This code // might be improved. try { registry.list(); } catch (ConnectException connectException) { // Since we cannot find the registry, we must perhaps create // one. // This is only allowed if the host is our localhost. We cannot // create a registry on a remote host. if (!(url.getHost().equals("localhost") || url.getHost().equals("127.0.0.1") || url.getHost().equals(InetAddress.getLocalHost().getHostName()) || url.getHost().equals(InetAddress.getLocalHost().getHostAddress()))) { throw new IllegalArgumentException("cannot create registry on remote host"); } registry = LocateRegistry.createRegistry(url.getPort()); } // We now have a registry. Let's resolve the context object RemoteContextInterface remoteContext = null; try { remoteContext = (RemoteContextInterface) registry.lookup(url.getFile()); } catch (NotBoundException notBoundException) { // Since we cannot find the context, we must create one. // This is done based on the java.naming.wrapped properties in // jndi.properties Hashtable