Backend built-in functions¶
This API page describes built-in functions defined on Backend level. As the Backend component integrates an Interpreter, all Interpreter built-in functions are still available.
When the Backend component starts, it builds-up the Backend Scolvo script using the backend.scolvo as entry point. The built-up script is loaded to the Interpreter and holds the Backend business logic.
Backend built-in function groups¶
Scheduling functions
Authentication related functions
Internal communication functions
External communication functions
Document handling functions
Reporting functions
Misc functions
Scheduling functions¶
This function group implements functionality for scripting-space automation, it supports addJob, addImmediateJob and deleteJob functions.
addJob() function¶
This function defines a repeated job for the Backend.
Function syntax
void addJob(cronExpression, jobName, groupName, triggerExpression)
Where the given cronExpression is a mandatory String describing the repetition, the jobName mandatory String defines the name of the repeated job, the groupName mandatory String defines the job group and the triggerExpression defines the repeating expression (usually event name without ‘on’, e.g.: ‘CalculateUserFees’).
The CRON expression is validated by Quartz scheduler during appropriate object creation, next invoke time is logged as debug information for validation purposes. Job is created with the unique name of groupName - jobName pair, which can be used when deleting the job.
1function initScheduledJobs() {
2 addJob("0 0 8 ? * * *", "morningDataImportJob", "DataImport", "MorningDataImport");
3 addJob("0 0 12 ? * * *", "noonDataImportJob", "DataImport", "NoonDataImport");
4}
5
6initScheduledJobs();
7
8function onMorningDataImport(originId) {
9 importUsers();
10 importData();
11}
12
13function onNoonDataImport(originId) {
14 importData();
15}
addImmediateJob() function¶
This function defines a start-time executed job for the Backend Scheduler.
Function syntax
void addImmediateJob(jobName, groupName, triggerExpression)
Where the given jobName mandatory String defines the name of the repeated job, the groupName mandatory String defines the job group and the triggerExpression defines the repeating expression (usually event name without ‘on’, e.g.: ‘CalculateStartTimeFees’).
1function initScheduledJobs() {
2 addImmediateJob("startTimeFeeCalculationJob", "Statistics", "CalculateFeesAtStart");
3}
4
5initScheduledJobs();
6
7function onCalculateFeesAtStart(originId) {
8 calculateFees();
9}
deleteJob() function¶
This function deletes a job defined with jobGroup and jobName. It returns if the action is successful.
Function syntax
boolean deleteJob(jobName, groupName)
Where the given jobName mandatory String and the groupName mandatory String defines the job.
1function cleanUpUnnecessaryJobs() {
2 if (deleteJob("morningDataImportJob", "DataImport")) {
3 info("Job has been deleted successfully.");
4 } else {
5 info("Scheduled job DataImport - morningDataImportJob delete has been failed");
6 }
7}
Authentication functions¶
This function group implements functionality for managing users security-related representation in the Authentication Service (actually a Keycloak Server). Defined functions are:
createKeycloakUser
updateKeycloakUser
deleteKeycloakUser
getAuthToken
These function keep in-sync the Backend’s User database and the Keycloak data.
createKeycloakUser() function¶
This function creates a user with given attributes, it returns the Keycloak id of the created user.
Function syntax
String createKeycloakUser(userConfig)
Where the given userConfig contains the user attributes (see the example for details). Usual usage is when a new User created on administration UI or by self registration.
1function onSelfRegistering(originId) {
2 var userDao = $IN.data.map;
3
4 var userConfig = {
5 "id": userDao.id,
6 "enabled": true,
7 "name": userDao.name,
8 "email": userDao.email,
9 "username": userDao.username,
10 "password": userDao.password,
11 "realmRoles": ["authenticated", "otherRelevantRole"]
12 };
13
14 var keycloakUserId = createKeycloakUser(userConfig);
15 debug("Created keycloak user is: " + keycloakUserId);
16 userDao.put("keycloakId", keycloakUserId);
17 userDao.put("role", "otherRelevantRole");
18 return userDao;
19}
20
21function onSelfRegistered(originId) {
22}
1function onUserInserting(originId) {
2 var userDao = $IN.data.map;
3
4 var userConfig = {
5 "id": userDao.id,
6 "enabled": true,
7 "name": userDao.name,
8 "email": userDao.email,
9 "password": userDao.password,
10 "username": userDao.username,
11 "realmRoles": ["authenticated", userDao.role]
12 };
13 return createKeycloakUser(userConfig);
14}
15
16function onUserInserted(originId) {
17 var userDaoFromRequest = $IN.data.map;
18 info("Updating created user with KeycloakId: " + $IN.data.preScriptResult + " ...");
19 var userDao = {
20 "id": userDaoFromRequest.id,
21 "keycloakId": $IN.data.preScriptResult,
22 "changeType": "UPDATE"
23 };
24 updateTypeDefinition("user", userDaoFromRequest.id, userDao);
25 info("User has been updated with KeycloakId.");
26}
updateKeycloakUser() function¶
This function updates a user definition with given attributes.
Function syntax
void updateKeycloakUser(userConfig)
Where the given userConfig contains the user attributes (see the example for details). Usual usage is when a User update is done on administration UI or in the profile.
1function onUserUpdating(originId) {
2}
3
4function onUserUpdated(originId) {
5 var userDao = $IN.data.map;
6 var userConfig = {
7 "id": userDao.id
8 };
9 if (userDao.containsKey("name")) {
10 userConfig.put("name", userDao.name);
11 }
12 if (userDao.containsKey("email")) {
13 userConfig.put("email", userDao.email);
14 }
15 if (userDao.containsKey("username")) {
16 userConfig.put("username", userDao.username);
17 }
18 if (userDao.containsKey("role")) {
19 userConfig.put("realmRoles", ["authenticated", userDao.role]);
20 }
21 if (userDao.containsKey("password")) {
22 userConfig.put("password", userDao.password);
23 }
24 if (userDao.containsKey("status")) {
25 userConfig.put("enabled", userDao.get("status") == "active");
26 }
27 updateKeycloakUser(userConfig);
28}
deleteKeycloakUser() function¶
This function deletes a user definition identified by email address.
Function syntax
boolean deleteKeycloakUser(emailAddress)
Where the given emailAddress is a String identifying a user. The result value reflects if the deletion is successful or not. Usual usage is when a User is deleted on the administration UI.
1function onUserDeleting(originId) {
2 var userInfo = $IN.data.map;
3 var userDao = getUserById(userInfo.id);
4 debug("Deleting user: " + userDao.email);
5 if (deleteKeycloakUser(userDao.email)) {
6 info("The user with email '" + userDao.email + "' has been successfully deleted.");
7 } else {
8 error("User delete in Keycloak has been failed.");
9 }
10}
11
12function onUserDeleted(originId) {
13}
getAuthToken() function¶
This function gets a valid auth token for given email. Backend events usually contain the client authentication token (accessible form script space). For the cases where the authentication token is not yet defined, or it is not available, but the user’s email and password are available, this function call gets a valid authentication token for further internal requests. For example at self-registration time there is no authentication token (as before the successful Keycloak registration it is not possible to get one), but we know the username and password - a valid token can be received and used for other internal service calls.
Function syntax
String getAuthToken(emailAddress, password)
Where the given emailAddress and the password are Strings and the result access token is given in form of String.
1function onSelfRegistering(originId) {
2 var userDao = $IN.data.map;
3
4 var userConfig = {
5 "id": userDao.id,
6 "enabled": true,
7 "name": userDao.name,
8 "email": userDao.email,
9 "username": userDao.username,
10 "password": userDao.password,
11 "realmRoles": ["authenticated", "someRoleName"]
12 };
13
14 var keycloakId = createKeycloakUser(userConfig);
15 debug("Created keycloak user is: " + keycloakId);
16 var userToken = getAuthToken(userDao.email, userDao.password);
17
18 // Do your logic, use the userToken as needed for internal calls
19 // e.g. store it to be able to use in further requests
20 putTheTokenToTheStore(userDao.id, userToken);
21
22 userDao.put("keycloakId", keycloakId);
23 userDao.put("role", roleEditor);
24
25 return userDao;
26}
27
28function onSelfRegistered(originId) {
29 var userDaoFromRequest = $IN.data.map;
30 var token = getTheTokenFromTheStore(userDaoFromRequest.id);
31 if (token != null) {
32 var response = doTheSpecialInternalRequest(token);
33 if (response.getStatusCode() == 200) {
34 var someResult = response.getData();
35 sendWelcomeEmail(userDaoFromRequest.id, someResult);
36 } else {
37 error("Error when requesting some result: " + response.getData());
38 }
39 } else {
40 error("No token found for the given user.");
41 }
42}
Internal Communication functions¶
This function group implements functionality for internal communication between clients. It supports broadcastDatagram function sending internal message to all or to a dedicated client and function createDataSyncElement helping in the creation of data synchronization message elements.
broadcastDatagram() function¶
It has the dataChangeDg - a Map<String, Object> (mandatory parameter) - and the clientId parameter - an optional String parameter.
Function syntax
void broadcastDatagram(dataChangeDg, clientId)
Where the valid keys of the dataChangeDg Map<String, Object> parameter are:
originId - String (mandatory key), represents the origin Id,
typeDefinition - String (mandatory key), defined the name of the type definition,
typeDefinitionVersion - long (mandatory key), represents the version number of the type definition,
changeSet - List<Map<String, Object>> parameter (mandatory key, the list must be non-empty), it holds the row definitions.
And the clientId can be the clientId of an existing client or null to send the message to all clients).
1function onDoSometingRequest(originId) {
2 var requestData = $IN.data;
3 var clientId = $IN.data.clientId;
4 debug("Received request with parameters: " + requestData.toString());
5
6 var response = calculateSomeResoinse();
7 // Send the Backend-side calculated response to the requesting client:
8 publishBroadcastToClient("doSometingResponse", [{"someKeyForTheresponse": response}], clientId);
9}
10
11function publishBroadcastToAllClients(typeDefinitionName, changeSetList) {
12 publishBroadcastToClient(typeDefinitionName, changeSetList, null);
13}
14
15function publishBroadcastToClient(typeDefinitionName, changeSetList, clientId) {
16 if(!changeSetList.isEmpty()) {
17 var broadcastData = {
18 "originId": uuid(),
19 "typeDefinitionVersion": nowInMillis(),
20 "typeDefinition": typeDefinitionName,
21 "changeSet": changeSetList
22 };
23 broadcastDatagram(broadcastData, clientId);
24 }
25}
createDataSyncElement() function¶
It has the typeDefinitionName and the data parameter describing rows.
Function syntax
DataSyncRpElement createDataSyncElement(typeDefinitionName, data)
Where the typeDefinitionName is a mandatory String, the data is a mandatory List of Map<String, Object> objects, and the function returns the appropriate DataSyncRpElement.
1function onDataSync(userId, deviceType) {
2 debug("onDataSync " + userId + " deviceType: " + deviceType);
3 // For a superUser only the MHUB is the available client type
4 if (userId == "superUser") {
5 return dataSyncByAdministrator(deviceType);
6 }
7
8 // Check user details to make decision about the sync content:
9 var user = getUserById(userId);
10 debug("Device type is: " + deviceType);
11 if (user.role == "administrator") {
12 return dataSyncForAdministrator(deviceType);
13 } else if (user.role == "someCustomerSpecificRole") {
14 return dataSyncForSomeCustomerSpecificRole(user);
15 }
16
17 warn("No dedicated DataSync case, returning empty data for user " + user.role);
18 return [];
19}
20
21function dataSyncForAdministrator(deviceType) {
22 debug("Creating data sync content for administrator");
23 // For an administrator role only the MHUB is the available client type
24 if (deviceType == "MHUB") {
25 return [
26 createDataSyncElement("user", getUsers()),
27 ];
28 }
29 return [];
30}
31
32function dataSyncForSomeCustomerSpecificRole(userDao) {
33 debug("Creating data sync content for someCustomerSpecificRole");
34 return [
35 createDataSyncElement("example_table", getExampleRowsForUser(userDao.id))
36 ];
37}
External Communication functions¶
This function group implements functionality for external communication. It supports:
httpDownloadUrl function downloading content from the given URL and saving the content to a file,
httpPost function sending POST request with json body or containing file requests,
httpCall function with generic type of request definition and security configuration possibilities,
sendToDevices function sending Firebase message,
sendEmail function sending email message.
httpDownloadUrl() function¶
It downloads content from the given url to a file defined by fileName parameter (the fileName is taken as pattern).
Function syntax
String httpDownloadUrl(url, fileName)
Where the url is given a mandatory String representing the URL of the desired location, the fileName is a mandatory String, defining the result file name template. Using this template a unique name is generated and returned as result.
1function getTheMoon(originId) {
2 debug("Downloading moon ... ");
3 var moonUrl = "https://spaceplace.nasa.gov/review/all-about-the-moon/the-moon-near-side.en.jpg";
4 var resultFile = httpDownloadUrl(moonUrl, "MyMoonPhoto.jpg");
5
6 debug("My Moon is under: " + resultFile);
7 return resultFile;
8}
httpPost() function¶
This built-in function sends a POST Http request to the given url.
Function syntax
String httpPost(String url, Map<String, String> headers, String jsonContent, Map<String, String> bodyFileDescriptor)
Where the url is given as String (mandatory String parameter), the headers parameters are merged to the request’s header, and the content is sent as jsonContent String or as Map<String, String> bodyFileDescriptor (one of these latter has to be defined, if both are given, then json string is sent). The result is the resonse body, it is returned as String.
1function sendPostRequestWithAuthorizationHeader(originId) {
2 debug("Sending post request ... ");
3
4 var jsonObject = {"key": "value"};
5 var url = "https://eov8qe6o4c0adbw.m.pipedream.net";
6 var headers = {"Authorization": "Basic XYZ", "x": "y"};
7 var result = httpPost(url, headers, jsonObject.toString(), null);
8 debug("The result is: " + result);
9
10 return result;
11}
httpCall() function¶
This built-in function is a generic purpose function to send any kind of Http request, where many parameter can be specified.
Function syntax
HttpResponse httpCall(Map<String, Object> requestDescriptor)
Where the requestDescriptor is the Map<String, Object> representation of the HttpRequest object, the result is a HttpResponse object (definitions of these objects are below).
HttpRequest object attributes¶
String requestMethod - default value is GET, other possible values: HEAD, POST, PUT, PATCH, DELETE, OPTIONS, TRACE,
String url, contains the targeted URL,
Map<String, String> headerParams - all given parameters are put to request headers,
boolean baseAuth - defines if base authentication is used (an alternate solution to but the ready made Authorization header value to headerParams),
String baseAuthUser - in case of baseAuth is true, then the auth user is used when generating appropriate Base64 String,
String baseAuthPw - in case of baseAuth is true, then the auth password is used when generating appropriate Base64 String,
String jsonData - if given, then this content is sent as json body of the request,
Map<String, Object> formData - if jsonData is not given or null, then this content is sent as form data.
HttpResponse object attributes¶
statusCode int, containing the HTTP status code as integer, can be accessed by getStatusCode() call,
data Object, containing the response data, can be accessed using getData() call,
1function sendPostRequestWithAuthorizationHeader(originId) {
2 debug("Sending post request ... ");
3
4 var jsonObject = {"key": "value"};
5 var request = {
6 "requestMethod": "POST",
7 "url": "https://mydream.net",
8 "baseAuth": true,
9 "baseAuthUser": "MyUser",
10 "baseAuthPw": "MyPassword",
11 "headerParams": {
12 "Content-Type": "application/json"
13 },
14 "jsonData": jsonObject.toString()
15 };
16 var response = httpCall(request);
17 debug("The result code is: " + response.getStatusCode());
18 debug("The result data is: " + response.getData());
19
20 return response;
21}
sendToDevices() function¶
This built-in function sends a Firebase request with given parameters to the defined Firebase clients (defined by Firebase tokens). It requires the Firebase related configuration to be set.
Function syntax
void sendToDevices(String title, String body, Map<String, String> data, List<String> registrationTokens)
Where the title, body and data are defining the message, the registrationTokens parameter defines target user audience. In case of any communication error a FirebaseErrorResultException is thrown describing the error cases.
Hint: The List<String> getErrorDetails(), or String getMessage() functions can be used to get error details from FirebaseErrorResultException instance.
1function sendMessageToUsers(originId, tokens) {
2 debug("Sending firebase message ... ");
3
4 try {
5 var data = {
6 "key": "someValue"
7 };
8 sendToDevices("My Important Message", "Dear User, Please do these important staps ...", data, tokens);
9
10 debug("Firebase message has been sent successfully.");
11 } catch (FirebaseErrorResultException e) {
12 error("Error when sending message to firebase users: " + e.getMessage());
13 }
14}
sendEmail() function¶
This built-in function sends an email message with the given parameters. It requies the email sending related configuration to be set.
Function syntax
boolean sendEmail(String from, String toAddressList, String ccAddressList, String subject, String content, List<String> attachments)
Where the from defines the sender email address in String, the toAddressList and ccAddressList are addresses in form of String (separated by coma for multi-address case), the subject and content are describing the message, and the attachments defines the pathes for the attached files (if there is any). It returns true is the sending is successful.
1function sendMessageToUsers(originId, addresses) {
2 debug("Sending email message ... ");
3 // example addreses content: "address1@mydomain.com, address2@mydomain.com"
4 var attachments = ["/app/documents/stepsDescription.pdf"];
5 var result = sendEmail(getEnv("EMAIL_USERNAME"), addresses, null, "Important Information for MyDomain Users", "Message content ...", attachments);
6 if (result) {
7 debug("The message has been sent successfully.");
8 } else {
9 debug("The email message hasn't been sent.");
10 }
11
12}
Document handling functions¶
This function group implements functionality for Cloud handling, Local file handling and import/export related functions. It supports:
Cloud functions
documentGetUrl function generating public URL for a content in a Cloud repository (requires appropriate Cloud repository configuration),
documentPut function uploading local content to the Cloud repository (requires appropriate Cloud repository configuration),
documentDownload function downloading content from the Cloud repository (requires appropriate Cloud repository configuration),
Filesystem functions
createDirectory function creating a directory in local filesystem,
listDirectory function listing the content of a directory in the local filesystem,
fileDelete function deleting an entry (file or directory) from local fileystem,
fileCopy function copying an entry in the local filesystem,
fileMove function moving an entry in the local filesystem,
Export/import functions
writeFile function writing content to a file,
fileToString function reading the content of a file,
writeCsvFile function writing data to CSV format,
readCsvFile function reading CSV file to data,
readExcelFile function reading Excel file to data.
documentGetUrl() function¶
This built-in function gets a public URL (containing autentication) to the given resource path in the configured Cloud repository. (It requires a configured Cloud repository.)
Function syntax
String documentGetUrl(String documentKey)
Where the documentKey is the path of an existing document in the Cloud repository. It return the URL accessing the document in Http GET reuest.
1function uploadCsvFileToCloud(fileName, cloudRelativePath, csvHeaders, content) {
2 var filePath = writeCsvFile(fileName, csvHeaders, content, getCsvFormat());
3 debug("CsvFile is created on path: " + filePath);
4
5 documentPut(filePath, cloudRelativePath);
6 var downloadUrl = documentGetUrl(cloudRelativePath);
7 debug("CsvFile public URL is: " + downloadUrl);
8
9 return downloadUrl;
10}
documentPut() function¶
This built-in function uploads a file to the configured Cloud repository. (It requires a configured Cloud repository.)
Function syntax
void documentPut(String sourcePath, String targetPath)
Where the sourcePath is the path of an existing document in the local filesystem and the targetPath is a path to be created in the Cloud repository.
1function uploadCsvFileToCloud(fileNamePattern, cloudRelativePath, csvHeaders, content) {
2 var filePath = writeCsvFile(fileNamePattern, csvHeaders, content, getCsvFormat());
3 debug("CsvFile is created on path: " + filePath);
4
5 documentPut(filePath, cloudRelativePath);
6 var downloadUrl = documentGetUrl(cloudRelativePath);
7 debug("CsvFile public URL is: " + downloadUrl);
8
9 return downloadUrl;
10}
documentDownload() function¶
This built-in function downloads an entry from the configured Cloud repository. (It requires a configured Cloud repository.)
Function syntax
String documentDownload(String sourcePath, String targetPathPattern)
Where the sourcePath is the path of an existing document in the CloudRepository and the targetPathPattern is a path pattern int the local filesystem. It returns the full path (not the same as given in targetPathPattern parameter) to the downloaded file.
1function downloadCsvFileFromCloud(cloudRelativePath, fileNamePattern) {
2 var filePath = documentDownload(cloudRelativePath, fileNamePattern);
3 debug("CsvFile is created on path: " + filePath);
4
5 return filePath;
6}
createDirectory() function¶
This built-in function creates a directory in the local filesystem. The actual implementation can create only the last directory, the containing path must exist.
Function syntax
boolean createDirectory(String directoryPath)
Where the directoryPath is the path of the directory to be created. It returns true in only case when the directory is created by this call.
1function createSubDirectory(containingDirectory, subDirectory) {
2
3 var targetPath = directory + "/" + subDirectory;
4 if (createDirectory(targetPath)) {
5 return targetPath;
6 }
7
8 return null;
9}
listDirectory() function¶
This built-in function lists an existing directory in the local filesystem.
Function syntax
Map<String, Map<String, Object>> listDirectory(String directoryPath)
Where the directoryPath is the path of the directory to be listed. It returns with the content of the directory with a descriptor containg name, size, type, absolute path and last modification time (see the example below).
1function listDirectoryContent(directoryPath) {
2
3 var content = listDirectory(directoryPath);
4 debug("The result is: " + content);
5 content.keySet().each(function(fileName){
6 debug("----------------------------------");
7 debug(" Actual entry is: " + fileName);
8 var descriptor = content.get(fileName);
9 debug(" Name is: " + descriptor.get("name"));
10 debug(" Type is: " + descriptor.get("fileType"));
11 debug(" Size (in Bytes) is: " + descriptor.get("size"));
12 debug(" Absolute path is: " + descriptor.get("absolutePath"));
13 debug(" Last modified is: " + dateToString(descriptor.get("lastModified"), "yyyy.MM.dd. HH:mm"));
14 });
15
16 return content;
17}
fileDelete() function¶
This built-in function deletes the given path and returns the status of the operation (true if deleted, false oterwise).
Function syntax
boolean fileDelete(String path)
Where the path is the path of the local filestem entry to be deleted. If the given path is a non-empty directory, then it is deleted with its child entries.
1function deleteDirectoryContent(directoryPath) {
2 debug("Deleting directory with its content: " + directoryPath);
3 return fileDelete(directoryPath);
4}
fileCopy() function¶
This built-in function creates a copy of the source file to the given path.
Function syntax
void fileCopy(String sorcePath, String targetPath)
Where the sourcePath is an existing path in the filesystem, and the targetPath is the path where the file copy has to be created. It is possible to copy a simple file entry or a complete directory.
1function backupDirectory(directoryPath, backupDirectoryPath) {
2 debug("Creating backup of directory: " + directoryPath);
3
4 var content = listDirectory(directoryPath);
5 content.keySet().each(function(fileName){
6 var descriptor = content.get(fileName);
7 var sourcePath = descriptor.get("absolutePath");
8 var targetPath = backupDirectoryPath + "/" + descriptor.get("name");
9 fileCopy(sourcePath, targetPath);
10 });
11}
fileMove() function¶
This built-in function moves an existing file to a new path.
Function syntax
void fileMove(String sorcePath, String targetPath)
Where the sourcePath is an existing path in the filesystem, and the targetPath is the new path of the entry.
1function downloadFileFromCloud(cloudRelativePath, targetDirectory, fileName) {
2 var filePath = documentDownload(cloudRelativePath, fileName);
3 debug("File is created on path: " + filePath);
4
5 var targetPath = targetDirectory + "/" + fileName;
6 fileMove(filePath, targetPath)
7 debug("File is moved to path: " + targetPath);
8
9 return targetPath;
10}
writeFile() function¶
This built-in function creates a file with the given content.
Function syntax
String writeFile(String fileNamePattern, String content)
Where the fileNamePattern is the file name pattern of the created file, and the content is a String to be written to the file. It retuns the fupp path of the created file.
1function createMonthlyReport(type, month, content) {
2 var fileNamePattern = "Report_" + type + "_" + month + ".txt";
3
4 var resultPath = writeFile(fileNamePattern, content);
5 debug("Report File is created at: " + resultPath);
6
7 return resultPath;
8}
fileToString() function¶
This built-in function reads a file content and returns it as String.
Function syntax
String fileToString(String filePath)
Where the filePath is the prat of the file to be read.
1function readInputFile(fileName) {
2 var importFilePath = "/import/" + fileName;
3
4 var content = fileToString(importFilePath);
5 if(content != null) {
6 debug("Read content size: " + content.size());
7 } else {
8 debug("No content returned from file " + importFilePath);
9 }
10
11 return content;
12}
writeCsvFile() function¶
This function writes the given content using header columns and formatting parameters to a CSV file. The path of the created file is returned.
Function syntax
String writeCsvFile(String namePattern, List<String> headerColumns, List<List<String>> data, Map<String, Object> csvFormattingParameters)
- Where:
namePattern is a String mandatory parameter, it is used as a basis for filename construction,
headerColumns is a List<String> mandatory parameter, a not empty list of the headers,
data is a List<List<String>> list of content lines (mandatory parameter), a non-empty list of lines,
csvFormattingParameters is a Map<String, Object> (mandatory parameter), see below description for keys and values.
it returns the path of the created file,
it throws FunctionInvokeException in case of errors.
- Details of valid CSV formatting parameters:
The parameters given in Map<String, Object> format,
format - String, name of the CSV format, if not given, then “Default” is used, (valid values are: Default, Excel, InformixUnload, InformixUnloadCsv, MongoDBCsv, MongoDBTsv, MySQL, Oracle, PostgreSQLCsv, PostgreSQLText, RFC4180, TDF), it is used as a basis of other parameters,
delimiter - String, the first character taken as delimiter character,
quote - String, the first character taken as quote character,
nullString - String, it is set as the null-string value for the formatter,
skipHeaderRecord - boolean, its value set to skipHeaderRecord of the formatter,
recordSeparator - String, its value set as record separator,
charset - String, its value is used to create a charset, if not given, then UTF-8 is used.
1function getCsvFormat() {
2 var format = {
3 "delimiter": ";",
4 "quote": null,
5 "nullString": "",
6 "skipHeaderRecord": false,
7 "recordSeparator": "\r\n",
8 "charset": "UTF-8",
9 };
10
11 return format;
12}
13
14function exportDataToCsv() {
15
16 var csvHeaders = ["StoreDevice_Code", "StoreDevice_DeviceTypeName"];
17 var content = [];
18 var storeDevices = getStoreDevicesByStatus("active");
19 storeDevices.each(function(storeDevice) {
20 content.add([storeDevice.deviceCode, storeDevice.deviceTypeName]);
21 });
22
23 var reportName = "Data_" + dateToString(nowInMillis(), "yyyyMMdd_HHmm") + ".csv";
24 var filePath = writeCsvFile(reportName, csvHeaders, content, getCsvFormat());
25 debug("CsvFile is created on path: " + filePath);
26
27 var targetPath = "/export/" + fileName;
28 fileMove(filePath, targetPath);
29
30 return targetPath;
31}
readCsvFile() function¶
This function reads the content of the given CSV file to structured List<Map<String, String>> format.
Function syntax
List<Map<String, String>> readCsvFile(String pathToFile, List<String> headerColumns, Map<String, Object> csvFormattingParameters)
- Where:
pathToFile - is a String (mandatory parameter),
headerColumns - List<String> (mandatory parameter), a not empty list of the headers,
csvFormatParameters - Map<String, Object> (mandatory parameter), see below the description of keys and values,
it returns the content in form of List<Map<String, String>> according to the specified format,
it throws FunctionInvokeException in case of errors.
1function getReadCsvFormat() {
2 var format = {
3 "delimiter": ";",
4 "quote": null,
5 "nullString": "",
6 "skipHeaderRecord": true,
7 "recordSeparator": "\r\n",
8 "charset": "Cp1250",
9 };
10
11 return format;
12}
13
14function importDataFromCsv() {
15 debug("Importing data ....");
16 var filePath = documentDownload("/import/data.csv", uuid());
17 var importHeaders = ["Name", "ID", "Size", "Activity_ID", "Exporter"];
18
19 var parsedData = readCsvFile(filePath, importHeaders, getReadCsvFormat());
20 fileDelete(filePath);
21
22 return parsedData;
23}
readExcelFile() function¶
This function reads the content of the given Excel file (.xls or .xlsx file) to structured format.
Function syntax
Map<String, List<List<Object>>> readExcelFile(String filePath, int numOfColumns)
- Where:
filePath - mandatory parameter String,
numOfColumns - BigInteger mandatory parameter, non-negative number, if 0 is given, then every sheet is checked for its max column,
it returns the sheets defined by lines and cells in form of Map<String, List<List<Object>>>,
it throws FunctionValidationException for invalid parameters, and FunctionInvokeException for processing errors.
1function readImportFromFile(filePath, sheetName) {
2 var result = readExcelFile(filePath, 3);
3
4 var sheet = result.get(sheetName);
5 var fullContent = [];
6 sheet.each(function(line) {
7 var content = "[";
8 line.each(function(cell) {
9 content = content + "'" + cell + "', ";
10 });
11 content = content + "]";
12 fullContent.add(content);
13 });
14 return fullContent;
15}
Reporting repository functions¶
This function group implements functionality for Reporting repository handling. It supports:
downloadReport function to download specific report from Reporting repository,
downloadReport() function¶
This function supports report file downloading from configured Reporting repository. The hendling of the download is asynchronus, in case of success a successTrigger is executed, in case of error the given errorTrigger is called.
Function syntax
void downloadReport(String downloadId, String reportUrl, String reportFileName, String successTrigger, String errorTrigger, Map<String, Object> additionalParameters)
- Where:
downloadId is a String, mandatory parameter,
reportUrl is a String, mandatory parameter,
reportFileName is a String, filename base string used when storing locally the downloaded file,
successTrigger is a String, mandatory parameter, the name of the function to be invoked in case of success,
errorTrigger is a String, optional parameter, the name of the function to be invoked in case of error,
additionalParameters is a Map<String, Object>, optional parameter, parameters that have to be added to trigger parameters
- Trigger parameters are in case of success (these are put to $IN.data map):
id - the corresponding download id,
filePath - the path of the downloaded file in local filesystem,
additional keys and values from additionalParameters map.
- Trigger parameters are in case of error (these are put to $IN.data map):
id - the corresponding download id,
errorCode - the code of the error in form of String,
errorMessage - the error message,
additional keys and values from additionalParameters map.
1function onMontlyTodoReportDownloadSuccess(originId) {
2 debug("The id of the Report download is: '" + $IN.data.id + "' The path of the downloaded file: '" + $IN.data.filePath + "'");
3 debug("The downloadedFile for Store '" + $IN.data.storeName + "' is at " + $IN.data.filePath);
4
5 // Do the logic, e.g. send an email
6
7 var deleteResult = fileDelete($IN.data.filePath);
8 debug("Report file has been deleted with result: " + deleteResult);
9}
10
11function onMontlyTodoReportDownloadError(originId) {
12 error("The MontlyTodoReport download has been failed with id: '" + $IN.data.id + "' The error is: " + $IN.data.errorCode + " - " + $IN.data.errorMessage);
13}
14
15function sendMonthlyTodoReports(dueMonth) {
16 debug("Sending Monthly to-be-done tasks reports about previous month ...");
17 var users = getStoreLeaderUsersWithStore();
18 users.each(function(user) {
19 info("Store: '" + user.storeId + "', Email: '" + user.email + "'");
20 var reportUrl = "https://something/report/monthlyreport/" + user.storeId;
21 var downloadId = uuid();
22
23 var additionalParams = {
24 "email": user.email,
25 "storeName": user.storeName,
26 "name": user.name,
27 "dueMonth": dueMonth
28 };
29 downloadReport(downloadId, reportUrl, "UserReport_" + user.email, "MontlyTodoReportDownloadSuccess", "MontlyTodoReportDownloadError", additionalParams);
30 debug("Download MontlyTodoReport request is sent for store '" + use.storeId + "' ...");
31 });
32}
Misc functions¶
This function group implements a set of utility functions. It supports:
getEnv function returning environment variables,
getDictionaryValue function reading backend dictionary values,
getEnv() function¶
This function retruns the value of the appropriate environment variable defined by the key parameter.
Function syntax
String getEnv(String key)
1function sendMessageToUsers(originId, addresses) {
2 debug("Sending email message ... ");
3 // example addreses content: "address1@mydomain.com, address2@mydomain.com"
4 var attachments = ["/app/documents/stepsDescription.pdf"];
5 var result = sendEmail(getEnv("EMAIL_USERNAME"), addresses, null, "Important Information for MyDomain Users", "Message content ...", attachments);
6 if (result) {
7 debug("The message has been sent successfully.");
8 } else {
9 debug("The email message hasn't been sent.");
10 }
11
12}
getDictionaryValue() function¶
This function retruns the value of the appropriate dictionary key using the specified locale from backend dictionary files (backend_dictionary_*.properties). If the dictionary is not available, then the backend’s default language (defined by DEFAULT_LANGUAGE env variable) is used to resolve the value. If the requested key is not defined, then a null value is returned.
Function syntax
String getDictionaryValue(String key, String locale)
- The function has the following parameters:
key - String, mandatory parameter,
locale - String mandatory parameter.
1function resolveActivityStatusForLocale(status, locale) {
2 return getDictionaryValue(status + "_name", locale);
3}