View Javadoc
1   package nl.tudelft.simulation.naming.context;
2   
3   import java.io.BufferedInputStream;
4   import java.io.File;
5   import java.io.FileInputStream;
6   import java.io.ObjectInputStream;
7   import java.net.URI;
8   import java.util.Hashtable;
9   
10  import org.djutils.logger.CategoryLogger;
11  
12  /**
13   * A factory for FileContext instances, automatically invoked by JNDI when the correct jndi.properties file has been used.
14   * <p>
15   * Copyright (c) 2002-2025 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
16   * for project information <a href="https://simulation.tudelft.nl/dsol/manual/" target="_blank">DSOL Manual</a>. The DSOL
17   * project is distributed under a three-clause BSD-style license, which can be found at
18   * <a href="https://simulation.tudelft.nl/dsol/docs/latest/license.html" target="_blank">DSOL License</a>.
19   * </p>
20   * @author <a href="https://www.linkedin.com/in/peterhmjacobs">Peter Jacobs </a>
21   * @author <a href="https://github.com/averbraeck">Alexander Verbraeck</a>
22   */
23  public class FileContextFactory implements ContextFactory
24  {
25      /** context refers to the static JvmContext. */
26      private static FileContext context = null;
27  
28      @Override
29      public synchronized ContextInterface getInitialContext(final Hashtable<?, ?> environment, final String atomicName)
30      {
31          if (context == null)
32          {
33              try
34              {
35                  URI fileURI = new URI(environment.get("java.naming.provider.url").toString());
36                  File file = new File(fileURI);
37                  if (file.exists())
38                  {
39                      ObjectInputStream stream = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file)));
40                      FileContextFactory.context = (FileContext) stream.readObject();
41                      stream.close();
42                  }
43                  else
44                  {
45                      FileContextFactory.context = new FileContext(file, atomicName);
46                  }
47              }
48              catch (Exception exception)
49              {
50                  CategoryLogger.always().error(exception, "getInitialContext");
51              }
52          }
53          return context;
54      }
55  }