Wiki Spaces

Documentation
Projects
Resources

Get Help from Others

Q&A: Ask OpenMRS »
Discussion: OpenMRS Talk »
Real-Time: IRC Chat

Documentation

Skip to end of metadata
Go to start of metadata

Overview

This module was created as a proof of concept (for embedding Groovy into OpenMRS) and to serve as a base module for other modules that want to use Groovy scripting as well.

For a quick overview of some of the cool groovy features, see this spring source training video

Setup

Download and install the Groovy module omod file from the module repository.
(You can download the code from github: https://github.com/openmrs/openmrs-module-groovy)

Usage

Find and click on the Groovy Scripting Form link within the Groovy Module section of OpenMRS' administration page. You should be taken to a simple web form with a single textarea followed by a "GO" button. Type any valid Groovy script into the textarea and click the button to execute the script.

Some variables are automatically provided (most of these represent the API service):

  • admin
  • cohort
  • concept
  • encounter
  • form
  • locale
  • logic
  • obs
  • patient
  • person
  • user
  • fn (as of 2.2)

Using fn

The special fn variable provides access to convenience functions:

  • fn.sql("select count() from users")
    Runs the given SQL and returns the result set (only allows reading from database)
  • fn.sql("update users set name='Super-duper User' where user_id = 1", false)
    Runs SQL that can write to the database

Scheduling Groovy Scripts

As of version 2.2, you can schedule Groovy scripts to run automatically using the scheduler.

  1. Create and save a groovy script
  2. Create a task (Scheduler within administration page) using the Schedulable Class: org.openmrs.module.groovy.GroovyTask
  3. Add a property as follows:
    1. name: "script name" (the literal text, 'script name' without quotes... not the name of your script)
    2. value: the name of your script

Accessing Other Module Services

When trying to access the service of another module within a Groovy script, you might see a an error like:

If you do, try loading the service like this:

Groovy script examples

List 100 concepts?

Display some encounters?

Display some observations

Search for patients by name

Create providers for all users

Create providers for users with specified roles

Execute SQL commands

Manage modules

Delete program

pid = 4

// Get program
p = program.getProgram(pid)
println "<p><b>Program ${p.programId}: ${p.name} ${p.concept}</b><br>"

program.purgeProgram(p)

Add Locations

Using groovy only:

import org.openmrs.Location

println """
<h2>Adding locations:</h2>
<table  border=1>
  <tr><th></th><th>Location name</th></tr>"""

locationNames = [ "Boucan Carre", "Belladeres", "Thomonde", "Lascahobas", "Cerca la Source", "Mirebalais", "St Marc SSPE", "POZ", "Petite Riviere", "Verrettes", "St Nicholas HSN", "Tilory", "Cerca Cavajal", "Thomassique", "Savanette", "Baptiste", "Maissade", "Dufailly"]

i = 0
locationNames.each() {
  def location = new Location()
  println "<tr><td>${++i}</td><td>${it}</td></tr>"
  location.setName("${it}")
  location.setCountry("Haiti")

ls = org.openmrs.api.context.Context.locationService
ls.saveLocation(location)
}

println  "</table>"

Using mysql:

println """
<h2>Adding locations:</h2>
<table  border=1>
  <tr><th></th><th>Location name</th></tr>"""

location = [ "Boucan Carre", "Belladeres", "Thomonde", "Lascahobas", "Cerca la Source", "Mirebalais", "St Marc SSPE", "POZ", "Petite Riviere", "Verrettes", "St Nicholas HSN", "Tilory", "Cerca Cavajal", "Thomassique", "Savanette", "Baptiste", "Maissade", "Dufailly"]

i = 0
location.each() {
  println "<tr><td>${++i}</td><td>${it}</td></tr>"
  admin.executeSQL("""
  insert into location (name, country, creator, date_created, uuid)
    values("${it}", 'Haiti', '1', now(), uuid() )""", false)
}

println  "</table>"

Print user and patients

println """
<h2>The following  people are both patients and users in your system:</h2>
<table  border=1>
<tr><th></th><th>Internal  ID</ht><th>Patient</th><th>User</th></tr>"""

i = 0
admin.executeSQL("""
select patient_id,  identifier, system_id from patient_identifier, users
where patient_id in  (select user_id from users, patient where user_id = patient_id)
and patient_id =  user_id
and not  patient_identifier.voided""", false).each  {
println  "<tr><td>${++i}</td><td>" +  it.join("</td><td>") + "</td></tr>"}
println  "</table>"

Delete duplicate patients

//List of userids with duplicate system_ids
for (uid in [20587, 22087, 18239, 18255, 18259, 18335, 18338, 18347,
18352, 18356, 18377, 18387, 18389, 18393, 18401, 18407,
18414, 18432, 18434, 18507, 17021 ] ) {

u = user.getUser(uid)
println "<h2>Original: ${u.systemId} ${u.userId} ${u.givenName} ${u.familyName}"
// Change and save system id for the first patient and print
u.setSystemId(user.generateSystemId())
user.saveUser(u,null)
println "Replaced with: ${u.systemId} ${u.userId} ${u.givenName} ${u.familyName}</h2><br>"


}

Modify observation to use coded answer

Delete observations

/ Delete observation
p = patient.getPatient(15919)
e = encounter.getEncounter(39696)
// Print name and location for patient
println "<h2>${p.givenName} ${p.familyName} ${e.location}</h2>"

// print information about the observations
for (o in obs.getObservations(p,false)) {
if (o.location =\~ 'Rwaza') {
println "${o.location} ${o.obsId} ${o.concept.name} : ${o.getValueAsString(locale)}<br/>"
}
}

// obs_id for location 33 (Rwaza)
def numbers =

// get observations and purge them
for (obsno in numbers) {
thisObs = obs.getObs(obsno)
println "${thisObs.location} ${thisObs.obsId} ${thisObs.concept.name} ${thisObs.getValueAsString(locale)}<br />"
obs.purgeObs(thisObs)


}

Delete concept and concept answers

conceptID = 3823


c = concept.getConcept(conceptID);
println "<h2>${c.conceptId} ${c.name}</h2>"
for (ca in c.getAnswers()) {
println "<h2>${ca.concept.conceptId} ${ca.conceptAnswerId} ${ca.answerConcept} </h2>"

//  This works, but isn't saved
c.removeAnswer(ca)
}

//This doesn't save the removed answers
concept.saveConcept(c)

// This proves that it is removed
println "Second pass\n"
for (ca2 in c.getAnswers()) {
println "<h2>${ca2.concept.conceptId} ${ca2.conceptAnswerId} ${ca2.answerConcept} </h2>"
}

// This won't work until the answers are deleted
//concept.deleteConcept(concept.getConcept(conceptID))

Change program and workflow

// What are the program_id and workflow_id?
//  Get these from the GUI
//  IMPORTANT:  These variables are real for Rwanda and HEART FAILURE PROGRAM and DIAGNOSIS WORKFLOW
//  Otherwise...replace with the real numbers
pid = 11
wid = 21
// Get program
p = program.getProgram(pid)
println "<p><b>Program ${p.programId}: ${p.name} ${p.concept}</b><br>"

// Get program workflow
pw = program.getWorkflow(wid)
println "<p><b>Workflow ${pw.programWorkflowId}: ${pw.concept} ${pw.concept.name}</b> ${pw.program.programId} <br>${pw.program}</p>"

//  Get all states and delete the states for the appropriate workflows
for (s in program.getStates()) {
println "<p><b>States ${s.programWorkflowStateId}: ${s.concept} ${s.concept.name}</b><br>${s.programWorkflow} </p>"
pw.removeState(s)
}

//  Save the removed workflow and save the program
//  NOTE: Uncomment the next 2 lines after testing
//p.removeWorkflow(pw)
//program.saveProgram(p)

Change person

// Change the Given name for a Person

// Variables
person_id = 20754
new_given_name = "MBASABYAMAHORO"
new_birthdate = "1980-01-01 00:00:00.0"

// Second patient
//person_id = 1588
//new_given_name = "Claudine"
//new_family_name = "MUKARURANGA"

// Get person
p = person.getPerson(person_id)
name = p.getNames()
bd = p.getBirthdate()

// Print out current values
given_name = p.getGivenName()
family_name = p.getFamilyName()
println "<p>Original given name: ${given_name}</br>"
println "<p>Original family name: ${family_name}</br>"
println "<p>Birthdate: ${bd}</br>"

// Get person name
pn = p.getPersonName()
println "<p>Person name: ${pn}</br>"
pn.setGivenName(new_given_name)
//pn.setFamilyName(new_family_name)

// Add and save the corrected name
p.addName()
person.savePerson(p)

// Print the corrected values
cname = p.getNames()
println "<h3>Corrected name:  ${cname}</h3></br >"

Or this simple script

import org.openmrs.PersonName
p = person.getPerson(1);
p.addName(new PersonName("Given", "middle name", "Family"));
person.savePerson(p);

Change form id

This used when we duplicate an InfoPath form into htmlform, and want to change all the infopath forms to use htmlform view/edit capabilities.

// Original formId of Infopath form
infopathFormId = 82

// formId of htmlform form
htmlformId = 188

f = form.getForm(infopathFormId)
htmlform = form.getForm(htmlformId)

for (e in encounter.getEncounters(null,null,null,null,[f],null,null,true)) {
   if (e.getForm().getFormId() == infopathFormId) {
       e.setForm(htmlform)
   }
   encounter.saveEncounter(e)
}

Retire form

// Set variables
form_id = 99
user_id = 7
reason = 'Form no longer needed'
def today= new Date()

u = user.getUser(user_id)

f = form.getForm(form_id)

// Print form information
println "<h2>Old Form: ${f} ${f.name}"
println " ${f.retired} ${f.retiredBy} ${f.retiredReason} ${f.dateRetired} "

// Set form to retired
f.setRetired(true)
f.setRetiredBy(u)
f.setRetiredReason(reason)
f.setDateRetired(today)

form.saveForm(f)

// Print form information
println "Saved Form: ${f} ${f.name}"
println " ${f.retired} ${f.retiredBy} ${f.retiredReason} ${f.dateRetired} </h2>"

Delete forms (with no encounters)

import org.openmrs.FormField

// delete all formfield rows, but need to null the parent first
for (ff in form.getAllFormFields() ) {
  // set parent_form_field to NULL
  ff.setParent(null)
  form.saveFormField(ff) }

for (ff2 in form.getAllFormFields() ) {
  form.deleteFormField(ff2) }

for ( form_id in [9,10,11,12] ) {
  // get form_id
  f = form.getForm(form_id)

  // delete the formentry_xsn rows  // This next line requires a change to the groovy module (see GRV-18)
  formEntry.deleteFormEntryXsn(f)

  // Print form information
  println "<h2>deleting form: ${f} ${f.name}"

  // delete each form
  form.deleteForm(f)
}

Retire drug

// Set variables
drug_id = 11
user_id = 7
reason = 'test retire'
def today= new Date()

u = user.getUser(user_id)
d = concept.getDrug(drug_id)

// Print drug information
println "<h2>Old drug: ${d} ${d.name}"
println " ${d.retired} ${d.retiredBy} ${d.retireReason} ${d.dateRetired} </h2>"

// Set form to retired
d.setRetired(true)
d.setRetiredBy(u)
d.setRetireReason(reason)
d.setDateRetired(today)
concept.saveDrug(d)

Remove birthdates

This is useful when no birthdate is known and bogus ages are selected (ie. 106 years old)

// remove bogus birthdates

for (person_id in [4,5] ) {

  // Get person
  p = person.getPerson(person_id)

  // Print out current values
  bd = p.getBirthdate()
  pn = p.getPersonName()
  println "<p>Person name: ${pn}  Birthdate: ${bd}</br>"

  // Remove birthdate
  p.setBirthdate(null)
  p.setBirthdateEstimated(false)
  person.savePerson(p)
}

Print concept sets and names 

set = concept.getConcept(3642);
for (sm in set.conceptSets) {
    println(sm.conceptSetId + " , " + sm.concept.conceptId + " , " 
                 + sm.conceptSet.conceptId + " , " + sm.sortWeight + " , "
                 + sm.dateCreated + " , " + sm.uuid);
    println(" = ");
    println(sm.concept.names);
    println(" "); 
}

Void concept names

// Void these concept_names
def conceptNameIds = [13932, 13662, 13778,13670,7105,11259,13310, 13935, 13731, 13460,13284,10000,9860];

def reason = 'Duplicate name removed for OpenMRS 1.9'
def today= new Date()
def user_id = 1010

u = user.getUser(user_id)

for (conceptNameId in conceptNameIds) {

    org.openmrs.ConceptName name = concept.getConceptName(conceptNameId);
    org.openmrs.Concept c = name.getConcept()

    name.setVoided(true);
    name.setVoidedBy(u);
    name.setDateVoided(today);
    name.setVoidReason(reason);

    println "<h2>${name.name} </h2>"

    concept.saveConcept(c);
}

Change ConceptSource

 

def sourceName = 'IMB Rwanda' 
def newName = 'Rwanda' 
def newCode = '' 
def newDesc = 'Rwanda harmonized concepts for MoH and IMB'

source = org.openmrs.api.context.Context.getConceptService().getConceptSourceByName(sourceName); 
println "<p><b>Name: ${source.getConceptSourceId()} ${source.getName()}</b><br>"   

source.setName(newName) 
source.setHl7Code(newCode) 
source.setDescription(newDesc)

Change concept_map comment (for OpenMRS 1.9 upgrade)

def oldTypeName = "Map Type: 3";
def typeName = "Map Type: BROADER-THAN";
def sourceNames = ["ICD-10","SNOMED NP","ICD-10-WHO NP", "ICD-10-WHO 2nd"];
for (sourceName in sourceNames) {
    org.openmrs.ConceptSource source = concept.getConceptSourceByName(sourceName);
    List conceptMaps = concept.getConceptsByConceptSource(source);
    for (conceptMap in conceptMaps) {
      if (oldTypeName.equals(conceptMap.getComment())) {
        println "<p><b>Map: ${conceptMap.concept}: ${conceptMap.comment}</b><br>"
        conceptMap.setComment(typeName);
        concept.saveConcept(conceptMap.getConcept());
      }
    }
}
def typeName = "Map Type: SAME-AS";
def sourceNames = ["PIH","org.openmrs.module.mdrtb",
     "local","AMPATH","ZL/PIH installation in Haiti",
     "ZL/PIH installation in Haiti - Boston server",
     "MVP/CIEL at PIH"];
for (sourceName in sourceNames) {
    org.openmrs.ConceptSource source = concept.getConceptSourceByName(sourceName);
    List conceptMaps = concept.getConceptsByConceptSource(source);
    for (conceptMap in conceptMaps) {
      if (!typeName.equals(conceptMap.getComment())) {
        println "<p><b>Map: ${conceptMap.concept}: ${conceptMap.comment}</b><br>"
        conceptMap.setComment(typeName);
        concept.saveConcept(conceptMap.getConcept());
      }
    }
}

Remove role

roleName = "Patient Registration"
us = org.openmrs.api.context.Context.userService
r = us.getRole(roleName)
println "<p><b>Role: ${r.role}<br>description: ${r.description}<br> uuid: ${r.uuid}</b><br>"
us.purgeRole(r)

A more complex example

Trigger Sync for a Patient (may not be complete)

Make REST web service calls

Make sure you don't save your password in a script! You can enter your password into this script and run it, but make sure to remove your password before saving the script!

The following script sets up basic authentication, makes a call to the REST Web Services module, and then displays the result.

Copy the JSON-formatted result into an editor like Sublime Text 2 with a JSON formatter (in Sublime Text 2, Tools > Command Palette > Package Control : Install Package > Pretty JSON) to quickly format the JSON into a more legible form.

Look for HTML Forms that have the same concept repeated, without extra contextual information

Update a Person Attribute and insert an Obs given a value from another Obs

 

/**********
If  concepts
 celular del paciente que dio el paciente o celular modificado  are 
later than latest changed by date for cel attribute
* place them in the celular history and then in the patient attribute
********/

  import org.openmrs.api.context.Context
    import org.openmrs.api.EncounterService;
    import org.openmrs.module.groovy.GroovyUtil
    import org.openmrs.Encounter;
    import java.lang.Integer;
    import org.openmrs.EncounterType;
    import org.openmrs.Person;
    import org.openmrs.Patient;
    import org.openmrs.Obs;
    import org.openmrs.PersonAttribute;
    import org.openmrs.Concept;
    import org.hibernate.SessionFactory;
    import org.openmrs.api.FormService;
    import org.openmrs.api.ObsService;
    import org.openmrs.api.ConceptService;
    import org.openmrs.api.PersonService;
    import org.openmrs.Location;
    
    sf = Context.serviceContext.applicationContext.getBean(SessionFactory.class)
    ObsService os = Context.getObsService()
    ConceptService cs = Context.getConceptService();
    PersonService ps = Context.getPersonService();
    
def sql(s) { admin.executeSQL(s,false) }

rs = sql("""
select p.patient_id as pid,REPLACE(FORMAT(o.value_numeric, 0), ',', '') as celular from patient p, obs o, person_attribute pa where p.patient_id = o.person_id and p.patient_id = pa.person_id and pa.person_attribute_type_id = 8 and o.concept_id in (331,138) and o.voided=0 and p.voided=0 and pa.voided=0 and IF(pa.date_changed is not null, pa.date_changed, pa.date_created) < o.obs_datetime and pa.value != o.value_numeric;
""")

rs.each { row ->
          (pid,celular) = row
       Obs o = new Obs();
print celular
       o.setConcept(cs.getConcept(260));
       o.setDateCreated(new Date());
       o.setCreator(Context.getAuthenticatedUser());
       o.setLocation(new Location(1));
       o.setObsDatetime(new Date());
       o.setPerson(new Person(pid));
       o.setValueText(celular.toString());
       os.saveObs(o,"inserted by groovy script");
      
       PersonAttribute pa = new PersonAttribute();
       def t = ps.getPersonAttributeType(new Integer(8));
       pa.setAttributeType(t);

       def p = ps.getPerson(new Patient(pid));
       pa.setPerson(new Person(pid));
       pa.setValue(celular.toString());
       pa.setDateChanged(new Date());
       p.addAttribute(pa);
       ps.savePerson(p);

     //print e
}

A slightly groovier way

/**********
If  concepts
 celular del paciente que dio el paciente o celular modificado  are 
later than latest changed by date for cel attribute
* place them in the celular history and then in the patient attribute
********/

  import org.openmrs.api.context.Context
    import org.openmrs.api.EncounterService;
    import org.openmrs.module.groovy.GroovyUtil
    import org.openmrs.Encounter;
    import java.lang.Integer;
    import org.openmrs.EncounterType;
    import org.openmrs.Person;
    import org.openmrs.Patient;
    import org.openmrs.Obs;
    import org.openmrs.PersonAttribute;
    import org.openmrs.Concept;
    import org.hibernate.SessionFactory;
    import org.openmrs.api.FormService;
    import org.openmrs.api.ObsService;
    import org.openmrs.api.ConceptService;
    import org.openmrs.api.PersonService;
    import org.openmrs.Location;
    
    sf = Context.serviceContext.applicationContext.getBean(SessionFactory.class)
    ObsService os = Context.getObsService()
    ConceptService cs = Context.getConceptService();
    PersonService ps = Context.getPersonService();
    
def sql(s) { admin.executeSQL(s,false) }

rs = sql("""
select p.patient_id as pid,REPLACE(FORMAT(o.value_numeric, 0), ',', '') as celular from patient p, obs o, person_attribute pa where p.patient_id = o.person_id and p.patient_id = pa.person_id and pa.person_attribute_type_id = 8 and o.concept_id in (331,138) and o.voided=0 and p.voided=0 and pa.voided=0 and IF(pa.date_changed is not null, pa.date_changed, pa.date_created) < o.obs_datetime and pa.value != o.value_numeric;
""")

rs.each { row ->
  (pid,celular) = row

  def o = new Obs()
  def pa = new PersonAttribute()
  o.concept = concept.getConcept(260)
  o.dataCreated = new Date()
  o.creator = Context.authenticatedUser
  o.location = new Location(1)
  o.obsDatetime = new Date()
  o.person = new Patient(pid)
  o.encounter = new Encounter(enc_id)
  o.valueText = celular
  obs.saveObs(o,"inserted by groovy script")
  
  pa.person = new Patient(pid)
  pa.attributeType = person.getPersonAttributeType(8)
  pa.value = celular
  pa.dateChanged = new Date()
}

Troubleshooting

java.lang.ClassFormatError: Invalid method Code length 82342 in class file Script1

Solution: Java only allows methods that are 64K long. Reduce the size of your groovy script.