Class Context
- All Implemented Interfaces:
AutoCloseable
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.
-
Nested Class Summary
Nested Classes -
Field Summary
Fields -
Constructor Summary
ConstructorsModifierConstructorDescriptionContext()Construct a new context object with default options.Context(Context.Mode mode) Construct a new context object with the given mode enabled.protectedContext(EventService eventService, DBConnection dbConnection) -
Method Summary
Modifier and TypeMethodDescriptionvoidabort()Close the context, without committing any of the changes performed using this context.voidAdd an event to be dispatched when this context is committed.voidcacheAllMemberGroupsSet(EPerson ePerson, Set<Group> groups) voidcacheAuthorizedAction(DSpaceObject dspaceObject, int action, EPerson eperson, Boolean result, ResourcePolicy rp) voidcacheGroupMembership(Group group, EPerson eperson, Boolean isMember) voidclose()Close this Context, discarding any uncommitted changes and releasing its database connection.voidcommit()Commit the current transaction with the database, persisting any pending changes.voidcomplete()Close the context object after all of the operations performed in the context have completed successfully.voidDispatch any events (cached in current Context) to configured EventListeners (consumers) in the EventService.voidenableBatchMode(boolean batchModeEnabled) Deprecated.protected voidfinalize()Close the context, aborting any open transactions (if any).Returns the default "Administrator" group for DSpace administrators.getCachedAllMemberGroupsSet(EPerson ePerson) getCachedAuthorizationResult(DSpaceObject dspaceObject, int action, EPerson eperson) getCachedGroupMembership(Group group, EPerson eperson) longReturns the size of the cache of all object that have been read from the database so far.Gets the current LocaleThe current database mode of this context.Get the current (authenticated) userGet the current event list.Get extra information to be logged with message logged in the scope of this context.Get an array of all of the special groups that current user is a member of.Get a set of all of the special groups uuids that current user is a member of.booleanWhether or not the context has events cached.booleanFind out if the authorisation system should be ignored for this context.protected voidinit()Initializes a new context object.booleaninSpecialGroup(UUID groupID) Test if a group is a special groupbooleanDeprecated.booleanCheck if the user of the context is switched.booleanReports whether context supports updating DSpaceObjects, or only reading.protected booleanFind out whether our context includes an open database transaction.booleanisValid()Find out if this context is valid.Retrieves the first element in the events list and removes it from the list of events once retrieved<E extends ReloadableEntity>
EreloadEntity(E entity) Reload an entity from the database into the cache.voidRestore the previous Authorisation System State.voidRestore the user bound to the context and their special groupsvoidrollback()Rollback the current transaction with the database, without persisting any pending changes.voidsetAuthenticationMethod(String authenticationMethod) voidsetCurrentLocale(Locale locale) set the current LocalevoidsetCurrentUser(EPerson user) Set the current user.voidsetDispatcher(String dispatcher) Select an event dispatcher,nullselects the defaultvoidsetExtraLogInfo(String info) Set extra information that should be added to any message logged in the scope of this context.voidsetMode(Context.Mode newMode) Change the mode of this current context.voidsetSpecialGroup(UUID groupID) Add a group's UUID to the list of special groups cached in ContextvoidvoidswitchContextUser(EPerson newUser) Temporary change the user bound to the context, empty the special groups that are retained to allow subsequent restorevoidTurn Off the Authorisation System for this context and store this change in a history for future use.voidRemove all entities from the cache and reload the current user entity.<E extends ReloadableEntity>
voiduncacheEntity(E entity) Remove an entity from the cache.static booleanUpdate the DSpace database, ensuring that any necessary migrations are run prior to initializing Hibernate.
-
Field Details
-
databaseUpdated
-
eventService
-
-
Constructor Details
-
Context
-
Context
public Context()Construct a new context object with default options. A database connection is opened. No user is authenticated. -
Context
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
- Throws:
SQLException
-
getDbType
-
setCurrentUser
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, ornullif no user is authenticated
-
getCurrentUser
Get the current (authenticated) user- Returns:
- the current user, or
nullif no user is authenticated
-
getCurrentLocale
Gets the current Locale- Returns:
- Locale the current Locale
-
setCurrentLocale
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:
trueif 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
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
Get extra information to be logged with message logged in the scope of this context.- Returns:
- the extra log info - guaranteed non-
null
-
complete
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
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 (seereloadEntity(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
Select an event dispatcher,nullselects the default- Parameters:
dispatcher- dispatcher
-
addEvent
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
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
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
nullif the list is empty
-
rollback
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 (seereloadEntity(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:
closein interfaceAutoCloseable
-
isValid
public boolean isValid()Find out if this context is valid. Returnsfalseif this context has been aborted or completed.- Returns:
trueif the context is still valid, otherwisefalse
-
isTransactionAlive
protected boolean isTransactionAlive()Find out whether our context includes an open database transaction. Returnstrueif there is an open transaction. Returnsfalseif 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:
trueif the context is read-only, otherwisefalse
-
setSpecialGroup
Add a group's UUID to the list of special groups cached in Context- Parameters:
groupID- UUID of group
-
inSpecialGroup
Test if a group is a special group- Parameters:
groupID- ID of special group to test- Returns:
- true if member
-
getSpecialGroups
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
Get a set of all of the special groups uuids that current user is a member of.- Returns:
- list of special groups uuids
-
switchContextUser
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
Close the context, aborting any open transactions (if any). -
shutDownDatabase
- Throws:
SQLException
-
getCacheSize
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 (seeuncacheEntity(ReloadableEntity)() uncacheEntity}).- Returns:
- cache size.
- Throws:
SQLException- When connecting to the active cache fails.
-
setMode
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
The current database mode of this context.- Returns:
- The current mode
-
enableBatchMode
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.Check if "batch processing mode" is enabled for this context.- Returns:
- True if batch processing mode is enabled, false otherwise.
-
reloadEntity
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 theReloadableEntityinterface.- 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
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
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 theReloadableEntityinterface.- Parameters:
entity- The entity to reload- Throws:
SQLException- When reloading the entity from the database fails.
-
getCachedAuthorizationResult
-
cacheAuthorizedAction
public void cacheAuthorizedAction(DSpaceObject dspaceObject, int action, EPerson eperson, Boolean result, ResourcePolicy rp) -
getCachedGroupMembership
-
cacheGroupMembership
-
cacheAllMemberGroupsSet
-
getCachedAllMemberGroupsSet
-
getAuthenticationMethod
-
setAuthenticationMethod
-
isContextUserSwitched
public boolean isContextUserSwitched()Check if the user of the context is switched. -
getAdminGroup
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
-