net.i2p

## Class I2PAppContext

- java.lang.Object
- - net.i2p.I2PAppContext

- Direct Known Subclasses:
    RouterContext

      public class I2PAppContext
      extends Object

  Provide a base scope for accessing singletons that I2P exposes. Rather than using the traditional singleton, where any component can access the component in question directly, all of those I2P related singletons are exposed through a particular I2PAppContext. This helps not only with understanding their use and the components I2P exposes, but it also allows multiple isolated environments to operate concurrently within the same JVM - particularly useful for stubbing out implementations of the rooted components and simulating the software's interaction between multiple instances.

  As a simplification, there is also a global context - if some component needs access to one of the singletons but doesn't have its own context from which to root itself, it binds to the I2PAppContext's globalAppContext(), which is the first context that was created within the JVM, or a new one if no context existed already. This functionality is often used within the I2P core for logging - e.g.

           private static final Log _log = new Log(someClass.class);

  It is for this reason that applications that care about working with multiple contexts should build their own context as soon as possible (within the main(..)) so that any referenced components will latch on to that context instead of instantiating a new one. However, there are situations in which both can be relevant.

- - ### Field Summary

    Fields
    Modifier and Type | Field and Description
    --- | ---
    `protected Clock` | `_clock`
    `protected boolean` | `_clockInitialized`
    `protected static I2PAppContext` | `_globalAppContext` the context that components without explicit root are bound
    `protected KeyRing` | `_keyRing`
    `protected boolean` | `_keyRingInitialized`
    `protected I2PProperties` | `_overrideProps`
    `protected SessionKeyManager` | `_sessionKeyManager`
    `protected boolean` | `_sessionKeyManagerInitialized`
    `protected Set<Runnable>` | `_shutdownTasks`

  - ### Constructor Summary

    Constructors
    Modifier | Constructor and Description
    --- | ---
    `` | `I2PAppContext()` Create a brand new context.
    `protected` | `I2PAppContext(boolean doInit, Properties envProps)` Create a brand new context.
    `` | `I2PAppContext(Properties envProps)` Create a brand new context.

  - ### Method Summary

    All Methods Static Methods Instance Methods Concrete Methods
    Modifier and Type | Method and Description
    --- | ---
    `void` | `addPropertyCallback(I2PProperties.I2PPropertyCallback callback)` Add a callback, which will fire upon changes in the property given in the specific callback.
    `void` | `addShutdownTask(Runnable task)` WARNING - Shutdown tasks are not executed in an I2PAppContext.
    `AESEngine` | `aes()` Ok, I'll admit it, there is no good reason for having a context specific AES engine.
    `ClientAppManager` | `clientAppManager()` As of 0.9.30, returns non-null in I2PAppContext, null in RouterContext.
    `Clock` | `clock()` The context's synchronized clock, which is kept context specific only to enable simulators to play with clock skew among different instances.
    `void` | `deleteTempDir()` don't rely on deleteOnExit()
    `DSAEngine` | `dsa()` Our DSA engine (see HMAC and SHA above)
    `net.i2p.crypto.ElGamalEngine` | `elGamalEngine()` This is the ElGamal engine used within this context.
    `File` | `getAppDir()` Where applications may store data.
    `File` | `getBaseDir()` This is the installation dir, often referred to as $I2P.
    `boolean` | `getBooleanProperty(String propName)` Default false
    `boolean` | `getBooleanPropertyDefaultTrue(String propName)` Get a boolean property, defaulting to true if not set.
    `File` | `getConfigDir()` The base dir for config files.
    `static I2PAppContext` | `getCurrentContext()` Pull the default context, WITHOUT creating a new one.
    `long` | `getEstimatedDowntime()` How long this router was down before it started, or 0 if unknown.
    `static I2PAppContext` | `getGlobalContext()` Pull the default context, creating a new one if necessary, else using the first one created.
    `File` | `getLibDir()` This is the library dir, which is usually $I2P/lib.
    `File` | `getLogDir()` Where the router keeps its log directory.
    `File` | `getPIDDir()` Where router.ping goes.
    `Properties` | `getProperties()` Access the configuration attributes of this context, listing the properties provided during the context construction, as well as the ones included in System.getProperties.
    `String` | `getProperty(String propName)` Access the configuration attributes of this context, using properties provided during the context construction, or falling back on System.getProperty if no properties were provided during construction (or the specified prop wasn't included).
    `boolean` | `getProperty(String propName, boolean defaultVal)` Return a boolean with a boolean default
    `float` | `getProperty(String propName, float defaultVal)` Return a float with a float default
    `int` | `getProperty(String propName, int defaultVal)` Return an int with an int default
    `long` | `getProperty(String propName, long defaultVal)` Return a long with a long default
    `String` | `getProperty(String propName, String defaultValue)` Access the configuration attributes of this context, using properties provided during the context construction, or falling back on System.getProperty if no properties were provided during construction (or the specified prop wasn't included).
    `Set<String>` | `getPropertyNames()` Access the configuration attributes of this context, listing the properties provided during the context construction, as well as the ones included in System.getProperties.
    `File` | `getRouterDir()` Where the router keeps its files.
    `Set<Runnable>` | `getShutdownTasks()` Get the list of shutdown tasks.
    `File` | `getTempDir()` Where anybody may store temporary data.
    `boolean` | `hasWrapper()` Is the wrapper present?
    `HMAC256Generator` | `hmac256()` Un-deprecated in 0.9.38
    `protected void` | `initializeClock()`
    `protected void` | `initializeKeyRing()`
    `protected void` | `initializeSessionKeyManager()`
    `InternalClientManager` | `internalClientManager()` Use this to connect to the router in the same JVM.
    `boolean` | `isRouterContext()` Use this instead of context instanceof RouterContext
    `KeyGenerator` | `keyGenerator()` Component to generate ElGamal, DSA, and Session keys.
    `KeyRing` | `keyRing()` Basic hash map
    `LogManager` | `logManager()` Query the log manager for this context, which may in turn have its own set of configuration settings (loaded from the context's properties).
    `NamingService` | `namingService()` Pull up the naming service used in this context.
    `PortMapper` | `portMapper()` Basic mapping from service names to ports
    `RandomSource` | `random()` [insert snarky comment here]
    `void` | `removeShutdownTask(Runnable task)` Remove a shutdown task.
    `RoutingKeyGenerator` | `routingKeyGenerator()` Determine how much do we want to mess with the keys to turn them into something we can route.
    `SessionKeyManager` | `sessionKeyManager()` The session key manager which coordinates the sessionKey / sessionTag data.
    `protected static boolean` | `setGlobalContext(I2PAppContext ctx)` Sets the default context, unless there is one already.
    `void` | `setLogManager(LogManager logManager)` Overwrites the LogManager instance to be used by the router.
    `SHA256Generator` | `sha()` Our SHA256 instance (see the hmac discussion for why its context specific)
    `SimpleTimer2` | `simpleTimer2()` Use instead of SimpleTimer2.getInstance()
    `StatManager` | `statManager()` The statistics component with which we can track various events over time.

    - ### Methods inherited from class java.lang.Object

      `clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait`

- - ### Field Detail

    - #### _clock

          protected Clock _clock

    - #### _clockInitialized

          protected volatile boolean _clockInitialized

    - #### _globalAppContext

          protected static volatile I2PAppContext _globalAppContext

      the context that components without explicit root are bound

    - #### _keyRing

          protected KeyRing _keyRing

    - #### _keyRingInitialized

          protected volatile boolean _keyRingInitialized

    - #### _overrideProps

          protected final I2PProperties _overrideProps

    - #### _sessionKeyManager

          protected SessionKeyManager _sessionKeyManager

    - #### _sessionKeyManagerInitialized

          protected volatile boolean _sessionKeyManagerInitialized

    - #### _shutdownTasks

          protected final Set<Runnable> _shutdownTasks

  - ### Constructor Detail

    - #### I2PAppContext

          public I2PAppContext()

      Create a brand new context. WARNING: In almost all cases, you should use getGlobalContext() instead, to avoid creating additional contexts, which may spawn numerous additional resources and threads, and may be the cause of logging problems or hard-to-isolate bugs.

    - #### I2PAppContext

          protected I2PAppContext(boolean doInit,
                                  Properties envProps)

      Create a brand new context. WARNING: In almost all cases, you should use getGlobalContext() instead, to avoid creating additional contexts, which may spawn numerous additional resources and threads, and may be the cause of logging problems or hard-to-isolate bugs. NOT a public API, for use by RouterContext only, NOT for external use.
      Parameters:
        `doInit` - should this context be used as the global one (if necessary)? Will only apply if there is no global context now.

    - #### I2PAppContext

          public I2PAppContext(Properties envProps)

      Create a brand new context. WARNING: In almost all cases, you should use getGlobalContext() instead, to avoid creating additional contexts, which may spawn numerous additional resources and threads, and may be the cause of logging problems or hard-to-isolate bugs.

  - ### Method Detail

    - #### addPropertyCallback

          public void addPropertyCallback(I2PProperties.I2PPropertyCallback callback)

      Add a callback, which will fire upon changes in the property given in the specific callback. Unimplemented in I2PAppContext: this only makes sense in a router context.
      Parameters:
        `callback` - The implementation of the callback.

    - #### addShutdownTask

          public void addShutdownTask(Runnable task)

      WARNING - Shutdown tasks are not executed in an I2PAppContext. You must be in a RouterContext for the tasks to be executed at shutdown. This method moved from Router in 0.7.1 so that clients may use it without depending on router.jar.

    - #### aes

          public AESEngine aes()

      Ok, I'll admit it, there is no good reason for having a context specific AES engine. We don't really keep stats on it, since its just too fast to matter. Though for the crazy people out there, we do expose a way to disable it.

    - #### clientAppManager

          public ClientAppManager clientAppManager()

      As of 0.9.30, returns non-null in I2PAppContext, null in RouterContext. Prior to that, returned null always. Overridden in RouterContext to return the RouterAppManager.
      Returns:
        As of 0.9.30, returns non-null in I2PAppContext, null in RouterContext

    - #### clock

          public Clock clock()

      The context's synchronized clock, which is kept context specific only to enable simulators to play with clock skew among different instances.

    - #### deleteTempDir

          public void deleteTempDir()

      don't rely on deleteOnExit()

    - #### dsa

          public DSAEngine dsa()

      Our DSA engine (see HMAC and SHA above)

    - #### elGamalEngine

          public net.i2p.crypto.ElGamalEngine elGamalEngine()

      This is the ElGamal engine used within this context. While it doesn't really have anything substantial that is context specific (the algorithm just does the algorithm), it does transparently use the context for logging its performance and activity. In addition, the engine can be swapped with the context's properties (though only someone really crazy should mess with it ;)

    - #### getAppDir

          public File getAppDir()

      Where applications may store data. The same as the config dir for now, but may change in the future. Apps should be careful not to overwrite router files.
      Returns:
        dir constant for the life of the context

    - #### getBaseDir

          public File getBaseDir()

      This is the installation dir, often referred to as $I2P. Applilcations should consider this directory read-only and never attempt to write to it. It may actually be read-only on a multi-user installation. The config files in this directory are templates for user installations and should not be accessed by applications. The only thing that may be useful in here is the lib/ dir containing the .jars.
      Returns:
        dir constant for the life of the context

    - #### getBooleanProperty

          public boolean getBooleanProperty(String propName)

      Default false

    - #### getBooleanPropertyDefaultTrue

          public boolean getBooleanPropertyDefaultTrue(String propName)

      Get a boolean property, defaulting to true if not set.
      Parameters:
        `propName` - the property name
      Returns:
        the boolean value, or true if the property is not set

    - #### getConfigDir

          public File getConfigDir()

      The base dir for config files. Applications may use this to access router configuration files if necessary. Usually ~/.i2p on Linux and %APPDIR%\I2P on Windows. In installations originally installed with 0.7.5 or earlier, and in "portable" installations, this will be the same as the base dir.
      Returns:
        dir constant for the life of the context

    - #### getCurrentContext

          public static I2PAppContext getCurrentContext()

      Pull the default context, WITHOUT creating a new one. Use this in static methods used early in router initialization, where creating a context messes things up.
      Returns:
        context or null

    - #### getEstimatedDowntime

          public long getEstimatedDowntime()

      How long this router was down before it started, or 0 if unknown. This may be used for a determination of whether to regenerate keys, for example. We use the timestamp of the previous ping file left behind on crash, as set by isOnlyRouterRunning(), if present. Otherwise, the last STOPPED entry in the event log. May take a while to run the first time, if it has to go through the event log. Once called, the result is cached.
      Returns:
        0 always in app context

    - #### getGlobalContext

          public static I2PAppContext getGlobalContext()

      Pull the default context, creating a new one if necessary, else using the first one created. Warning - do not save the returned value, or the value of any methods below, in a static field, or you will get the old context if a new router is started in the same JVM after the first is shut down, e.g. on Android.

    - #### getLibDir

          public File getLibDir()

      This is the library dir, which is usually $I2P/lib. It contains all the jars (i.e. the classpath). Most applications will not need this, and must treat this directory as read-only.
      Returns:
        dir constant for the life of the context

    - #### getLogDir

          public File getLogDir()

      Where the router keeps its log directory. Applications should not use this. The same as the config dir for now. (i.e. ~/.i2p, NOT ~/.i2p/logs)
      Returns:
        dir constant for the life of the context

    - #### getPIDDir

          public File getPIDDir()

      Where router.ping goes. Applications should not use this. The same as the router dir by default as of 0.8.12 Was the same as the system temp dir prior to that. Which was a problem for multi-user installations.
      Returns:
        dir constant for the life of the context

    - #### getProperties

          public Properties getProperties()

      Access the configuration attributes of this context, listing the properties provided during the context construction, as well as the ones included in System.getProperties.
      Returns:
        new Properties with system and context properties

    - #### getProperty

          public String getProperty(String propName)

      Access the configuration attributes of this context, using properties provided during the context construction, or falling back on System.getProperty if no properties were provided during construction (or the specified prop wasn't included).

    - #### getProperty

          public boolean getProperty(String propName,
                                     boolean defaultVal)

      Return a boolean with a boolean default

    - #### getProperty

          public float getProperty(String propName,
                                   float defaultVal)

      Return a float with a float default

    - #### getProperty

          public int getProperty(String propName,
                                 int defaultVal)

      Return an int with an int default

    - #### getProperty

          public long getProperty(String propName,
                                  long defaultVal)

      Return a long with a long default

    - #### getProperty

          public String getProperty(String propName,
                                    String defaultValue)

      Access the configuration attributes of this context, using properties provided during the context construction, or falling back on System.getProperty if no properties were provided during construction (or the specified prop wasn't included).

    - #### getPropertyNames

          public Set<String> getPropertyNames()

      Access the configuration attributes of this context, listing the properties provided during the context construction, as well as the ones included in System.getProperties. WARNING - not overridden in RouterContext, doesn't contain router config settings, use getProperties() instead.
      Returns:
        set of Strings containing the names of defined system properties

    - #### getRouterDir

          public File getRouterDir()

      Where the router keeps its files. Applications should not use this. The same as the config dir for now.
      Returns:
        dir constant for the life of the context

    - #### getShutdownTasks

          public Set<Runnable> getShutdownTasks()

      Get the list of shutdown tasks.
      Returns:
        an unmodifiable Set of shutdown tasks

    - #### getTempDir

          public File getTempDir()

      Where anybody may store temporary data. This is a directory created in the system temp dir on the first call in this context, and is deleted on JVM exit. Applications should create their own directory inside this directory to avoid collisions with other apps.
      Returns:
        dir constant for the life of the context

    - #### hasWrapper

          public boolean hasWrapper()

      Is the wrapper present?

    - #### hmac256

          public HMAC256Generator hmac256()

      Un-deprecated in 0.9.38

    - #### initializeClock

          protected void initializeClock()

    - #### initializeKeyRing

          protected void initializeKeyRing()

    - #### initializeSessionKeyManager

          protected void initializeSessionKeyManager()

    - #### internalClientManager

          public InternalClientManager internalClientManager()

      Use this to connect to the router in the same JVM.
      Returns:
        always null in I2PAppContext, the client manager if in RouterContext

    - #### isRouterContext

          public boolean isRouterContext()

      Use this instead of context instanceof RouterContext

    - #### keyGenerator

          public KeyGenerator keyGenerator()

      Component to generate ElGamal, DSA, and Session keys. For why it is in the appContext, see the DSA, HMAC, and SHA comments above.

    - #### keyRing

          public KeyRing keyRing()

      Basic hash map

    - #### logManager

          public LogManager logManager()

      Query the log manager for this context, which may in turn have its own set of configuration settings (loaded from the context's properties). Each context's logManager keeps its own isolated set of Log instances with their own log levels, output locations, and rotation configuration.

    - #### namingService

          public NamingService namingService()

      Pull up the naming service used in this context. The naming service itself works by querying the context's properties, so those props should be specified to customize the naming service exposed.

    - #### portMapper

          public PortMapper portMapper()

      Basic mapping from service names to ports

    - #### random

          public RandomSource random()

      [insert snarky comment here]

    - #### removeShutdownTask

          public void removeShutdownTask(Runnable task)

      Remove a shutdown task.
      Parameters:
        `task` - the task to remove

    - #### routingKeyGenerator

          public RoutingKeyGenerator routingKeyGenerator()

      Determine how much do we want to mess with the keys to turn them into something we can route. This is context specific because we may want to test out how things react when peers don't agree on how to skew. As of 0.9.16, returns null in I2PAppContext. You must be in RouterContext to get a generator.
      Returns:
        null always

    - #### sessionKeyManager

          public SessionKeyManager sessionKeyManager()

      The session key manager which coordinates the sessionKey / sessionTag data. This component allows transparent operation of the ElGamal/AES+SessionTag algorithm, and contains all of the session tags for one particular application. This is deprecated for client use, it should be used only by the router as its own key manager. Not that clients are doing end-to-end crypto anyway. For client crypto within the router, use RouterContext.clientManager.getClientSessionKeyManager(dest) As of 0.9.15, this returns a dummy SessionKeyManager in I2PAppContext. The dummy SKM does NOT handle session tags. Overridden in RouterContext to return the full TransientSessionKeyManager.

    - #### setGlobalContext

          protected static boolean setGlobalContext(I2PAppContext ctx)

      Sets the default context, unless there is one already. NOT a public API, for use by RouterContext only, NOT for external use.
      Parameters:
        `ctx` - context constructed with doInit = false
      Returns:
        success (false if previously set)

    - #### setLogManager

          public void setLogManager(LogManager logManager)

      Overwrites the LogManager instance to be used by the router. This should only be called after the Router is instantiated but before it is started. Calling this at any other time can have unpredictable side effects.

    - #### sha

          public SHA256Generator sha()

      Our SHA256 instance (see the hmac discussion for why its context specific)

    - #### simpleTimer2

          public SimpleTimer2 simpleTimer2()

      Use instead of SimpleTimer2.getInstance()

    - #### statManager

          public StatManager statManager()

      The statistics component with which we can track various events over time.