Class Context

java.lang.Object
org.dspace.core.Context
All Implemented Interfaces:
AutoCloseable

public class Context extends Object implements AutoCloseable
Class representing the context of a particular DSpace operation. This stores information such as the current authenticated user and the database connection being used.

Typical use of the context object will involve constructing one, and setting the current user if one is authenticated. Several operations may be performed using the context object. If all goes well, complete is called to commit the changes and free up any resources used by the context. If anything has gone wrong, abort is called to roll back any changes and free up the resources.

The context object is also used as a cache for CM API objects.

  • Field Details

  • Constructor Details

    • Context

      protected Context(EventService eventService, DBConnection dbConnection)
    • Context

      public Context()
      Construct a new context object with default options. A database connection is opened. No user is authenticated.
    • Context

      public Context(Context.Mode mode)
      Construct a new context object with the given mode enabled. A database connection is opened. No user is authenticated.
      Parameters:
      mode - The mode to use when opening the context.
  • Method Details

    • init

      protected void init()
      Initializes a new context object.
    • updateDatabase

      public static boolean updateDatabase()
      Update the DSpace database, ensuring that any necessary migrations are run prior to initializing Hibernate.

      This is synchronized as it only needs to be run successfully *once* (for the first Context initialized).

      Returns:
      true/false, based on whether database was successfully updated
    • getDBConfig

      public DatabaseConfigVO getDBConfig() throws SQLException
      Throws:
      SQLException
    • getDbType

      public String getDbType()
    • setCurrentUser

      public void setCurrentUser(EPerson user)
      Set the current user. Authentication must have been performed by the caller - this call does not attempt any authentication.
      Parameters:
      user - the new current user, or null if no user is authenticated
    • getCurrentUser

      public EPerson getCurrentUser()
      Get the current (authenticated) user
      Returns:
      the current user, or null if no user is authenticated
    • getCurrentLocale

      public Locale getCurrentLocale()
      Gets the current Locale
      Returns:
      Locale the current Locale
    • setCurrentLocale

      public void setCurrentLocale(Locale locale)
      set the current Locale
      Parameters:
      locale - the current Locale
    • ignoreAuthorization

      public boolean ignoreAuthorization()
      Find out if the authorisation system should be ignored for this context.
      Returns:
      true if authorisation should be ignored for this session.
    • turnOffAuthorisationSystem

      public void turnOffAuthorisationSystem()
      Turn Off the Authorisation System for this context and store this change in a history for future use.
    • restoreAuthSystemState

      public void restoreAuthSystemState()
      Restore the previous Authorisation System State. If the state was not changed by the current caller a warning will be displayed in log. Use: mycontext.turnOffAuthorisationSystem(); some java code that require no authorisation check mycontext.restoreAuthSystemState(); If Context debug is enabled, the correct sequence calling will be checked and a warning will be displayed if not.
    • setExtraLogInfo

      public void setExtraLogInfo(String info)
      Set extra information that should be added to any message logged in the scope of this context. An example of this might be the session ID of the current Web user's session:

      setExtraLogInfo("session_id="+request.getSession().getId());

      Parameters:
      info - the extra information to log
    • getExtraLogInfo

      public String getExtraLogInfo()
      Get extra information to be logged with message logged in the scope of this context.
      Returns:
      the extra log info - guaranteed non- null
    • complete

      public void complete() throws SQLException
      Close the context object after all of the operations performed in the context have completed successfully. Any transaction with the database is committed.

      Calling complete() on a Context which is no longer valid (isValid()==false), is a no-op.

      Throws:
      SQLException - if there was an error completing the database transaction or closing the connection
    • commit

      public void commit() throws SQLException
      Commit the current transaction with the database, persisting any pending changes. The database connection is not closed and can be reused afterwards. WARNING: After calling this method all previously fetched entities are "detached" (pending changes are not tracked anymore). You have to reload all entities you still want to work with manually after this method call (see reloadEntity(ReloadableEntity)).
      Throws:
      SQLException - When committing the transaction in the database fails.
    • dispatchEvents

      public void dispatchEvents()
      Dispatch any events (cached in current Context) to configured EventListeners (consumers) in the EventService. This should be called prior to any commit as some consumers may add to the current transaction. Once events are dispatched, the Context's event cache is cleared.
    • setDispatcher

      public void setDispatcher(String dispatcher)
      Select an event dispatcher, null selects the default
      Parameters:
      dispatcher - dispatcher
    • addEvent

      public void addEvent(Event event)
      Add an event to be dispatched when this context is committed. NOTE: Read-only Contexts cannot add events, as they cannot modify objects.
      Parameters:
      event - event to be dispatched
    • getEvents

      public LinkedList<Event> getEvents()
      Get the current event list. If there is a separate list of events from already-committed operations combine that with current list.
      Returns:
      List of all available events.
    • hasEvents

      public boolean hasEvents()
      Whether or not the context has events cached.
      Returns:
      true or false
    • pollEvent

      public Event pollEvent()
      Retrieves the first element in the events list and removes it from the list of events once retrieved
      Returns:
      The first event of the list or null if the list is empty
    • rollback

      public void rollback() throws SQLException
      Rollback the current transaction with the database, without persisting any pending changes. The database connection is not closed and can be reused afterwards. WARNING: After calling this method all previously fetched entities are "detached" (pending changes are not tracked anymore). You have to reload all entities you still want to work with manually after this method call (see reloadEntity(ReloadableEntity)).
      Throws:
      SQLException - When rollbacking the transaction in the database fails.
    • abort

      public void abort()
      Close the context, without committing any of the changes performed using this context. The database connection is freed. No exception is thrown if there is an error freeing the database connection, since this method may be called as part of an error-handling routine where an SQLException has already been thrown.

      Calling abort() on a Context which is no longer valid (isValid()==false), is a no-op.

    • close

      public void close()
      Close this Context, discarding any uncommitted changes and releasing its database connection.
      Specified by:
      close in interface AutoCloseable
    • isValid

      public boolean isValid()
      Find out if this context is valid. Returns false if this context has been aborted or completed.
      Returns:
      true if the context is still valid, otherwise false
    • isTransactionAlive

      protected boolean isTransactionAlive()
      Find out whether our context includes an open database transaction. Returns true if there is an open transaction. Returns false if the context is invalid (e.g. abort() or complete()) was called OR no current transaction exists (e.g. commit() was just called and no new transaction has begun)
      Returns:
    • isReadOnly

      public boolean isReadOnly()
      Reports whether context supports updating DSpaceObjects, or only reading.
      Returns:
      true if the context is read-only, otherwise false
    • setSpecialGroup

      public void setSpecialGroup(UUID groupID)
      Add a group's UUID to the list of special groups cached in Context
      Parameters:
      groupID - UUID of group
    • inSpecialGroup

      public boolean inSpecialGroup(UUID groupID)
      Test if a group is a special group
      Parameters:
      groupID - ID of special group to test
      Returns:
      true if member
    • getSpecialGroups

      public List<Group> getSpecialGroups() throws SQLException
      Get an array of all of the special groups that current user is a member of.
      Returns:
      list of special groups
      Throws:
      SQLException - if database error
    • getSpecialGroupUuids

      public Set<UUID> getSpecialGroupUuids()
      Get a set of all of the special groups uuids that current user is a member of.
      Returns:
      list of special groups uuids
    • switchContextUser

      public void switchContextUser(EPerson newUser)
      Temporary change the user bound to the context, empty the special groups that are retained to allow subsequent restore
      Parameters:
      newUser - the EPerson to bound to the context
      Throws:
      IllegalStateException - if the switch was already performed without be restored
    • restoreContextUser

      public void restoreContextUser()
      Restore the user bound to the context and their special groups
      Throws:
      IllegalStateException - if no switch was performed before
    • finalize

      protected void finalize() throws Throwable
      Close the context, aborting any open transactions (if any).
      Overrides:
      finalize in class Object
      Throws:
      Throwable
    • shutDownDatabase

      public void shutDownDatabase() throws SQLException
      Throws:
      SQLException
    • getCacheSize

      public long getCacheSize() throws SQLException
      Returns the size of the cache of all object that have been read from the database so far. A larger number means that more memory is consumed by the cache. This also has a negative impact on the query performance. In that case you should consider uncaching entities when they are no longer needed (see uncacheEntity(ReloadableEntity) () uncacheEntity}).
      Returns:
      cache size.
      Throws:
      SQLException - When connecting to the active cache fails.
    • setMode

      public void setMode(Context.Mode newMode)
      Change the mode of this current context. BATCH_EDIT: Enabling batch edit mode means that the database connection is configured so that it is optimized to process a large number of records. READ_ONLY: READ ONLY mode will tell the database we are nog going to do any updates. This means it can disable optimalisations for delaying or grouping updates. READ_WRITE: This is the default mode and enables the normal database behaviour. This behaviour is optimal for querying and updating a small number of records.
      Parameters:
      newMode - The mode to put this context in
    • getCurrentMode

      public Context.Mode getCurrentMode()
      The current database mode of this context.
      Returns:
      The current mode
    • enableBatchMode

      @Deprecated public void enableBatchMode(boolean batchModeEnabled) throws SQLException
      Deprecated.
      Enable or disable "batch processing mode" for this context. Enabling batch processing mode means that the database connection is configured so that it is optimized to process a large number of records. Disabling batch processing mode restores the normal behaviour that is optimal for querying and updating a small number of records.
      Parameters:
      batchModeEnabled - When true, batch processing mode will be enabled. If false, it will be disabled.
      Throws:
      SQLException - When configuring the database connection fails.
    • isBatchModeEnabled

      @Deprecated public boolean isBatchModeEnabled()
      Deprecated.
      Check if "batch processing mode" is enabled for this context.
      Returns:
      True if batch processing mode is enabled, false otherwise.
    • reloadEntity

      public <E extends ReloadableEntity> E reloadEntity(E entity) throws SQLException
      Reload an entity from the database into the cache. This method will return a reference to the "attached" entity. This means changes to the entity will be tracked and persisted to the database.
      Type Parameters:
      E - The class of the entity. The entity must implement the ReloadableEntity interface.
      Parameters:
      entity - The entity to reload
      Returns:
      A (possibly) NEW reference to the entity that should be used for further processing.
      Throws:
      SQLException - When reloading the entity from the database fails.
    • uncacheEntities

      public void uncacheEntities() throws SQLException
      Remove all entities from the cache and reload the current user entity. This is useful when batch processing a large number of entities when the calling code requires the cache to be completely cleared before continuing.
      Throws:
      SQLException - if a database error occurs.
    • uncacheEntity

      public <E extends ReloadableEntity> void uncacheEntity(E entity) throws SQLException
      Remove an entity from the cache. This is useful when batch processing a large number of entities when the calling code needs to retain some items in the cache while removing others.
      Type Parameters:
      E - The class of the entity. The entity must implement the ReloadableEntity interface.
      Parameters:
      entity - The entity to reload
      Throws:
      SQLException - When reloading the entity from the database fails.
    • getCachedAuthorizationResult

      public Boolean getCachedAuthorizationResult(DSpaceObject dspaceObject, int action, EPerson eperson)
    • cacheAuthorizedAction

      public void cacheAuthorizedAction(DSpaceObject dspaceObject, int action, EPerson eperson, Boolean result, ResourcePolicy rp)
    • getCachedGroupMembership

      public Boolean getCachedGroupMembership(Group group, EPerson eperson)
    • cacheGroupMembership

      public void cacheGroupMembership(Group group, EPerson eperson, Boolean isMember)
    • cacheAllMemberGroupsSet

      public void cacheAllMemberGroupsSet(EPerson ePerson, Set<Group> groups)
    • getCachedAllMemberGroupsSet

      public Set<Group> getCachedAllMemberGroupsSet(EPerson ePerson)
    • getAuthenticationMethod

      public String getAuthenticationMethod()
    • setAuthenticationMethod

      public void setAuthenticationMethod(String authenticationMethod)
    • isContextUserSwitched

      public boolean isContextUserSwitched()
      Check if the user of the context is switched.
    • getAdminGroup

      public Group getAdminGroup() throws SQLException
      Returns the default "Administrator" group for DSpace administrators. The result is cached in the 'adminGroup' field, so it is only looked up once. This is done to improve performance, as this method is called quite often.
      Throws:
      SQLException