You are here: Jython Script Interfaces > Utility functions (HL7, HTTP, XML, DICOM, Date-time, Misc) - available to all scripts

example interface filesJython User API to MD Link utility functions

MD Link Jython code can access several utility functions through the engine object, described below. The functions on this page don't directly manipulate the engine, like other functions such as engine.cancel(). Rather, these utility functions do jobs that you could do yourself if you wrote your own library. MD Link provides them for convenience.

These functions are organized into the categories of HL7, HTTP (with example interface files), Databases, XML, DICOM, X12, Date/Time, and Miscellaneous.

HL7

HL7Message makeHL7Message()

Creates a new HL7 message object. The object will be empty except for an MSH segment with some basic fields.

Returns

the new HL7 message object.

HL7Message makeHL7Message(string messageAsString)

Creates a new HL7 message object from a string.

Returns

the new HL7 message object.

Throws

java.lang.IllegalArgumentException - if the supplied message string could not be parsed.

HL7Message makeHL7MessageFromXMLDocument(Document xmlDoc)

Create an HL7Message object from the given XML document. This is typically used to parse the incoming message of an execution. For example:

hl7msg = engine.makeHL7MessageFromXMLDocument(engine.inputDom)

Returns

the new HL7 message object.

Throws

java.lang.IllegalArgumentException - if an HL7 message could not be found in the supplied XML document.

HL7Segment makeHL7Segment(string segmentAsString)

Creates a new HL7 segment object. This segment object will not be a part of any message object until it is added to one, via HL7Message.addSegment(int,HL7Segment) or similar.

Parameters

segmentAsString - an HL7 segment in string form. eg. 'ZYX|a|b|c'.

HL7Segment makeHL7Segment(string segmentId, int numFields)

Creates a new HL7 segment object. This segment object will not be a part of any message object until it is added to one, via HL7Message.addSegment(int,HL7Segment) or similar.

Parameters

segmentId - the desired segment ID. Typically 3 characters, eg. 'EVN', 'PID', etc.

numFields - must be greater than or equal to 0.

Throws

InvalidArgumentException - if numFields is less than 0.

Document makeXMLDocumentFromHL7Message(string xmlPath, HL7Message hl7msg)

Create an XML document from the given HL7Message object. This is typically used to create the output message of a task execution, for example:

engine.outputDom = engine.makeXMLDocumentFromHL7Message('TaskData', hl7msg)

You must pass in as the first argument the XML path of where you want the HL7 message text to be put. If the output schema of your Custom Task is something other than the default, then you will need to compensate for that here. For example:

engine.outputDom = engine.makeXMLDocumentFromHL7Message('TaskData/outputMessage', hl7msg)

Returns

The new XML document.

 

HTTP

Requests

 

MD Link provides five main HTTP functions for acting as a client of web services:

engine.httpPost()

engine.httpPut()

engine.httpPatch()

engine.httpGet()

engine.httpDelete()

These functions are appropriate for communicating with many styles of web service: RESTful, SOAP, HL7 FHIR, and more.

For RESTful, use the functions as-is.

For SOAP, these functions don't do anything extra to build or parse the SOAP envelopes. You will need to do that yourself.

For HL7 FHIR, MD Link also provides these parallel functions:

engine.fhirPost()

engine.fhirPut()

engine.fhirPatch()

engine.fhirGet()

engine.fhirDelete()

The difference between httpPost() and fhirPost() is that fhirPost() will use default values for the 'Accept' and 'Content-Type' request headers which are more appropriate for FHIR. For example: "application/fhir+json" instead of "application/json".

 

These functions all take a URL string as a mandatory first argument. The URL can start with either http:// or https://. After that, these functions accept these optional arguments:

headers

A python dictionary of HTTP headers to send as part of the request.

The keys of this dictionary are the header names. The values of this dictionary are the header values. Pass in only strings for both keys and values.

Defaults: For certain headers, if you don't supply them in this argument, then this API will supply defaults. The default for 'Content-Type' is 'text/plain', unless this API does automatic type conversion on the body as described below. In those cases, the default 'Content-Type' will be appropriate to the type of the body that this API detected eg. application/json or application/xml, or the FHIR versions of those. If you want to omit such a default header from the request, pass a value of None for that key in this argument. This API will honour most such requests to omit the header. Notable exceptions include 'Content-Type' and 'Content-Length'.

Character sets / encodings: If you don't include a "charset=" parameter in 'Content-Type', or you don't supply 'Content-Type' at all, then this API will add "charset=UTF-8" to the request's 'Content-Type' header. The default 'Accept-Charset' is also UTF-8.

body

A string or other object to send as the body of the request.

Automatic type serialization: If this argument is a string, then this API will send it as-is, after encoding it according to the Content-Type header's charset. If this argument is a python dictionary or list, then this API will automatically serialize it to a JSON string before sending. If this argument is an XML DOM Document object, then this API will automatically serialize it to an XML string before sending. If this argument is any other type of object, then this API will convert it to a string using its Java "toString()" method before sending. This API will try to supply an appropriate value for the Content-Type header in these cases.

Automatic type detection: Similar to "automatic type conversion", this API will detect if this argument is a JSON string or an XML string, and supply an appropriate value for the Content-Type header.

truststorefilepath

A string which is a file path of a Java Key Store (JKS) file.

For HTTPS connections only. Useful for self-signed certificates.

truststorepassword

A string which is the password of the JKS file referred to by the 'truststorefilepath' argument.

hostnameverification

A string representing your desired level of hostname verification.

For HTTPS connections only. Valid values for this argument are "allow-all", "browser-compatible", and "strict".

oauth

A dictionary containing credentials and options for the OAuth 2.0 authorization protocol.

This API supports only the "client credentials" grant type of OAuth, and only two sub-types thereof: "client secret" and "JWT". This API supports only these because it is intended to interact with backend systems i.e. web services, not interactive websites.

Keys for the "client credentials / client secret" type:

Keys for the "client credentials / JWT" type:

okstatuscodes

A list of HTTP status code integers which this API will consider "OK".

This means that this API will refrain from throwing an exception if it receives any status code in this list from the HTTP server. The default is [200, 201, ..., 299].

timeout

Maximum time that this API will wait for a response from the HTTP server.

This value is in seconds. If the server doesn't respond in this time or less, then this function will throw an exception.

 

Responses

 

All http* and fhir* functions return an "HttpResponse" object.

It has four data fields:

status (an integer)

The status code of the response which the HTTP server returned eg. 200 for OK, 401 for Unauthorized. By default, status codes that aren't between 200 and 299 will cause the function to throw an exception, and therefore not return an HttpResponse object. So if you want to see a 401 in this field then you will need to include 401 in the "okstatuscodes" argument.

headers (a Python dictionary)

The headers of the response which the HTTP server returned.

body (a string)

The body (if there is one) of the response which the HTTP server returned.

bodyJson (a Python dictionary or list) 

A parsed version of the response body, if it is valid JSON. If it isn't, then this field will be None.

 

Examples

 

response = engine.httpGet('http://localhost:8080/get-test', timeout=20)

print response.status, response.headers, response.body

response = engine.httpPost('http://localhost:8080/post-test', body='request body')

print response.status, response.headers, response.body

 

Example Interface Files

 

In the folder C:\Program Files\MD Link <VERSION>\doc\help\examples, there are .xcs files that demonstrate this API. Many are self-contained. That is: you can run them without having to do any setup.

See Also

 

HTTP with OAuth

 

Databases

 

The following functions interact with JDBC-compliant databases:

 

engine.getConnection(driverClassName, url, username, password, timeoutInSeconds)

engine.select(connection, sqlString, params, maxRows)

engine.insert(connection, sqlString, params)

engine.update(connection, sqlString, params)

engine.delete(connection, sqlString, params)

engine.executeSql(connection, sqlString, params)

engine.makeDateTime(dateTimeString)

engine.makeDate(dateString)

engine.makeTime(timeString)

 

Below is a Jython example which inserts a row into a table, then does a SELECT to get and print every element in the table, up to a maximum of 100 elements.

driver = 'org.postgresql.Driver'
url = 'jdbc:postgresql://localhost:5432/postgres'
username = 'postgres'
password = 'password'
conn = engine.getConnection(driver, url, username, password)
try:
    values_to_insert = [93468231, 'Smith', 'John', engine.makeDateTime('1942-04-18 05:45:22')]
    engine.insert(conn, "INSERT INTO patients VALUES (?, ?, ?, ?)", values_to_insert)
    for item in engine.select(conn, "SELECT * FROM patients;", [], 100):
        print str(item)
finally:
    conn.close()

 

XML

Element addXMLElement(Document document, string newElementName, string text)

Like addXMLElement(org.w3c.dom.Element,string,string) but this method takes a document argument; the new element will be added to the document's root element.

Element addXMLElement(Element element, string newElementName, string text)

Creates a new XML element as a child of the specified element.

Parameters

newElementName - the desired tag name for the new element.

text - text to add under the new element, if any. If no text is desired, pass in an empty string ('').

Returns

the new element. (It will have already been added to the document.)

void appendText(Document document, string text)

Like appendText(org.w3c.dom.Element,string) but this method takes a document argument; the text will be added to the document's root element.

void appendText(Element element, string text)

Add some text under the specified XML element.

Document makeXMLDocument(string rootElementName)

Creates a new XML document object.

Returns

the new XML document.

string xmlDocumentToString(Document document, boolean preserveSpace)

Get a string representation of an XML document.

Parameters

preserveSpace - optional; defaults to False. If False, then the returned string representation will be formatted and indented in an easy-to-read way, rather than preserving the spacing of the original exactly.

Returns

a string representation of the specified XML document.

string xmlElementToString(Element element, boolean preserveSpace)

Get a string representation of an XML element. Same as xmlDocumentToString(Document,boolean) except that this functions takes an Element object instead.

Parameters

preserveSpace - optional; defaults to False. If false, then the returned string representation will be formatted and indented in an easy-to-read way, rather than preserving the spacing of the original exactly.

Returns

a string representation of the specified XML element and all of its (recursive) children.

Element xmlCreateElement(Node node, string xpath)

Creates an empty element at the given XPath, relative to the given node (document or element).

Parameters

node - Reference node - either a Document or Element object.

xpath - A simple XPath, for example 'ADT_A01/MSH/MSH.1-Field_Separator'.

Returns

the element that was created. It will have been already added to the document in question.

list xmlGetAllAttributeValues(Node node, string xpath)

Gets all values of a given XPath that identifies attributes.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath identifying the attributes. Can be of any complexity, for example, to get a list in a CDA document of all the 'assigningAuthorityName' values which are under a 'patientRole' element, and also under an 'id' element with a 'root' attribute value of 'OID1', you could use "//patientRole/id[@root='OID1']/@assigningAuthorityName".

Also, there is some support for namespace prefixes in the XPath. For example, if the 'patientRole' and 'id' elements had a namespace prefix of 'v3', then you could specify "//v3:patientRole/v3:id[@root='OID1']/@assigningAuthorityName".

Returns

A list of strings representing the values of all matched attributes.

list xmlGetAllElementsText(Node node, string xpath)

Gets the text contained in all of the elements identified by the given XPath.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath identifying the elements. Can be of any complexity, for example, to get a list in a CDA document of all of the 'originalText' values that are under an 'administrativeGenderCode' element which has a 'code' attribute of value 'F', you could use "//administrativeGenderCode[@code='F']/originalText".

Also, there is some support for namespace prefixes in the XPath. For example, if the 'administrativeGenderCode' and 'originalText' elements had a namespace prefix of 'v3', then you could specify "//v3:administrativeGenderCode[@code='F']/v3:originalText".

Returns

A list of strings representing the text content of all matched elements.

string xmlGetAttributeValue(Node node, string xpath)

Returns the value of the attribute specified by an XPath. If there is more than one such attribute, the first one is used.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath identifying the attribute. Can be of any complexity, for example, to get from a CDA document the first 'assigningAuthorityName' value which is under a 'patientRole' element, and also under an 'id' element with a 'root' attribute value of 'OID1', you could use "//patientRole/id[@root='OID1']/@assigningAuthorityName".

Also, there is some support for namespace prefixes in the XPath. For example, if the 'patientRole' and 'id' elements had a namespace prefix of 'v3', then you could specify "//v3:patientRole/v3:id[@root='OID1']/@assigningAuthorityName".

Returns

The attribute value as a string, of None if the attribute is not found in the document.

string xmlGetElementText(Node node, string xpath)

Gets the text contained in all the element identified by the given XPath. If there is more than one such element, then the first one is used.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath identifying the element. Can be of any complexity, for example, to get from a CDA document the first 'originalText' value that is under an 'administrativeGenderCode' element which has a 'code' attribute of value 'F', you could use "//administrativeGenderCode[@code='F']/originalText".

Also, there is some support for namespace prefixes in the XPath. For example, if the 'administrativeGenderCode' and 'originalText' elements had a namespace prefix of 'v3', then you could specify "//v3:administrativeGenderCode[@code='F']/v3:originalText".

Returns

The content of the element as a string, or None if the element is not found.

list xmlGetNodes(Node node, string xpath)

This function is like xmlGetAllElementsText and xmlGetAllAttributeValues combined, and does not get the text contents but rather returns the DOM nodes. It can accept an XPath argument that identifies both elements and attributes.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath string.

Returns

A list of DOM Node objects.

Document xmlMakeDocument(string inputString)

Creates an XML document from the given input string. The input string can be a root element name, or an entire XML document as a string. For example, both of the calls below will work:

engine.xmlMakeDocument('TaskData')

engine.xmlMakeDocument('''<TaskData> <group> <item>value1</item> <item>value2</item> </group> </TaskData>''')

Parameters

inputString - a string: either an element name, or an entire XML document.

Returns

An XML DOM Document object.

Document xmlMakeDocumentFromFile(string filePath)

Parses an XML file on disk.

Parameters

filePath - The absolute path (i.e. directory and filename) of the file which contains the XML document.

Returns

An Document object.

void xmlWriteDocumentToFile(string filePath, Document document)

Write an XML document to a file.

Parameters

filePath - The absolute path (i.e. directory and filename) of the file to write to. If this file already exists, it will be overwritten.

document - The XML DOM document to be written.

Returns

Nothing.

void xmlRemoveAll(Node node, string xpath)

Remove nodes (such as elements or attributes) from an XML document.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath, of any complexity, which identifies the nodes to remove. For example, to remove all 'assigningAuthorityName' attributes which are under 'id' elements in a CDA XML document, you could use an XPath argument of "//id/@assigningAuthorityName".

Also, there is some support for namespace prefixes in the XPath argument. If the 'id' element had a namespace prefix of 'v3', then you could specify "//v3:id/@assigningAuthorityName".

Returns

Nothing.

void xmlSetAllAttributeValues(Node node, string xpath, string value)

Set all attributes that match a given XPath to a given value. If no such attributes exist in the document, then do nothing.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath, of any complexity, which identifies the attributes whose values should be set.

value - The desired attribute value.

Returns

Nothing.

void xmlSetAllElementsText(Node node, string xpath, string value)

For all elements that match a given XPath, set their text context to a given value. If no such elements exist in the document, then do nothing.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath, of any complexity, which identifies the elements whose text content should be set.

value - The desired text content of the elements.

Returns

Nothing.

void xmlSetAttributeValue(Node node, string xpath, string value)

Set the attribute that matches a given XPath to a given value. If more than one attribute in the document matches the xpath, then only the first one will be modified. If no such attribute exists in the document, then the attribute will be created, then the value set.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath which identifies the attribute whose value should be set. This can be an XPath of any complexity if the attribute already exists, but can only be a simple XPath if the element does not exist and needs to be created.

value - The desired attribute value.

Returns

Nothing.

xmlSetElementText(Node node, string xpath, string value)

For the element that matches a given XPath, set its text context to a given value. If more than one element in the document matches the xpath, then only the first one will be modified. If no such element exists in the document, then the element will be created, then the value set.

Parameters

node - Reference node - either a Document or Element object.

xpath - An XPath, of any complexity which identifies the element whose text content should be set. This can be an XPath of any complexity if the element already exists, but can only be a simple XPath if the element does not exist and needs to be created.

value - The desired text content of the elements.

Returns

Nothing.

DICOM

DicomElement dicomGetElement(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Get the dicom element from the dicom object. eg. engine.dicomGetElement(dicomObj, 'TransferSyntaxUID')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

Returns

the dicom element from the dicom object.

void dicomRemoveElement(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Remove the dicom element from the dicom object. eg. engine.dicomRemoveElement(dicomObj, 'TransferSyntaxUID')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

string dicomGetElementType(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Get the dicom element type from the dicom object. eg. engine.dicomGetElementType(dicomObj, 'TransferSyntaxUID')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

Returns

the dicom element type.

int dicomGetElementVM(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Get the dicom element value multiplicity(VM) from the dicom object. eg. engine.dicomGetElementVM(dicomObj, 'TransferSyntaxUID')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

Returns

the dicom element value multiplicity.

Object dicomGetElementValue(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Get the dicom element value from the dicom object. eg. engine.dicomGetElementValue(dicomObj, 'TransferSyntaxUID')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

Returns

the dicom element value.

void dicomSetElementValue(org.dcm4che2.data.DicomObject dicomObject, tagObject, valueObject)

Set the element value of the dicom object. eg. engine.dicomSetElementValue(dicomObj, 'TransferSyntaxUID' ,'1.2.840.10008.1.2')

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

valueObject - element value

boolean dicomElementHasItems(org.dcm4che2.data.DicomElement dicomElement)

Check for items in dicom element. eg. engine.dicomElementHasItems(dicomElement)

Parameters

dicomElement - DicomElement

Returns

true if dicom element has items.

int dicomElementItemsCount(org.dcm4che2.data.DicomElement dicomElement)

Find the number of items in the dicom element. eg. engine.dicomElementItemsCount(dicomElement)

Parameters

dicomElement - DicomElement

Returns

the number of items in the dicom element.

void dicomAddSequenceElement(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Add the sequence element to the dicom object with the default capacity = 10.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

void dicomAddSequenceElement(org.dcm4che2.data.DicomObject dicomObject, tagObject, int capacity)

Add the sequence element to the dicom object with provided capacity.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

capacity - capacity number

void dicomElementAddDicomObject(org.dcm4che2.data.DicomElement dicomElement, org.dcm4che2.data.DicomObject dicomObject, int index)

Add the dicom object to the dicom element at the specified position. eg. engine.dicomElementAddDicomObject(dicomElement, dicomObject, 2)

Parameters

dicomElement - DicomElement

dicomObject - DicomObject

index - position

void dicomElementAddDicomObject(org.dcm4che2.data.DicomElement dicomElement, org.dcm4che2.data.DicomObject dicomObject)

Append the dicom object to the dicom element. eg. engine.dicomElementAddDicomObject(dicomElement, dicomObject)

Parameters

dicomElement - DicomElement

dicomObject - DicomObject

DicomObject dicomElementGetDicomObject(org.dcm4che2.data.DicomElement dicomElement, int index)

Get the dicom object from the dicom element at the specified position. eg. engine.dicomElementGetDicomObject(dicomElement, 2)

Parameters

dicomElement - DicomElement

index - position

Returns

the dicom object from the dicom element at the specified position.

boolean dicomElementHasDicomObjects(org.dcm4che2.data.DicomElement dicomElement)

Check whether the dicom element has dicom objects. eg. engine.dicomElementHasDicomObjects(dicomElement)

Parameters

dicomElement - DicomElement

Returns

true if the dicom element has dicom objects.

void dicomElementRemoveDicomObject(org.dcm4che2.data.DicomElement dicomElement, org.dcm4che2.data.DicomObject dicomObject)

Remove the dicom object from the dicom element. eg. engine.dicomElementRemoveDicomObject(dicomElement, dicomObject)

Parameters

dicomElement - DicomElement

dicomObject - DicomObject

void dicomElementRemoveDicomObject(org.dcm4che2.data.DicomElement dicomElement, int index)

Remove the dicom object from the dicom element at the specified position. eg. engine.dicomElementRemoveDicomObject(dicomElement, 2)

Parameters

dicomElement - DicomElement

index - position

void dicomElementSetDicomObject(org.dcm4che2.data.DicomElement dicomElement, org.dcm4che2.data.DicomObject dicomObject, int index)

Set the dicom object of the dicom element at the specified position. eg. engine.dicomElementSetDicomObject(dicomElement, dicomObject, 2)

Parameters

dicomElement - DicomElement

dicomObject - DicomObject

index - position

DicomObject dicomGetNestedDicom(org.dcm4che2.data.DicomObject dicomObject, tagObject)

Get the nested dicom object from the parent dicom object. eg. engine.dicomGetNestedDicom(dicomObject, ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1])

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'ScheduledProcedureStepSequence' or tag num 0x00400100 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1] or tag num array [0x00400100, 1, 0x00400008, 1]

Returns

the nested dicom object from the parent dicom object.

DicomObject dicomGetFileMetaInfo(org.dcm4che2.data.DicomObject dicomObject)

Get the file meta info dicom object from the parent dicom object. eg. engine.dicomGetFileMetaInfo(dicomObject)

Parameters

dicomObject - DicomObject

Returns

the file meta info dicom object from the parent dicom object.

DicomObject dicomGetCommand(org.dcm4che2.data.DicomObject dicomObject)

Get the command dicom object from the parent dicom object. eg. engine.dicomGetCommand(dicomObject)

Parameters

dicomObject - DicomObject

Returns

the command dicom object from the parent dicom object.

DicomObject dicomGetDataset(org.dcm4che2.data.DicomObject dicomObject)

Get the dataset dicom object from the parent dicom object. eg. engine.dicomGetDataset(dicomObject)

Parameters

dicomObject - DicomObject

Returns

the dataset dicom object from the parent dicom object.

string dicomGetTagName(org.dcm4che2.data.DicomElement dicomElement)

Get the dicom element tag name. eg. engine.dicomGetTagName(dicomElement)

Parameters

dicomElement - DicomElement

Returns

the dicom element tag name.

string dicomGetDateTime(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat)

Get the date-time from the dicom object in the specified format.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

Returns

the date-time from the dicom object in the specified format.

string[] dicomGetDateTimes(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat)

Get the date-times from the dicom object in the specified format.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

Returns

the date-times from the dicom object in the specified format.

String dicomGetDateTimeRange(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat)

Get the date-time range in the dicom object.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

Returns

the date-time range in the dicom object.

void dicomSetDateTime(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat, string dateTime)

Set the date-time in the dicom object.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

dateTime - eg. '20101218'

void dicomSetDateTimes(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat, string[] dateTimes)

Set the date-times in the dicom object.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

dateTimes - eg. ['20131120', '20121017', '20090908']

void dicomSetDateTimeRange(org.dcm4che2.data.DicomObject dicomObject, tagObject, string dateTimeFormat, string fromDate, string toDate)

Set the date-time range in the dicom object.

Parameters

dicomObject - DicomObject

tagObject - May be either a tag name -eg. 'PatientName' or tag num 0x00100010 or tag path array ['ScheduledProcedureStepSequence', 1, 'ScheduledProtocolCodeSequence', 1, 'CodeValue'] or tag num array [0x00400100, 1, 0x00400008, 1, 0x00080100]

dateTimeFormat - format of the date-time -eg. 'yyyyMMdd'. For more formatting tips refer to SimpleDateFormat javadoc.

fromDate - eg. '20101216'

toDate - eg. '20110625'

DicomObject dicomLoadObjectFromFile(string dicomFileName)

Load the dicom file into a dicom object.

Parameters

dicomFileName - eg. r'C:\temp\input\sample.dcm'

Returns

the dicom object.

void dicomSaveObjectToFile(org.dcm4che2.data.DicomObject dicomObject, string outFileName)

Save dicom object to a file.

Parameters

dicomObject - DicomObject

outFileName - eg. r'C:\temp\input\sample.dcm'

void dicomSaveImageToFile(string dicomFileName, int frameNum, string imageFormat, string outFileName)

Extract a image frame from the dicom input file and save it to the output file.

Parameters

dicomFileName - eg. r'C:\temp\input\sample.dcm'

frameNum - image frame index eg. 3

imageFormat - eg. 'jpg'

outFileName - eg. r'C:\temp\input\imageFrame3.jpg'

List dicomQuery(...)

Query the DICOM - Service Control Provider (SCP) for the dicom files and/or store the queried dicom files to a DICOM - Service Control User (SCU). The order should be followed for the first three parameters (respondingIp, respondingPort, respondingAE). For example:

respondingIp = '10.168.0.113'

respondingPort = '106'

respondingAE = 'PACS_SCP'

 

engine.dicomQuery(respondingIp, respondingPort, respondingAE, \

q = {'PatientName':'Boris^Katich', 'StudyDate':'20091121'},\

options={'L' : 'QRSCU:11113',\

'cmove' : 'QRSCU', \

'cstore' : '1.2.840.10008.5.1.4.1.1.7', \

'cstoredest' : r'C:\temp\dicomReceivedFiles'})

Parameters

respondingIp - string. DICOM Service Control Provider (SCP) IP.

respondingPort - string. DICOM Service Control Provider (SCP) port.

respondingAE - string. DICOM Service Control Provider (SCP) application entity.

q - dictionary. Multiple query filter options in the form of the python dictionary.

options - dictionary. Multiple query settings in the form of the python dictionary.

Returns

a list of matched dicom objects.

List dicomQueryModalityWorklist(...)

Query the DICOM - RIS system for the modality worklist entries. The order should be followed for the first three parameters (respondingIp, respondingPort, respondingAE). For example:

respondingIp = '10.168.0.113'

respondingPort = '106'

respondingAE = 'MW_SCP'

 

engine.dicomQueryModalityWorklist(respondingIp, respondingPort, respondingAE, \

q = {'PatientName':'Boris^Katich'},\

options={'mod' : 'MA',\

'date' : engine.getCurrentDateTime('yyyyMMdd')})

Parameters

respondingIp - string. DICOM Service Control Provider (SCP) IP.

respondingPort - string. DICOM Service Control Provider (SCP) port.

respondingAE - string. DICOM Service Control Provider (SCP) application entity.

q - dictionary. Multiple query filter options in the form of the python dictionary.

options - dictionary. Multiple mwl query settings in the form of the python dictionary.

Returns

a list of matched dicom mwl objects.

void dicomSendFile(...)

Send the DICOM file to DICOM - Service Control Provider (SCP). The order should be followed for the first four parameters (filePath, receivingIp, receivingPort, receivingAE).

For example:

filePath = r'C:\temp\sample.dcm'

receivingIp = '10.168.0.113'

receivingPort = '106'

receivingAE = 'PACS_SCP'

 

engine.dicomSendFile(filePath, receivingIp, receivingPort, receivingAE, \

options = {'L' : 'DVTK_QR_SCU:11113'})

Parameters

filePath - string. DICOM file location.

receivingIp - string. DICOM Service Control Provider (SCP) IP.

receivingPort - string. DICOM Service Control Provider (SCP) port.

receivingAE - string. DICOM Service Control Provider (SCP) application entity.

options - dictionary. Multiple send settings in the form of the python dictionary.

X12

MD Link is distributed with Google's X12 library . Here we provide some wrapper functions for that library, for convenience. Full documentation on this library is here.

X12Simple x12ParseTransactionFromFile(string filePath)

Reads a file on disk and turns it into a parsed X12 object.

Parameters

filePath - Absolute path (i.e. directory and filename) of the file in question.

Returns

An 'X12Simple' object.

X12Simple x12ParseTransactionFromString(string x12Transaction)

Parses an X12 string.

Parameters

x12Transaction - An X12 transaction in string format.

Returns

An 'X12Simple' object.

x12WriteTransactionToFile(string filePath, X12Simple x12Transaction)

Writes an X12 transaction object to a file.

Parameters

filePath - Absolute path (i.e. directory and filename) of the file in question.

x12Transaction - An X12 transaction object.

Date/time

string addToDate(string date, string field, int amount)

Add the amount to the date field. For example:

engine.addToDate('20110216', 'DAY', 3)

returns '20110219'.

Parameters

date - accept strings of the form yyyyMMdd.

field - should be one of ['YEAR', 'MONTH', 'DAY'].

amount - value to add to date field.

Returns

a string representation of the provided date after addition.

string addToTime(string time, string field, int amount)

Add the amount to the time field. For example:

engine.addToTime('093420', 'MINUTE', -4)

returns '093020'.

Parameters

time - accept strings of the form HHmmssSSS format (ss and SSS are optional).

field - should be one of ['HOUR', 'MINUTE', 'SECOND', 'MILLISECOND'].

amount - value to add to time field.

Returns

a string representation of the provided time after addition.

string addToDateTime(string dateTime, string field, int amount)

Add the amount to the dateTime field. For example:

engine.addToDateTime('20120216093420347', 'MILLISECOND', -36)

returns '20120216093420311'.

Parameters

dateTime - accept strings of the form yyyyMMddHHmmssSSS format (ss and SSS are optional).

field - should be one of ['YEAR', 'MONTH', 'DAY', 'HOUR', 'MINUTE', 'SECOND', 'MILLISECOND'].

amount - value to add to dateTime field.

Returns

a string representation of the provided dateTime after addition.

int yearsBetween(string oldDate, string newDate)

Calculate the number of years between oldDate and newDate. For example:

engine.yearsBetween('19820915', '19960222')

returns 13.

Parameters

oldDate - accept strings of the form yyyyMMdd.

newDate - accept strings of the form yyyyMMdd.

Returns

the number of years between oldDate and newDate.

int age(string birthDate)

Returns the age of a person, given their date of birth. For example:

engine.age('19470318')

returns 66.

Parameters

birthDate - accept strings of the form yyyyMMdd.

Returns

the age.

string getCurrentDateTime(string dateTimeFormat)

Get the current date time in the specified dateTimeFormat. For example:

engine.getCurrentDateTime('yyyy-MM-dd-HH:mm:ss:SSS')

returns '2011-03-28-16:57:21:508'.

 

engine.getCurrentDateTime("'Today is' dd 'and time is' HH:mm")

returns 'Today is 28 and time is 17:02'.

Parameters

dateTimeFormat - accept strings in any form.'yyyy-MM-dd-HH', 'yyyy/MM/dd', 'HH:mm:ss:SSS' , "'Current time is' HH:mm" , etc. For more formatting tips refer to SimpleDateFormat javadoc.

Returns

the current date time in the specified dateTimeFormat.

string convertDateTimeFormat(string dateTime, string oldFormat, string newFormat)

Convert the specified dateTime into the newFormat. For example:

engine.convertDateTimeFormat('10 11 2005', 'MM dd yyyy', 'yyyy-MM-dd')

returns '2005-10-11'.

 

engine.convertDateTimeFormat('24/09-07 30/45:678', 'dd/MM-hh mm/ss:SSS', 'MM-dd-HH:mm:ss:SSS')

returns '09-24-07:30:45:678'.

Parameters

dateTime - dateTime in the oldFormat. Accept strings in any form.'yyyy-MM-dd-HH', 'yyyy/MM/dd', 'HH:mm:ss:SSS' , "'Current time is' HH:mm" , etc. For more formatting tips refer to SimpleDateFormat javadoc.

oldFormat - format of dateTime. Accept strings in any form.'yyyy-MM-dd-HH', 'yyyy/MM/dd', 'HH:mm:ss:SSS' , "'Current time is' HH:mm" , etc. For more formatting tips refer to SimpleDateFormat javadoc.

newFormat - desired return date format.

Returns

a string representation of the provided dateTime in newFormat.

int epochMillis()

Returns

The number of milliseconds since the UNIX epoch (00:00:00 UTC January 1, 1970).

int epochSeconds()

Returns

The number of seconds since the UNIX epoch (00:00:00 UTC January 1, 1970).

Date/time comparison functions

There are several functions for comparing dates and time strings. They all accept two string argument and return a boolean. Functions starting with 'date' accept strings of the form yyyyMMdd. Functions starting with 'time' accept strings of the form HHmmssSSS format (ss and SSS are optional). Functions starting with 'dateTime' accept strings of the form yyyyMMddHHmmssSSS format (ss and SSS are optional). Use these functions like this:

if engine.timeIsGreaterThanOrEqualTo(timeFromMsg, '1200'):

        ...

The complete list of available functions is:

Miscellaneous

LookupTable createLookupTable(string path, ...)

Creates a new lookup object. The path parameter is mandatory. Other optional parameters are:

ignorecase, keycolumn, valuecolumn, delimiter, escape_char_for_doublequotes, reread_file_if_modified, defaultvalue, and defaultaction.

Among defaultvalue and defaultaction, only one should be provided. If neither defaultvalue nor defaultaction is provided as parameter, then default behavior on a nonexisting key is to fail execution. Optional parameters can be provided in any order. For example:

path = r'c:\cygwin\tmp\lookup.csv'

Creates a lookup with default values for optional parameters.

lookup = engine.createLookupTable(path)

value = lookup.getValue('abc') #returns value for key = 'abc'.

Creates a lookup with keycolumn = 2, valuecolumn = 1 and returns value 'XYZ' for a nonexisting key.

lookup = engine.createLookupTable(path, keycolumn = 2, valuecolumn = 1, defaultvalue = 'XYZ')

Creates a lookup which ignores case, uses backslash as escape char for double quotes and cancels execution on a nonexisting key.

lookup = engine.createLookupTable(path, ignorecase = True, escape_char_for_doublequotes = '\\', defaultaction = 'cancel')

Creates a lookup which uses tab as delimiter and updates lookup if the file is modified.

lookup = engine.createLookupTable(path, delimiter = '\t', reread_file_if_modified = True)

Note: For better performance create the lookup table object in the 'Load' script, rather than the beginning of the 'Run' script.

Parameters

path - Absolute path to the lookup file. For example r'c:\cygwin\tmp\lookup.csv'

ignorecase - boolean. If set to True, ignores upper- and lower-case during key lookup. (default is False).

keycolumn - integer. Index of 'key' column. (default is 1).

valuecolumn - integer. Index of 'value' column. (default is 2).

delimiter - string (1 character only). Delimiter that separates fields. (default is ',').

escape_char_for_doublequotes - string (1 character only.) Escape character for double quotes. Accepts two values (default is ") and other is backslash '\\'.

reread_file_if_modified - boolean. If true, then the source lookup file will be re-read (and the lookup object's set key/value pairs fully updated) if the file is ever modified while the solution is running. (default is False).

defaultvalue - string. If provided, then getValue() will return this if the key argument does not exist in the lookup table.

defaultaction - string. Like the 'defaultvalue' option, this determines the behavior in the case where the key argument does not exist in the lookup table. This option allows you to specify an action other than outputting a constant string, as 'defaultvalue' does. Valid values are 'passthrough' (which will output the input value), 'cancel' (cancel the task execution), and 'fail' (fail the execution). Default is 'fail'.

Returns

a lookup object.

list splitTextByWidth(string text, int width)

Split the text by width. For example:

engine.splitTextByWidth('The erythrocyte sedimentation rate (ESR), also called a sedimentation rate or Westergren ESR.', 30)

returns list - ['The erythrocyte ', 'sedimentation rate (ESR)', ', also called a sedimentation ', 'rate or Westergren ESR.'].

Parameters

text - content to split.

width - max line length.

Returns

a list of strings.

string fileToString(string filepath)

Read the contents of a file, and return the contents as a string.

Parameters

filepath - The absolute path (i.e. directory and filename) of the file you want to read.

Returns

The contents of that file, as a string.

string stringToFile(string filepath, string contents)

Write a string to a file.

Parameters

filepath - The absolute path (i.e. directory and filename) of the file you want to write to. If this file already exists, it will be overwritten.

contents - The string that you want to write to the file.