Web Service Scripts
Web Service Scripts provides a flexible solution to create and publish customized Web Services using Javascript.
You can use REST to interact with the GpsGate Server, but previously you had to create your own adapter if you had to translate the data format to fit your legacy system. This is no longer necessary as you can configure your customized Web Services inside GpsGate Server to communicate with external systems that require specific data formats.
Configuration
1. Log in as Site Admin to the application.
2. Access the application properties
3. Enable the privileges: _EditScriptApp, _EditWebServiceScript and _WebServiceScriptLogin as shown below.
4. Click on Save
Creating a Web Service Script
1. Log in to your application
2. Click on Main Menu > Admin > Development > App Builder.
3. Create a new app
4. Set a new name to your web script app and click on Save.
5. Go to the Web Service Scripts section. Click on the + Script button.
6. Fill in the details for the web service.
7. Click the Edit button. The script editor window shows up with the default script template.
If you have experience with other types of scripts in the GpsGate platform, the editor interface will be familiar.
The list of exposed objects is on the right side. The editable input fields can be used to set test data when clicking the Run Script button.
Example
Usually, a web service script consists of three main parts:
- Parsing the request parameters from the URL or request body
- Interaction with the GpsGate server through exposed JavaScript functions
- Creating the response body
Let's learn how to use the JavaScript framework to implement these steps. Take a look at the API section of the article for further API documentation that is not covered in the example. The current list of exposed functions is limited. It will be extended on a case-by-case basis.
In this example, we create a Web Service to return the latest position of a vehicle. The Web Service consumer system requests the data in the format shown below. It authenticates itself using the credentials specified in the login XML node. The user needs to have _WebServiceScriptLogin, _ReadUsers and _ReadData privileges to be able to access the specified vehicle.
< request >
< login >
< user >username</ user >
< pass >password</ pass ></ login >< vehicleid >123</ vehicleid >
</ request >
|
The service consumer system expects the response in the following format:
< response >
< lat >1</ lat >
< long >2</ long >
</ response >
|
Example script
var xmlReq = xml.parseFromString(request.body);
var user = xmlReq.selectSingleNode( '/request/login/user' ).innerText;
var pass = xmlReq.selectSingleNode( '/request/login/pass' ).innerText;
auth.login(user, pass); // the user needs _WebServiceScriptLogin privilege
var vehicleID = xmlReq.selectSingleNode( '/request/vehicleid' ).innerText;
var user = directory.getUserByID(vehicleID);
if (user != null ) {
var lat = user.trackPoint.position.latitude;
var lon = user.trackPoint.position.longitude;
response.body =
'<response>’ +
‘<lat>’ + lat + ‘</lat>’ +
‘<long>’ + lon + ‘</long>’ +
‘</reponse>’;
} else {
response.body = ' <response><error>Not found</error></response>';
} |
In the object browser, fill the request body with test data, and then click on the Test Script button. You will see the response in the script editor console.
Note: you need to authenticate the web service consumer system to be able to access data. It is a good practice to create a separate user for the service with the minimal necessary privilege set. The AccessFilter plugin makes it possible to control which IP addresses can access your service.
Note: XML format is used in the examples above, but it is also possible to communicate using JSON format (check JSON.stringify(obj) and JSON.parse(str) functions)
Note: API methods can throw exceptions in case of missing privilege, etc. Use try-catch to handle those errors.
Enable logging at runtime
You may enable the log function for Web Service Scripts at runtime by editing the Nlog.config file in the NMEA service folder under the GpsGate Server installation folder (if you are not hosting your own server, please contact support). Under <targets>, you should add a new target entry like this:
|
.
< target name = "TARGET_NAME" xsi:type = "File" fileName = "FILE_NAME" layout = "${longdate} | ${message}" />
. |
where TARGET_NAME is an unique name for the file target and FILE_NAME is the name of the log file you wish to be created with full path to the file. Under <rules>, add an entry like this:
|
< logger name = "NAME_OF_WEB_SERVICE_SCRIPT" minlevel = "Info" writeTo = "TARGET_NAME" />
|
where NAME_OF_WEB_SERVICE_SCRIPT is the name of the click script which you want to log to the file, and TARGET_NAME is the unique name of the target you added above. Data logged through log method in the specified web service script will then be written to the specified file.
API
request:
- body: string
Request body. - query: string
Request query string. - queryParams : NameValueCollection
Represents a collection of query string parameters.
xml:
- parseFromString(strXml) : XmlDocument
Returns a document object that represents the DOM tree of the XML source. - createDocument() : XmlDocument
Returns a new empty xml document object.
JSON: (added in version 4.0.0.2174)
- stringify(object) : string
Converts a value to JSON - parse(str) : object
Parses a string as JSON.
auth:
- login(strUsername, strPassword) : string
Authenticates a user with password and returns session id. - login(strSessionId)
Authenticates a user with session id.
customFields:
- getValues(strNamespace, iObjectID) : array of CustomFieldValue
Returns the Custom Fields for the specified object. Value of strNamespace can be ‘user’ or ‘poi’.
directory:
- getUserByID(iUserID) : GateUser
Returns a user by user id. - getUserByIMEI(strIMEI) : GateUser
Returns a user by IMEI. - getUsers() : array of GateUser
(added in version 4.0.0.2174)
Returns all users in the current application - getLatestRecords(iUserID) : array of MessageRecord
Returns the latest value of variables.
tags (added in version 4.0.0.2174)
- getTags() : array of UserTag
Get all tags in the application. - getTagByName(strName) : UserTag
Returns the usertag having the specified name. - updateUsers(iTagID, userIDsToAdd, userIDsToRemove) : UserTag
Adds/Removes users to/from the specified tag.
geo (added in version 4.0.0.2190)
- reverseGeocode(lat, lng) : Location
Resolves a geo-location into an address.
log(valueOrObject) : void
This function logs value to log file or script editor console.
Types that are not exposed explicitly as root members:
CustomFieldValue
- name : string
The name of the field. - value : string
The value of the filed.
GateUser
- id : int
User id. - name : string
User name. - username: string
User username. - trackPoint: TrackPoint
Latest valid TrackPoint for the user.
UserTag
- id : integer
The id of user tag. - name : string
The name of user tag. - description : string
The description of the user tag. - userIDs : array of integers
User IDs associated to the tag.
MessageRecord
- name: string
Name of the field. - value: object
Value of the field - type: string
Type of the field - unit: string
Unit of the field. - utc: JsDate
Specifies when the value was recorded.
NameValueCollection:
- get(strName) : string
Gets the value associated with the specified key.
XmlNode:
- nodeName : string
The name of this node. - nodeValue : string
The value of this node. - innerText : string
Gets the concatenated values of the node and all its child nodes. - nodeType: int
A code representing the type of the underlying object. - nodeTypeName : string
A type name representing the type of the underlying object. - hasChildNodes : bool
Returns whether this node has any children. - childNodes : XmlNodeList
A NodeList that contains all children of this node. If there are no children, this is a NodeList containing no nodes.
(for(var child in node.childNodes){} also works) - appendChild(XmlNode) : XmlNode
Adds the specified node to the end of the list of child nodes, of this node. - selectNodes(strXPath) : XmlNodeList
Selects a list of nodes matching the XPath expression.
(for(var child in node.childNodes){} also works) - selectSingleNode(strXPath) : XmlNode
Selects the first node that matches the XPath expression.
XmlNodeList:
- length : int
The number of nodes in the list. - [index] : XmlNode
Returns the item from the specified position.
XmlDocument : XmlNode
- createElement(strName) : XmlElement
Creates an element with the specified name. - createTextNode(strText) : XmlText
Creates a text node with the specified content. - outerXml: string
Gets the markup representing this node and all its child nodes.
XmlElement: XmlNode
XmlText: XmlNode