org.openmrs.api.context
Class Context

java.lang.Object
  extended by org.openmrs.api.context.Context

public class Context
extends java.lang.Object

Represents an OpenMRS Context, which may be used to authenticate to the database and obtain services in order to interact with the system.

The Context is split into a UserContext and ServiceContext. The UserContext is lightweight and there is an instance for every user logged into the system. The ServiceContext is heavier and contains each service class. This is more static and there is only one ServiceContext per OpenMRS instance.

Both the UserContext and the ServiceContext should not be used directly. This Context class has methods to pass through to the currently defined UserContext for the thread and the currently defined ServiceContext.

To use the OpenMRS api there are four things that have to be done:

  1. Call startup(String, String, String, Properties) to let the Context contact the database
  2. Call openSession() to start a "unit of work".
  3. Call authenticate(String, String) to authenticate the current user on the current thread
  4. Call closeSession() to end your "unit of work" and commit all changes to the database.

Example usage:
        public static void main(String[] args) {
                Context.startup("jdbc:mysql://localhost:3306/db-name?autoReconnect=true", "openmrs-db-user", "3jknfjkn33ijt", new Properties());
                try {
                        Context.openSession();
                        Context.authenticate("admin", "test");
                        List patients = Context.getPatientService().getPatientsByName("Fred");
                        patients.get(0).setBirthdate(new Date());
                        Context.getPatientService().savePatient(patients.get(0));
                        ...
                }
                finally {
                        Context.closeSession();
                }
        }
 

See Also:
UserContext, ServiceContext

Constructor Summary
Context()
          Default public constructor
 
Method Summary
static void addAdvice(java.lang.Class cls, org.aopalliance.aop.Advice advice)
          Adds an AOP advice object around the given Class cls
static void addAdvisor(java.lang.Class cls, org.springframework.aop.Advisor advisor)
          Adds an AOP advisor around the given Class cls
static void addProxyPrivilege(java.lang.String privilege)
          Convenience method.
static void authenticate(java.lang.String username, java.lang.String password)
          Used to authenticate user within the context
static void becomeUser(java.lang.String systemId)
          Become a different user.
static void checkCoreDataset()
          Runs through the core data (e.g.
static void clearSession()
          Clears cached changes made so far during this unit of work without writing them to the database.
static void clearUserContext()
          Clears the user context from the threadlocal.
static void closeSession()
          Used to define a unit of work.
static void evictFromSession(java.lang.Object obj)
          Used to clear a cached object out of a session in the middle of a unit of work.
static void flushSession()
          Forces any changes made so far in this unit of work to be written to the database
static ActiveListService getActiveListService()
           
static AdministrationService getAdministrationService()
           
static AlertService getAlertService()
           
static java.util.Set<Role> getAllRoles(User user)
          Convenience method.
static ArdenService getArdenService()
           
static User getAuthenticatedUser()
           
static CohortService getCohortService()
           
static ConceptService getConceptService()
           
static DataSetService getDataSetService()
          Deprecated. see reportingcompatibility module
static java.text.SimpleDateFormat getDateFormat()
          Gets the simple date format for the current user's locale.
static EncounterService getEncounterService()
           
static FormService getFormService()
           
static HL7Service getHL7Service()
           
static java.util.Locale getLocale()
          Convenience method.
static LocationService getLocationService()
           
static LogicService getLogicService()
           
static MessageService getMessageService()
          Get the message service.
static MessageSourceService getMessageSourceService()
           
static ObsService getObsService()
           
static OrderService getOrderService()
           
static PatientService getPatientService()
           
static PatientSetService getPatientSetService()
           
static PersonService getPersonService()
           
static ProgramWorkflowService getProgramWorkflowService()
           
static
<T> java.util.List<T>
getRegisteredComponents(java.lang.Class<T> type)
           
static ReportObjectService getReportObjectService()
          Deprecated. see reportingcompatibility module
static ReportService getReportService()
          Deprecated. see reportingcompatibility module
static java.util.Properties getRuntimeProperties()
          Get the runtime properties that this OpenMRS instance was started with
static SchedulerService getSchedulerService()
           
static SerializationService getSerializationService()
           
static
<T> T
getService(java.lang.Class<? extends T> cls)
          Used for getting services not in the previous get*Service() calls
static UserContext getUserContext()
          Gets the user context from the thread local.
static UserService getUserService()
           
static java.lang.Object getVolatileUserData(java.lang.String key)
          Get a piece of information for the currently authenticated user.
static boolean hasPrivilege(java.lang.String privilege)
          Convenience method.
static boolean isAuthenticated()
           
static boolean isRefreshingContext()
           
static boolean isSessionOpen()
          This method tells whether openSession() has been called or not already.
static java.lang.Class<?> loadClass(java.lang.String className)
          Loads a class with an instance of the OpenmrsClassLoader.
static void logout()
          logs out the "active" (authenticated) user within context
static void openSession()
          Used to define a unit of work.
static void refreshAuthenticatedUser()
          Refresh the authenticated user object in the current UserContext.
static void removeAdvice(java.lang.Class cls, org.aopalliance.aop.Advice advice)
          Removes the given AOP advice object from Class cls
static void removeAdvisor(java.lang.Class cls, org.springframework.aop.Advisor advisor)
          Removes the given AOP advisor from Class cls
static void removeProxyPrivilege(java.lang.String privilege)
          Convenience method.
static void requirePrivilege(java.lang.String privilege)
          Throws an exception if the currently authenticated user does not have the specified privilege.
 void setContextDAO(ContextDAO dao)
          Used to set the context's DAO for the application.
static void setLocale(java.util.Locale locale)
          Convenience method.
static void setRuntimeProperties(java.util.Properties props)
          Set the runtime properties to be used by this OpenMRS instance
 void setServiceContext(ServiceContext ctx)
          Sets the service context.
static void setUserContext(UserContext ctx)
          Sets the user context on the thread local so that the service layer can perform authentication/authorization checks.

TODO Make thread-safe because this might be accessed by several thread at the same time.
static void setVolatileUserData(java.lang.String key, java.lang.Object value)
          Set a piece of information for the currently authenticated user.
static void shutdown()
          Stops the OpenMRS System Should be called after all activity has ended and application is closing
static void startup(java.util.Properties props)
          Starts the OpenMRS System Should be called prior to any kind of activity

If an InputRequiredException is thrown, a call to DatabaseUpdater#update(Map) will be required with a mapping from question prompt to user answer before startup can be called again.
static void startup(java.lang.String url, java.lang.String username, java.lang.String password, java.util.Properties properties)
          Starts the OpenMRS System in a _non-webapp_ environment

If an InputRequiredException is thrown, a call to DatabaseUpdater#update(Map) will be required with a mapping from question prompt to user answer before startup can be called again.
static void updateDatabase(java.util.Map<java.lang.String,java.lang.Object> userInput)
          Updates the openmrs database to the latest.
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 

Constructor Detail

Context

public Context()
Default public constructor

Method Detail

setContextDAO

public void setContextDAO(ContextDAO dao)
Used to set the context's DAO for the application.

Parameters:
dao - ContextDAO to set

loadClass

public static java.lang.Class<?> loadClass(java.lang.String className)
                                    throws java.lang.ClassNotFoundException
Loads a class with an instance of the OpenmrsClassLoader. Convenience method equivalent to OpenmrsClassLoader.getInstance().loadClass(className);

Parameters:
className - the class to load
Returns:
the class that was loaded
Throws:
java.lang.ClassNotFoundException
Expected behavior:
load class with the OpenmrsClassLoader

setUserContext

public static void setUserContext(UserContext ctx)
Sets the user context on the thread local so that the service layer can perform authentication/authorization checks.

TODO Make thread-safe because this might be accessed by several thread at the same time. Making this thread safe might make this a bottleneck.

Parameters:
ctx - UserContext to set

clearUserContext

public static void clearUserContext()
Clears the user context from the threadlocal.


getUserContext

public static UserContext getUserContext()
Gets the user context from the thread local. This might be accessed by several threads at the same time.

Returns:
The current UserContext for this thread.
Expected behavior:
fail if session hasnt been opened

setServiceContext

public void setServiceContext(ServiceContext ctx)
Sets the service context.

Parameters:
ctx -

authenticate

public static void authenticate(java.lang.String username,
                                java.lang.String password)
                         throws ContextAuthenticationException
Used to authenticate user within the context

Parameters:
username - user's identifier token for login
password - user's password for authenticating to context
Throws:
ContextAuthenticationException
Expected behavior:
not authenticate with null username and password, not authenticate with null password, not authenticate with null username, not authenticate with null password and proper username, not authenticate with null password and proper system id

refreshAuthenticatedUser

public static void refreshAuthenticatedUser()
Refresh the authenticated user object in the current UserContext. This should be used when updating information in the database about the current user and it needs to be reflecting in the (cached) getAuthenticatedUser() User object.

Since:
1.5
Expected behavior:
get fresh values from the database

becomeUser

public static void becomeUser(java.lang.String systemId)
                       throws ContextAuthenticationException
Become a different user. (You should only be able to do this as a superuser.)

Parameters:
systemId -
Throws:
ContextAuthenticationException

getRuntimeProperties

public static java.util.Properties getRuntimeProperties()
Get the runtime properties that this OpenMRS instance was started with

Returns:
copy of the runtime properties

setRuntimeProperties

public static void setRuntimeProperties(java.util.Properties props)
Set the runtime properties to be used by this OpenMRS instance

Parameters:
props - runtime properties

getConceptService

public static ConceptService getConceptService()
Returns:
concept dictionary-related services

getEncounterService

public static EncounterService getEncounterService()
Returns:
encounter-related services

getLocationService

public static LocationService getLocationService()
Returns:
location services

getObsService

public static ObsService getObsService()
Returns:
observation services

getPatientService

public static PatientService getPatientService()
Returns:
patient-related services

getCohortService

public static CohortService getCohortService()

getPersonService

public static PersonService getPersonService()
Returns:
person-related services

getHL7Service

public static HL7Service getHL7Service()
Returns:
Returns the hl7Service.

getPatientSetService

public static PatientSetService getPatientSetService()
Returns:
patientset-related services

getUserService

public static UserService getUserService()
Returns:
user-related services

getOrderService

public static OrderService getOrderService()
Returns:
order service

getFormService

public static FormService getFormService()
Returns:
form service

getSerializationService

public static SerializationService getSerializationService()
Returns:
serialization service
Since:
1.5

getReportService

@Deprecated
public static ReportService getReportService()
Deprecated. see reportingcompatibility module

Returns:
report service

getReportObjectService

@Deprecated
public static ReportObjectService getReportObjectService()
Deprecated. see reportingcompatibility module

Returns:
report object service

getDataSetService

@Deprecated
public static DataSetService getDataSetService()
Deprecated. see reportingcompatibility module

Returns:
dataset service

getLogicService

public static LogicService getLogicService()
Returns:
logic service

getAdministrationService

public static AdministrationService getAdministrationService()
Returns:
admin-related services

getMessageSourceService

public static MessageSourceService getMessageSourceService()
Returns:
MessageSourceService

getSchedulerService

public static SchedulerService getSchedulerService()
Returns:
scheduler service

getAlertService

public static AlertService getAlertService()
Returns:
alert service

getArdenService

public static ArdenService getArdenService()
Returns:
arden service

getProgramWorkflowService

public static ProgramWorkflowService getProgramWorkflowService()
Returns:
program- and workflow-related services

getMessageService

public static MessageService getMessageService()
Get the message service.

Returns:
message service

getActiveListService

public static ActiveListService getActiveListService()
Returns:
active list service

getAuthenticatedUser

public static User getAuthenticatedUser()
Returns:
"active" user who has been authenticated, otherwise null

isAuthenticated

public static boolean isAuthenticated()
Returns:
true if user has been authenticated in this context

logout

public static void logout()
logs out the "active" (authenticated) user within context

See Also:
authenticate(java.lang.String, java.lang.String)
Expected behavior:
not fail if session hasnt been opened yet

getAllRoles

public static java.util.Set<Role> getAllRoles(User user)
                                       throws java.lang.Exception
Convenience method. Passes through to userContext.getAllRoles(User)

Throws:
java.lang.Exception

hasPrivilege

public static boolean hasPrivilege(java.lang.String privilege)
Convenience method. Passes through to userContext.hasPrivilege(String)

Expected behavior:
give daemon user full privileges

requirePrivilege

public static void requirePrivilege(java.lang.String privilege)
                             throws ContextAuthenticationException
Throws an exception if the currently authenticated user does not have the specified privilege.

Parameters:
privilege -
Throws:
ContextAuthenticationException

addProxyPrivilege

public static void addProxyPrivilege(java.lang.String privilege)
Convenience method. Passes through to UserContext.addProxyPrivilege(String)


removeProxyPrivilege

public static void removeProxyPrivilege(java.lang.String privilege)
Convenience method. Passes through to UserContext.removeProxyPrivilege(String)


setLocale

public static void setLocale(java.util.Locale locale)
Convenience method. Passes through to UserContext.setLocale(Locale)


getLocale

public static java.util.Locale getLocale()
Convenience method. Passes through to UserContext.getLocale()

Expected behavior:
not fail if session hasnt been opened

openSession

public static void openSession()
Used to define a unit of work. All "units of work" should be surrounded by openSession and closeSession calls.


closeSession

public static void closeSession()
Used to define a unit of work. All "units of work" should be surrounded by openSession and closeSession calls.


clearSession

public static void clearSession()
Clears cached changes made so far during this unit of work without writing them to the database. If you call this method, and later call closeSession() or flushSession() your changes are still lost.


flushSession

public static void flushSession()
Forces any changes made so far in this unit of work to be written to the database

Since:
1.6

isSessionOpen

public static boolean isSessionOpen()
This method tells whether openSession() has been called or not already. If it hasn't been called, some methods won't work correctly because a UserContext isn't available.

Returns:
true if openSession() has been called already.
Since:
1.5
Expected behavior:
return true if session is closed

evictFromSession

public static void evictFromSession(java.lang.Object obj)
Used to clear a cached object out of a session in the middle of a unit of work. Future updates to this object will not be saved. Future gets of this object will not fetch this cached copy

Parameters:
obj - The object to evict/remove from the session

startup

public static void startup(java.util.Properties props)
                    throws DatabaseUpdateException,
                           InputRequiredException,
                           ModuleMustStartException
Starts the OpenMRS System Should be called prior to any kind of activity

If an InputRequiredException is thrown, a call to DatabaseUpdater#update(Map) will be required with a mapping from question prompt to user answer before startup can be called again.

Parameters:
props - Runtime properties to use for startup
Throws:
InputRequiredException - if the DatabaseUpdater has determined that updates cannot continue without input from the user
DatabaseUpdateException - if database updates are required, see DatabaseUpdater.executeChangelog()
ModuleMustStartException - if a module that should be started is not able to
See Also:
InputRequiredException#getRequiredInput() for the required question/datatypes

startup

public static void startup(java.lang.String url,
                           java.lang.String username,
                           java.lang.String password,
                           java.util.Properties properties)
                    throws DatabaseUpdateException,
                           InputRequiredException,
                           ModuleMustStartException
Starts the OpenMRS System in a _non-webapp_ environment

If an InputRequiredException is thrown, a call to DatabaseUpdater#update(Map) will be required with a mapping from question prompt to user answer before startup can be called again.

Note: This method calls openSession(), so you must call closeSession() somewhere on the same thread of this application so as to not leak memory.

Parameters:
url - database url like "jdbc:mysql://localhost:3306/openmrs?autoReconnect=true"
username - Connection username
password - Connection password
properties - Other startup properties
Throws:
InputRequiredException - if the DatabaseUpdater has determined that updates cannot continue without input from the user
DatabaseUpdateException - if the database must be updated. See DatabaseUpdater
ModuleMustStartException - if a module that should start is not able to
See Also:
startup(Properties), InputRequiredException#getRequiredInput() for the required question/datatypes

shutdown

public static void shutdown()
Stops the OpenMRS System Should be called after all activity has ended and application is closing


getService

public static <T> T getService(java.lang.Class<? extends T> cls)
Used for getting services not in the previous get*Service() calls

Parameters:
cls - The Class of the service to get
Returns:
The requested Service
Expected behavior:
return the same object when called multiple times for the same class

addAdvisor

public static void addAdvisor(java.lang.Class cls,
                              org.springframework.aop.Advisor advisor)
Adds an AOP advisor around the given Class cls

Advisors can wrap around a method and effect the method before or after

Parameters:
cls -
advisor -

addAdvice

public static void addAdvice(java.lang.Class cls,
                             org.aopalliance.aop.Advice advice)
Adds an AOP advice object around the given Class cls

Advice comes in the form of before or afterReturning methods

Parameters:
cls -
advice -

removeAdvisor

public static void removeAdvisor(java.lang.Class cls,
                                 org.springframework.aop.Advisor advisor)
Removes the given AOP advisor from Class cls

Parameters:
cls -
advisor -

removeAdvice

public static void removeAdvice(java.lang.Class cls,
                                org.aopalliance.aop.Advice advice)
Removes the given AOP advice object from Class cls

Parameters:
cls -
advice -

checkCoreDataset

public static void checkCoreDataset()
Runs through the core data (e.g. privileges, roles, and global properties) and adds them if necessary.


updateDatabase

public static void updateDatabase(java.util.Map<java.lang.String,java.lang.Object> userInput)
                           throws DatabaseUpdateException,
                                  InputRequiredException
Updates the openmrs database to the latest. This is only needed if using the API alone.

The typical use-case would be: Try to startup(String, String, String, Properties), if that fails, call this method to get the database up to speed.

Parameters:
userInput - (can be null) responses from the user about needed input
Throws:
DatabaseUpdateException - if an error occurred while updating
InputRequiredException - if user input is required
Since:
1.5

getVolatileUserData

public static java.lang.Object getVolatileUserData(java.lang.String key)
Get a piece of information for the currently authenticated user. This information is stored only temporarily. When a new module is loaded or the server is restarted, this information will disappear. If there is not information by this key, null is returned TODO: This needs to be refactored/removed

Parameters:
key - identifying string for the information
Returns:
the information stored

setVolatileUserData

public static void setVolatileUserData(java.lang.String key,
                                       java.lang.Object value)
Set a piece of information for the currently authenticated user. This information is stored only temporarily. When a new module is loaded or the server is restarted, this information will disappear TODO: This needs to be refactored/removed

Parameters:
key - identifying string for this information
value - information to be stored

getDateFormat

public static java.text.SimpleDateFormat getDateFormat()
Gets the simple date format for the current user's locale. The format will be similar in size to mm/dd/yyyy

Returns:
SimpleDateFormat for the user's current locale
See Also:
OpenmrsUtil.getDateFormat(Locale)
Expected behavior:
return a pattern with four y characters in it

isRefreshingContext

public static boolean isRefreshingContext()
Returns:
true/false whether the service context is currently being refreshed
See Also:
ServiceContext.isRefreshingContext()

getRegisteredComponents

public static <T> java.util.List<T> getRegisteredComponents(java.lang.Class<T> type)
Since:
1.5
See Also:
ServiceContext.getRegisteredComponents(Class)

OpenMRS-1.7.x

Generated Apr 27 2012 10:06 PM. NOTE - these libraries are in active development and subject to change