public class Context extends Object
Context
, which may be used to authenticate to the database and
obtain services in order to interact with the system.UserContext
and ServiceContext
. The UserContext is
lightweight and there is an instance for every user logged into the system. The ServiceContext is
heavier and it contains each service class. This is more static and there is only one ServiceContext
per OpenMRS instance. 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. startup(String, String, String, Properties)
to let the Context contact
the databaseopenSession()
to start a "unit of work".authenticate(String, String)
to authenticate the current user on the
current threadcloseSession()
to end your "unit of work" and commit all changes to the
database.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> patients = Context.getPatientService().getPatientsByName("Fred"); patients.get(0).setBirthdate(new Date()); Context.getPatientService().savePatient(patients.get(0)); ... } finally { Context.closeSession(); } }
UserContext
,
ServiceContext
Constructor and Description |
---|
Context()
Default public constructor
|
Modifier and Type | Method and Description |
---|---|
static void |
addAdvice(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 |
static void |
addAdvisor(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 |
static void |
addConfigProperty(Object key,
Object value)
Add or replace a property in the config properties list
|
static void |
addProxyPrivilege(String privilege)
Convenience method.
|
static Authenticated |
authenticate(Credentials credentials) |
static void |
authenticate(String username,
String password)
Deprecated.
as of 2.3.0, replaced by
authenticate(Credentials)
Used to authenticate user within the context |
static void |
becomeUser(String systemId)
Become a different user.
|
static void |
checkCoreDataset()
Runs through the core data (e.g. privileges, roles, and global properties) and adds them if
necessary.
|
static void |
clearEntireCache()
Evicts data from all cache regions.
|
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 |
closeSessionWithCurrentUser()
Used when the a unit of work which started with a call for openSessionWithCurrentUser has
finished.
|
static void |
evictAllEntities(Class<?> entityClass)
Evicts all entity data of a particular class from the given region.
|
static void |
evictEntity(OpenmrsObject object)
Evicts the entity data for a particular entity instance.
|
static void |
evictFromSession(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 AdministrationService |
getAdministrationService() |
static AlertService |
getAlertService() |
static Set<Role> |
getAllRoles(User user)
Convenience method.
|
static User |
getAuthenticatedUser() |
static AuthenticationScheme |
getAuthenticationScheme()
OpenMRS provides its default authentication scheme that authenticates via DAO with OpenMRS usernames and passwords.
|
static CohortService |
getCohortService() |
static ConceptService |
getConceptService() |
static ConditionService |
getConditionService() |
static Properties |
getConfigProperties()
Get the config properties that have been added to this OpenMRS instance
|
static Connection |
getDatabaseConnection() |
static DatatypeService |
getDatatypeService() |
static SimpleDateFormat |
getDateFormat()
Gets the simple date format for the current user's locale.
|
static SimpleDateFormat |
getDateTimeFormat()
Gets the simple datetime format for the current user's locale.
|
static DiagnosisService |
getDiagnosisService() |
static EncounterService |
getEncounterService() |
static FormService |
getFormService() |
static HL7Service |
getHL7Service() |
static Locale |
getLocale()
Convenience method.
|
static LocationService |
getLocationService() |
static LogicService |
getLogicService() |
static Properties |
getMailProperties() |
static MedicationDispenseService |
getMedicationDispenseService() |
static MessageService |
getMessageService()
Get the message service.
|
static MessageSourceService |
getMessageSourceService() |
static List<OpenmrsService> |
getModuleOpenmrsServices(String modulePackage) |
static ObsService |
getObsService() |
static OrderService |
getOrderService() |
static OrderSetService |
getOrderSetService() |
static PatientService |
getPatientService() |
static PersonService |
getPersonService() |
static ProgramWorkflowService |
getProgramWorkflowService() |
static ProviderService |
getProviderService() |
static <T> T |
getRegisteredComponent(String beanName,
Class<T> type) |
static <T> List<T> |
getRegisteredComponents(Class<T> type) |
static Properties |
getRuntimeProperties()
Get the runtime properties that this OpenMRS instance was started with
|
static SchedulerService |
getSchedulerService() |
static SerializationService |
getSerializationService() |
static <T> T |
getService(Class<? extends T> cls)
Used for getting services not in the previous get*Service() calls
|
static SimpleDateFormat |
getTimeFormat()
Gets the simple time format for the current user's locale.
|
static UserContext |
getUserContext()
Gets the user context from the thread local.
|
static UserService |
getUserService() |
static VisitService |
getVisitService() |
static boolean |
hasPrivilege(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 boolean |
isUseSystemClassLoader() |
static Class<?> |
loadClass(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 |
openSessionWithCurrentUser()
Used to define a unit of work which does not require clearing out the currently authenticated
user.
|
static void |
refreshAuthenticatedUser()
Refresh the authenticated user object in the current UserContext.
|
static void |
refreshEntity(Object obj)
Used to re-read the state of the given instance from the underlying database.
|
static void |
removeAdvice(Class cls,
org.aopalliance.aop.Advice advice)
Removes the given AOP advice object from Class
cls |
static void |
removeAdvisor(Class cls,
org.springframework.aop.Advisor advisor)
Removes the given AOP advisor from Class
cls |
static void |
removeConfigProperty(Object key)
Remove a property from the list of config properties
|
static void |
removeProxyPrivilege(String privilege)
Convenience method.
|
static void |
requirePrivilege(String privilege)
Throws an exception if the currently authenticated user does not have the specified
privilege.
|
static void |
setContext(ServiceContext ctx) |
void |
setContextDAO(ContextDAO dao)
Used to set the context's DAO for the application.
|
static void |
setDAO(ContextDAO dao) |
static void |
setLocale(Locale locale)
Convenience method.
|
static void |
setRuntimeProperties(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.
|
static void |
setUseSystemClassLoader(boolean useSystemClassLoader) |
static void |
shutdown()
Stops the OpenMRS System Should be called after all activity has ended and application is
closing
|
static void |
startup(Properties props)
Starts the OpenMRS System Should be called prior to any kind of activity
|
static void |
startup(String url,
String username,
String password,
Properties properties)
Starts the OpenMRS System in a _non-webapp_ environment
Note: This method calls openSession() , so you must call
closeSession() somewhere on the same thread of this application so as to not
leak memory. |
static void |
updateDatabase(Map<String,Object> userInput)
Deprecated.
as of 2.4
|
static void |
updateSearchIndex()
Updates the search index.
|
static Future<?> |
updateSearchIndexAsync()
Updates the search index.
|
static void |
updateSearchIndexForObject(Object object)
Updates the search index for the given object.
|
static void |
updateSearchIndexForType(Class<?> type)
Updates the search index for objects of the given type.
|
public void setContextDAO(ContextDAO dao)
dao
- ContextDAO to setpublic static void setDAO(ContextDAO dao)
public static Class<?> loadClass(String className) throws ClassNotFoundException
className
- the class to loadClassNotFoundException
- Should load class with the OpenmrsClassLoaderpublic static void setUserContext(UserContext ctx)
ctx
- UserContext to setpublic static void clearUserContext()
public static UserContext getUserContext()
public void setServiceContext(ServiceContext ctx)
ctx
- public static void setContext(ServiceContext ctx)
public static AuthenticationScheme getAuthenticationScheme()
AuthenticationScheme
.
This method would return Core's default authentication scheme unless a Spring override is provided somewhere else.@Deprecated public static void authenticate(String username, String password) throws ContextAuthenticationException
authenticate(Credentials)
Used to authenticate user within the contextusername
- user's identifier token for loginpassword
- user's password for authenticating to contextContextAuthenticationException
- Should not authenticate with null username and password
Should not authenticate with null password
Should not authenticate with null username
Should not authenticate with null password and proper username
Should not authenticate with null password and proper system idpublic static Authenticated authenticate(Credentials credentials) throws ContextAuthenticationException
credentials
- ContextAuthenticationException
public static void refreshAuthenticatedUser()
getAuthenticatedUser()
User object.public static void becomeUser(String systemId) throws ContextAuthenticationException
systemId
- ContextAuthenticationException
- Should change locale when become another userpublic static Properties getRuntimeProperties()
public static void setRuntimeProperties(Properties props)
props
- runtime propertiespublic static ConceptService getConceptService()
public static EncounterService getEncounterService()
public static LocationService getLocationService()
public static ObsService getObsService()
public static PatientService getPatientService()
public static CohortService getCohortService()
public static PersonService getPersonService()
public static ConditionService getConditionService()
public static DiagnosisService getDiagnosisService()
public static MedicationDispenseService getMedicationDispenseService()
public static HL7Service getHL7Service()
public static UserService getUserService()
public static OrderService getOrderService()
public static OrderSetService getOrderSetService()
public static FormService getFormService()
public static SerializationService getSerializationService()
public static LogicService getLogicService()
public static AdministrationService getAdministrationService()
public static MessageSourceService getMessageSourceService()
public static SchedulerService getSchedulerService()
public static AlertService getAlertService()
public static ProgramWorkflowService getProgramWorkflowService()
public static MessageService getMessageService()
public static Properties getMailProperties()
public static User getAuthenticatedUser()
null
public static boolean isAuthenticated()
public static void logout()
public static Set<Role> getAllRoles(User user) throws Exception
Exception
public static boolean hasPrivilege(String privilege)
public static void requirePrivilege(String privilege) throws ContextAuthenticationException
privilege
- ContextAuthenticationException
public static void addProxyPrivilege(String privilege)
UserContext.addProxyPrivilege(String)
public static void removeProxyPrivilege(String privilege)
UserContext.removeProxyPrivilege(String)
public static void setLocale(Locale locale)
UserContext.setLocale(Locale)
public static Locale getLocale()
UserContext.getLocale()
Should not fail if session hasn't been openedpublic static void openSession()
public static void closeSession()
public static void openSessionWithCurrentUser()
public static void closeSessionWithCurrentUser()
public static void clearSession()
public static void flushSession()
public static boolean isSessionOpen()
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.openSession()
has been called already.public static void refreshEntity(Object obj)
obj
- The object to refresh from the database in the sessionpublic static void evictFromSession(Object obj)
obj
- The object to evict/remove from the sessionpublic static void evictEntity(OpenmrsObject object)
object
- entity instance to evict from the DB cachepublic static void evictAllEntities(Class<?> entityClass)
entityClass
- entity class to evict from the DB cachepublic static void clearEntireCache()
public static void startup(Properties props) throws DatabaseUpdateException, InputRequiredException, ModuleMustStartException
props
- Runtime properties to use for startupInputRequiredException
- if the DatabaseUpdater
has determined that updates
cannot continue without input from the userDatabaseUpdateException
- if database updates are required, see
DatabaseUpdater.executeChangelog()
ModuleMustStartException
- if a module that should be started is not able toInputRequiredException#getRequiredInput() for
the required question/datatypes
public static void startup(String url, String username, String password, Properties properties) throws DatabaseUpdateException, InputRequiredException, ModuleMustStartException
openSession()
, so you must call
closeSession()
somewhere on the same thread of this application so as to not
leak memory.url
- database url like "jdbc:mysql://localhost:3306/openmrs?autoReconnect=true"username
- Connection usernamepassword
- Connection passwordproperties
- Other startup propertiesInputRequiredException
- if the DatabaseUpdater
has determined that updates
cannot continue without input from the userDatabaseUpdateException
- if the database must be updated. See DatabaseUpdater
ModuleMustStartException
- if a module that should start is not able tostartup(Properties)
,
InputRequiredException#getRequiredInput() for
the required question/datatypes
public static void shutdown()
public static <T> T getService(Class<? extends T> cls)
cls
- The Class of the service to getpublic static void addAdvisor(Class cls, org.springframework.aop.Advisor advisor)
cls
Advisors can wrap around a method and effect the method before or after
cls
- advisor
- public static void addAdvice(Class cls, org.aopalliance.aop.Advice advice)
cls
Advice comes in the form of before or afterReturning methods
cls
- advice
- public static void removeAdvisor(Class cls, org.springframework.aop.Advisor advisor)
cls
cls
- advisor
- public static void removeAdvice(Class cls, org.aopalliance.aop.Advice advice)
cls
cls
- advice
- public static void checkCoreDataset()
@Deprecated public static void updateDatabase(Map<String,Object> userInput) throws DatabaseUpdateException
startup(String, String, String, Properties)
,
if that fails, call this method to get the database up to speed.userInput
- (can be null) responses from the user about needed inputDatabaseUpdateException
- if an error occurred while updatingpublic static SimpleDateFormat getDateFormat()
Should return a pattern with four y characters in it
public static SimpleDateFormat getTimeFormat()
Should return a pattern with two h characters in it
public static SimpleDateFormat getDateTimeFormat()
Should return a pattern with four y characters and two h characters in it
public static boolean isRefreshingContext()
ServiceContext.isRefreshingContext()
public static <T> List<T> getRegisteredComponents(Class<T> type)
ServiceContext.getRegisteredComponents(Class)
public static <T> T getRegisteredComponent(String beanName, Class<T> type) throws APIException
APIException
ServiceContext.getRegisteredComponent(String, Class)
public static List<OpenmrsService> getModuleOpenmrsServices(String modulePackage)
ServiceContext.getModuleOpenmrsServices(String)
public static VisitService getVisitService()
ServiceContext.getVisitService()
public static ProviderService getProviderService()
ServiceContext.getProviderService()
public static DatatypeService getDatatypeService()
ServiceContext.getDatatypeService()
public static void addConfigProperty(Object key, Object value)
key
- name of the propertyvalue
- value of the propertypublic static void removeConfigProperty(Object key)
key
- name of the propertypublic static Properties getConfigProperties()
public static void updateSearchIndex()
There is no need to call this method in normal usage since the index is automatically updated whenever DB transactions are committed.
The method is designated to be used in tests, which rollback transactions. Note that if the transaction is rolled back, changes to the index will not be reverted.
public static Future<?> updateSearchIndexAsync()
There is no need to call this method in normal usage since the index is automatically updated whenever DB transactions are committed.
public static void updateSearchIndexForType(Class<?> type)
type
- updateSearchIndex()
public static void updateSearchIndexForObject(Object object)
object
- updateSearchIndex()
public static void setUseSystemClassLoader(boolean useSystemClassLoader)
ServiceContext.setUseSystemClassLoader(boolean)
public static boolean isUseSystemClassLoader()
ServiceContext.isUseSystemClassLoader()
public static Connection getDatabaseConnection()
Copyright © 2024 OpenMRS Inc.. All rights reserved.