Package org.dspace.core
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,
completeis called to commit the changes and free up any resources used by the context. If anything has gone wrong,abortis called to roll back any changes and free up the resources.The context object is also used as a cache for CM API objects.
- Version:
- $Revision$
-
-
Nested Class Summary
Nested Classes Modifier and Type Class Description static classContext.Mode
-
Field Summary
Fields Modifier and Type Field Description protected static AtomicBooleandatabaseUpdatedprotected EventServiceeventService
-
Constructor Summary
Constructors Modifier Constructor Description Context()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
All Methods Static Methods Instance Methods Concrete Methods Deprecated Methods Modifier and Type Method Description voidabort()Close the context, without committing any of the changes performed using this context.voidaddEvent(Event event)Add 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()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.voiddispatchEvents()Dispatch 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).Set<Group>getCachedAllMemberGroupsSet(EPerson ePerson)BooleangetCachedAuthorizationResult(DSpaceObject dspaceObject, int action, EPerson eperson)BooleangetCachedGroupMembership(Group group, EPerson eperson)longgetCacheSize()Returns the size of the cache of all object that have been read from the database so far.LocalegetCurrentLocale()Gets the current LocaleContext.ModegetCurrentMode()The current database mode of this context.EPersongetCurrentUser()Get the current (authenticated) userDatabaseConfigVOgetDBConfig()StringgetDbType()LinkedList<Event>getEvents()Get the current event list.StringgetExtraLogInfo()Get extra information to be logged with message logged in the scope of this context.List<Group>getSpecialGroups()Get an array of all of the special groups that current user is a member of.booleanhasEvents()Whether or not the context has events cached.booleanignoreAuthorization()Find 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 groupbooleanisBatchModeEnabled()Deprecated.booleanisReadOnly()Reports whether context supports updating DSpaceObjects, or only reading.protected booleanisTransactionAlive()Find out whether our context includes an open database transaction.booleanisValid()Find out if this context is valid.EventpollEvent()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.voidrestoreAuthSystemState()Restore the previous Authorisation System State.voidrestoreContextUser()Restore the user bound to the context and his special groupsvoidsetCurrentLocale(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 ContextvoidshutDownDatabase()voidswitchContextUser(EPerson newUser)Temporary change the user bound to the context, empty the special groups that are retained to allow subsequent restorevoidturnOffAuthorisationSystem()Turn Off the Authorisation System for this context and store this change in a history for future use.<E extends ReloadableEntity>
voiduncacheEntity(E entity)Remove an entity from the cache.static booleanupdateDatabase()
-
-
-
Field Detail
-
databaseUpdated
protected static final AtomicBoolean databaseUpdated
-
eventService
protected EventService eventService
-
-
Constructor Detail
-
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 Detail
-
init
protected void init()
Initializes a new context object.- Throws:
SQLException- if there was an error obtaining a database connection
-
updateDatabase
public static boolean updateDatabase()
-
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, ornullif no user is authenticated
-
getCurrentUser
public EPerson getCurrentUser()
Get the current (authenticated) user- Returns:
- the current user, or
nullif 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:
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
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 SQLExceptionClose 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 SQLExceptionCommit 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
public void setDispatcher(String dispatcher)
Select an event dispatcher,nullselects 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
nullif the list is empty
-
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()
- 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
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
-
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 his special groups- Throws:
IllegalStateException- if no switch was performed before
-
finalize
protected void finalize() throws ThrowableClose the context, aborting any open transactions (if any).
-
shutDownDatabase
public void shutDownDatabase() throws SQLException- Throws:
SQLException
-
getCacheSize
public long getCacheSize() throws SQLExceptionReturns 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}).- 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 enity. 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.
-
uncacheEntity
public <E extends ReloadableEntity> void uncacheEntity(E entity) throws SQLException
Remove an entity from the cache. This is necessary when batch processing a large number of items.- Type Parameters:
E- The class of the enity. The entity must implement theReloadableEntityinterface.- 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)
-
cacheGroupMembership
public void cacheGroupMembership(Group group, EPerson eperson, Boolean isMember)
-
-