Entities

Entities provisioning

Entity object structure

In the context of the Internet of Things (IoT), an entity represents any monitoring element.

OpenGate offers four types of entities: asset, device, subscription, and subscriber. The resourceType field is used to set the entity type. The following table illustrates the process for setting each entity type:

Entity ResourceType attribute Description Provision
Asset entity.asset The software enables users to create new entities that are distinct from the device environment. see provision of assets
Device entity.device This is a hardware unit. see provision of devices
Subscription entity.subscription This section stores information regarding the contracts with your communication operators. see provision of subscriptions
Subscriber entity.subscriber It is used to store information regarding a specific communication channel. see provision of subscribers

Common objects and attributes

All the entities have several attributes, objects, and arrays in common. The following sections provide further details on these shared objects.

{
  "provision": {
    "administration": {
      "channel": {
        "_current": {
          "value": "wind_farm_channel"
        }
      },
      "organization": {
        "_current": {
          "value": "wind_farm_organization"
        }
      },
      "serviceGroup": {
        "_current": {
          "value": "emptyServiceGroup"
        }
      }
    },
    "device": {
      "identifier": {
        "_current": {
          "value": "wind_mill_id"
        }
      }
    }
  }
}

Identifier attributes

OpenGate supports a variety of entities, each of which is identified by a unique identifier.

Administrative data attributes

  • id: Each Internet of Things (IoT) entity on the platform is assigned a unique identifier automatically by the platform.
  • provision.device.identifier: The customer-generated ID is a string that identifies a device in a specific organisation. HTTP/1.1 201 Created Location: http://api.opengate.es/north/v80/provision/organizations/{organizationName}/devices/device_1 It is imperative that you use this identifier as a URL suffix when you wish to retrieve, update or delete your device.
  • provision.device.communicationModules[].identifier: The customer-generated ID is a string that identifies a communication module.
  • provision.device.communicationModules[].subscription.identifier: It is a customer-generated identifier comprising a string that identifies a subscription.
  • provision.device.communicationModules[].subscriber.identifier: It is a customer-generated identifier comprising a string that identifies a subscriber.

Administration object attributes

It is a requirement for all OpenGate entities to operate within an administrative context.

Attributes

  • organization: the organization that owns the entity.
    • Forbidden in entity update operation
    • Required in entity insert operation
    • Constraints: [a-zA-Z0-9] max 50 chars
  • channel: an administrative grouping method for your entities.
    • Required in entity insert operation.
    • Constraints: [a-zA-Z0-9] max 50 chars
  • administrativeState: see administrativeState values
Organization ID as URL parameter

In entity POST and PUT operations, OpenGate ignores the organisation field because its value is mandatory in the URL.

  • serviceGroup: Service configuration: configuration of services, operations available, etc.
    • Constraints: [a-zA-Z0-9] max 50 chars
    • Forbidden in bundle operations.
  • workgroup: the workgroup is the way to establish the relationships between devices and users. It’s used, for example, when you want to create software bundles.
    • Constraints: [a-zA-Z0-9] max 50 chars
    • This field only applies to OpenGate users.
  • plan (optional): an administrative concept that allows limiting the number of events sent by the device. This concept only applies to devices.
    • Constraints: [a-zA-Z0-9] max 50 chars
    • Forbidden in bundle operations.
    • Optional in entity insert and update operation.
Click to show administrative data as JSON document into a device entity…
{
  "provision": {
    "administration": {
      "channel": {
        "_current": {
          "value": "YOUR_CHANNEL_NAME"
        }
      },
      "organization": {
        "_current": {
          "value": "YOUR_ORGANIZATION_NAME"
        }
      },
      "serviceGroup": {
        "_current": {
          "value": "SERVICE_GROUP_FOR_THE_ENTITY"
        }
      },
      "plan": {
        "_current": {
          "value": "FLOW_RATE_100"
        }
      }
    }
  }
}

Service group

It is of the utmost importance to select the correct entity service group. The service group you choose will determine how OpenGate behaves when managing your devices in the following ways:

  • Permitted operations.
  • This document outlines the process by which the platform transmits scheduled operations to devices.
    • Always: This type is designed for devices that are continuously connected. In this scenario, OpenGate will initiate operations on the devices in accordance with the pre-defined schedule. In the event that the target device is not connected, the operation will be cancelled and an error message will be generated.
    • On-session-connection: In this instance, the platform saves operations for subsequent use. Upon establishing a connection with the platform, the device will be notified of any pending operations and these will be sent to the device. This mode is applicable to devices utilising web sockets or MQTT connectors.
    • On-demand: In this instance, the device will request any outstanding operations. This approach enables devices to conserve battery power and retrieve pending operations when active.
Details

Should you wish for your devices to request all pending operations, you may utilise MQTT connections with the on-demand configuration.

  • Trusted boot: It is a requirement that all messages received by the platform include a field with the trusted boot value. In the absence of this field, OpenGate will reject the message.
  • Device security mode: This option allows you to select the desired security level for communications between the device and platform. The available options are:
    • None: communications are not encrypted.
    • Level 1: One-way authentication (or platform authentication). The platform is the sole entity responsible for authenticating itself to the client. It issues the client a certificate to confirm the platform’s authenticity.
    • At Level 2, both the client and the server authenticate themselves to each other, ensuring the veracity of the certificate presented by the platform.
    • At Level 3, both the client and the server authenticate themselves to each other, confirming the availability of the platform’s device certificate.

Service groups available on OpenGate cloud instance

Name Entity Type Operation Group Operation on Demand Security Mode Trusted Boot
emptyServiceGroup Asset, Gateway, Communications Module, Subscriber, Subscription emptyServiceGroup Send Always None disabled
emptyServiceGroup onDemand Asset, Gateway emptyServiceGroup Send On Demand None disabled
emptyServiceGroup onSession Asset, Gateway emptyServiceGroup Send On Session Connection None disabled
level1SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level1 disabled
level2SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level2 disabled
level3SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level3 disabled
noUpdate Asset, Gateway, Communications Module noUpdate Send Always None disabled
trustedLevel1SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level1 enabled
trustedLevel2SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level2 enabled
trustedLevel3SecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always Level3 enabled
trustedNoneSecurityServiceGroup Asset, Gateway emptyServiceGroup Send Always None enabled
trustedNoneSecurityServiceGroup_onDemand Asset, Gateway emptyServiceGroup Send On Demand None enabled

Plan feature

As outlined in the organization’s plan, usage limits are to be established for the OpenGate platform. In the case of entities, if your organization has not defined a collection event limit, it must be set at the time of entity creation.

Flattened format

It is possible to create and search for data stream values (see default data models) using the flat format. This format is the same as that used on the South API. To indicate if data streams are in a flattened form, use the Boolean parameter ‘flattened’ in the URL.

The format is:

{
  "parameter1_id": {
    "_value": {
      "_current": {
        "value": "value1"
      }
    }
  },
  "parameter2_id": {
    "_value": {
      "_current": {
        "value": "value2"
      }
    }
  },
  ...
  "parameterN_id": {
    "_value": {
      "_current": {
        "value": "valueN"
      }
    }
  }
}

The following examples demonstrate the process of transforming a hierarchical JSON format into a flattened JSON format. There are two types of values: simple and complex.

Simple values

The hierarchical JSON format is:

{
  "provision": {
    "administration": {
      "identifier": {
        "_current": {
          "value": "device_battery"
        }
      }
    }
  }
}

The flattened JSON format is:

{
  "provision.administration.identifier": {
    "_value": {
      "_current": {
        "value": "device_battery"
      }
    }
  }
}

Complex values

To illustrate this concept, we will examine two contrasting examples.

The hierarchical JSON format is:

{
  "provision": {
    "device": {
      "location": {
        "_current": {
          "value": {
            "position": {
              "type": "Point",
              "coordinates": [-3.7028, 40.41675]
            },
            "postal": "28013"
          }
        }
      }
    }
  }
}

The flattened JSON format is:

{
  "provision.device.location": {
    "_value": {
      "_current": {
        "value": {
          "position": {
            "type": "Point",
            "coordinates": [-3.7028, 40.41675]
          },
          "postal": "28013"
        }
      }
    }
  }
}

Another example:

The hierarchical JSON format is:

{
  "provision": {
    "device": {
      "communicationModules": [
        {
          "identifier": {
            "_current": {
              "value": "commsMod_battery_id"
            }
          },
          "name": {
            "_current": {
              "value": "commsMod_battery_name"
            }
          }
        }
      ]
    }
  }
}

In the context of creative operations, the flattened JSON format is as follows:

{
  "provision.device.communicationModules[].identifier": [
    {
      "_index": {
        "value": "commsMod_battery_id"
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_id"
        }
      }
    }
  ],
  "provision.device.communicationModules[].name": [
    {
      "_index": {
        "value": "commsMod_battery_id"
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_name"
        }
      }
    }
  ]
}

In the case of a reading operation, the flattened JSON format is as follows:

{
  "provision.device.communicationModules[].identifier": [
    {
      "_index": {
        "path": "provision.device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "provType": "MONITORING",
            "date": "2017-09-25T09:34:32.119Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_id",
          "provType": "MONITORING",
          "date": "2017-09-25T09:34:32.119Z"
        }
      }
    }
  ],
  "provision.device.communicationModules[].name": [
    {
      "_index": {
        "path": "provision.device.communicationModules[].identifier",
        "value": {
          "_current": {
            "value": "commsMod_battery_id",
            "provType": "MONITORING",
            "date": "2017-09-25T09:34:32.119Z"
          }
        }
      },
      "_value": {
        "_current": {
          "value": "commsMod_battery_name",
          "provType": "MONITORING",
          "date": "2017-09-25T09:34:32.169Z"
        }
      }
    }
  ]
}

We will also demonstrate how to transform the existing normalised/flattened JSON examples into CSV format. The above examples will be joined together in a single CSV file comprising three lines, one for each example (a straightforward example and two complex examples).

Transforming the flattened format into CSV format is a relatively straightforward process, as the CSV file’s content adheres to the same guidelines as the flattened format. The first line (header) contains the name of the data stream, separated by “;”, and the following lines represent the different entities, with the field value of the data stream separated by “;” in the same order as the first line.

The following lines illustrate the format of a CSV file.

provision.administration.identifier;provision.device.location;provision.device.communicationModules[].identifier;provision.device.communicationModules[].name
device_battery;;;
;"{"position":{"type":"Point","coordinates":[-3.7028,40.41675]},"postal":"28013"}";;
;;commsMod_battery_id;commsMod_battery_name

In the event that an entity contains a unique communication module, it is possible to indicate the name without the use of square brackets and without the inclusion of an identifier. In light of this, it can be seen that the two strings in question, namely [commsMod_battery_name(commsMod_battery_id)] and commsMod_battery_name, are identical.

Comprehensive API actions

Searching entities

This API enables the retrieval of a comprehensive list of entities, offering a multitude of options for:

  • Filtering (see Specific Filter Fields)
  • Sorting (see Sorting)
  • Selecting Required Fields (see Selecting)
  • Summarising (see Summary)

The results can be obtained in two distinct formats:

  • JSON Format (Default)
  • CSV Format

Additionally, the results can be obtained in a flattened format through the use of flattened parameters.

API specification

Subsections of Entities

Entity types & statuses

Entity type list

  • GATEWAY: M2M device like a concentrator or smart router, modem or gateway, etc.
  • ASSET: Business entity, usually have one or more devices connected.
  • COMMUNICATIONS_MODULE: Internal modem or interface for communications.
  • SUBSCRIPTION: Logical identifier for a communication channel as a GMS line.
  • SUBSCRIBER: Physical device associated with a Logical subscription.

Default device administrative statuses

  • REQUESTED: Entity requested to the supplier
  • READY: Entity ready for installation
  • REPAIR: Entity under repair
  • TESTING: Entity in tests
  • ACTIVE: Entity deployed on field
  • SUSPEND: Suspended its operation
  • DELETED: Entity removed from available stock
  • RETIRED: Entity retired from field
  • BANNED: Entity banned, no data is going to be collected for devices with this status

Alarms for BANNED entities

The default rules catalog has an automation rule to elevate an alarm when a BANNED device shows activity. Besides that, you can run a job or schedule a task over entities with a BANNED administrative state.

Device operational statuses

  • UNKNOWN: Not known
  • NORMAL: Normal Operation
  • ALARM: The device has active alarms
  • TESTING: The device is under test. Could be running but it is not performing its normal operation.
  • DOWN: The device is not operative. Could be running but it is not performing its operation.
  • SAFE_MODE: The device is in Safe Mode (Sleeping, etc.)
  • TAMPER: The device was tampered
  • TEST: The device is working in test mode

Communication modules operational status

  • UNKNOWN: The module status is not known
  • STOPPED: The module is not working
  • STARTING: The module is booting
  • RUNNING: The module is working
  • STOPPING: The module is shutting down
  • ERROR: The module has an error

Devices

Introduction

A device represents the physical element (communications devices, concentrators, machines, sensors, etc.) through which data is collected.

Relation between devices and assets

A device can be linked to an asset through the provision.device.related data stream, which must contain the identifier of the asset in question.

When these entities are related, the asset is able to collect data from the related device. In order to do this, it is necessary to define an available data model for the Devices and Assets resources, and then define all the data streams that you want to copy from the device. Once this has been done, the asset will then automatically start collecting these values from the device.

Comprehensive API actions

Creating a device

New devices can be created by sending a POST request that includes a correctly formatted JSON document in the body.

A device may contain or not contain subscriptions and subscribers. Furthermore, these can exist independently (please refer to create subscriptions or create subscribers for more information).

It is essential that the subscription or subscriber is located within the communication modules on the device. Consequently, there are various use cases for managing device relations, depending on whether there are existing subscriptions or subscribers.

The following options are available for creating a device:

  1. Create a device without subscriptions or subscribers.
  2. Create a device with subscriptions or subscribers that do not exist in the platform.
  3. Create a device with subscriptions or subscribers that exist in the platform. In this instance, the following steps must be completed:
  • A device must be created (please refer to the ‘Create a device without subscriptions or subscribers’ section below for further details).
  • The device must then be updated with the relevant subscriptions or subscribers that are already present on the platform (please refer to the ‘Associate a subscription or subscriber to the device’ section below for further details).

Furthermore, a device can be linked to an asset. Please refer to the section entitled Relation between devices and assets for additional details.

Updating a device

Updates can be made to the following:

  • Device data
  • Device subscription or subscriber associations
  • Device subscription or subscriber disassociations

The JSON object passed will vary depending on the desired update.

Patching a device

It is possible to patch the following:

  • Only the device data
  • Associate a subscription or subscriber to the device The JSON object passed will be different depending on the desired patch. Furthermore, a device can be related to an asset. Please refer to the section entitled ‘Relation between devices and assets’ for more information.

Deleting a device

To delete a complete device with all associated subscriptions, send a DELETE request using the provided URL. The request should include a Boolean parameter, “full,” to indicate that you wish to delete the entire device.

Note

The default value of the field ‘full’ is set to ‘false’. In this case, if a device with a subscription or subscriber is deleted, only the device will be removed. Neither the subscription nor the subscriber will be deleted. After this, they will exist on the platform independently, without being associated with a device.

Searching device

This API enables the retrieval of a comprehensive list of devices, offering a multitude of options for:

  • Filter (See Specific Filter Fields)
  • Order (see Sorting)
  • Select Required Fields (see Selecting)
  • Summary (see Summary)

The results can be obtained in two different formats, as detailed in the HTTP Header Options.

  • JSON Format (Default)
  • CSV Format

As an alternative, the result can be obtained in a flattened format thanks to the flattened parameter (see device parameters).

API specification

Subscriptions

Introduction

A subscription stores information regarding the contracts with your communication operators. It can exist as a standalone entity or integrated within the device.

Comprehensive API actions

Patching a subscription

  • Please note that the administration channel value is mandatory for securitisation purposes in patch operation.
  • In the event of patching complex objects, any non-passed object attributes will be patched as non-existent. Therefore, it is advisable to include previous unchanged values to avoid any loss of data.

Searching subscriptions

The results can be obtained in two different formats, as detailed in the HTTP Header Options:

  • JSON Format (the default)
  • CSV Format

Searching subscriptions summary

The summary will always display the total counter, the organisation grouping counter and the channel grouping counter by default.

API specification

Subscribers

Introduction

The Subscriber Entity Store contains information regarding a specific communication channel. It can exist independently or within the device.

Comprehensive API actions

Patching a subscriber

  • Please note that the administration channel value is mandatory for securitisation purposes in patch operation.
  • In the event of patching complex objects, any non-passed object attributes will be patched as non-existent. Therefore, it is advisable to include previous unchanged values to avoid any loss of data.

Searching subscribers

The results can be obtained in two different formats, as detailed in the HTTP Header Options:

  • JSON Format (the default)
  • CSV Format

Searching subscribers summary

The summary will always display the total counter, the organisation grouping counter and the channel grouping counter by default.

API specification

Assets

Introduction

The software enables the creation of entities that are not devices, allowing users to emulate any type of entity they require, such as a worker or a spool.

Concurrently, a device may be associated with an asset. To illustrate, a worker may utilise a device that monitors a range of parameters.

These devices can take the form of a bracelet that monitors battery levels, pulse rate, temperature and position, or a vest that measures a range of other parameters.

An asset is able to identify its associated devices through the provision.asset.related data stream. This data contains an array of identifiers for the associated devices.

Should you wish to receive all information pertaining to the device in the asset, you must add a data model with dual data streams. Once both are related in this way, the assets will be able to receive all common data streams from the device. This ensures that all datastreams and data points collected will be in the cycle of life for both.

The platform is set up by default to offer the Entity data model, which contains two dual data streams: ’entity.location’ and ’entity.areas’. Please refer to the Default Datamodels section for more information.

Asset object structure

An asset is a repository of information about the new entity created by the user.

In regard to provisioned data, the following attributes are applicable:

  • Minimum attributes:
    • provision.administration.
    • provision.asset.identifier.
    • resourceType.
  • Recommended attributes by OpenGate:
    • provision.asset.administrativeState.
    • provision.asset.specificType.
    • provision.asset.name.
    • provision.asset.description.
  • Extended attributes:
    • provision.asset.location.
    • Defined attributes in human datamodel.
    • Defined by the user in his new datamodels. For example photo, position
Note

The specificType field is used to differentiate new entities. For instance, a worker is classified as an entity.asset with the specificType WORKER.

Comprehensive API actions

Creating an asset

New assets can be created by sending a POST request, including a correctly formatted JSON document in the POST body using the generic URL for entities

  • Please be advised that there is no requirement to include an organisation field in the JSON, as this information is already available in the URL.

It is not possible to create a list of devices associated with an asset. These must be added from the Devices section.

Updating an asset

Please be advised that an asset can be modified by sending a PATCH request using the generic URL for entities.

It is necessary to replace {identifier} with the identifier of the asset you wish to modify. Additionally, a boolean parameter, flattened, must be included to enable the sending of a flattened JSON format.

Warning
  • Please be advised that it is not possible to patch the list of devices associated with the asset. The devices must be patched from the list.
  • When patching complex object values, non-passed object attributes will be patched as non-existent. Therefore, it is advisable to include previous unchanged values to avoid any loss of data.
  • Please note that the Resource Type and Administration Channel values are mandatory in asset patch operations for securitisation purposes.

Deleting an asset

Note that it is not possible to delete the list of devices associated with an asset. Instead, you will need to delete them from the devices list.

Please be advised that an asset can be deleted by sending a DELETE request using the generic URL for entities.

API specification

Subsections of Bulk provisioning

Classic bulk provisioning

Introduction

The bulk function enables the provisioning of a list of entities or tickets in a single operation, in either synchronous or asynchronous mode.

Bulk Object Structure

Bulk requests and responses can be formatted in four different ways, which can be selected through the Content-Type HTTP header. The default format is JSON, but the other formats are also available:

  • CSV format
  • XLS Excel format
  • XLSX Excel format

Attaching Files as Multipart

The Async API enables the creation of multipart files. In this instance, the Content-Type HTTP header will be multipart/form-data, and the file type will be indicated in the attached content.

HTTP Header Options

The API enables the indication of the format in which the request content is to be sent, either JSON or CSV, via the HTTP header option “Content-Type”. Similarly, the API allows the indication of the format in which the response content is to be received, either JSON or CSV, via the HTTP header option “Accept”.

It is possible to send a request and receive a response in different formats. For example, a request sent in JSON format can be received in CSV format.

Content-type header

The bulk input can be provided in different formats, depending on the file type. The Content-Type header should indicate the format of the input data. The following formats are supported for both synchronous and asynchronous operations:

  • application/json: json
  • text/plain: csv
  • application/vnd.ms-excel: xls
  • application/vnd.openxmlformats-officedocument.spreadsheetml.sheet: xlsx

Accept Header

Please be advised that the bulk processing results will be created in the format indicated in the ACCEPT header of the POST call, for both synchronous and asynchronous operations. To achieve the desired result with the GET call, it is essential to ensure that the ACCEPT header is identical to that used in the POST call.

In the event that the POST is not completed with the correct MIME type in the ACCEPT header, an error message will be displayed. Similarly, if the GET is not completed with the correct MIME type in the ACCEPT header, the same error message will be displayed.

Comprehensive API actions

Synchronous bulk

Creating a synchronous bulk for entities

The Synchronous Bulk Creation process allows you to create multiple entities in a single request. This bulk operation applies to the following entities:

  • Assets
  • Devices
  • Subscriptions
  • Subscribers

Creating a synchronous bulk for tickets

The Synchronous Bulk Creation process for tickets allows you to create multiple ticket records in a single request.

Asynchronous bulk

Creating an Asynchronous bulk for entities

In the case of asynchronous calls, the POST method will return an empty body and the URL of the created bulk process in the Location header. To monitor the progress and outcome, a GET request should be made to the URL returned by the POST method.

Asynchronous searching

A comprehensive search is being conducted across all previously created bulk processes, whether completed or still in progress.

API specification

Provision functions for bulk provisioning

Limited access API

Limited access

Please note that the provision API of this feature is only available to the root profile. Similarly, the execution API (plan or bulk) of this feature is only available to the following profiles: root, admin, admin_domain, advanced and super_admin_domain. In contrast, the searching API is accessible to all users. Should you require further information, please consult your administrator.

Introduction

This API enables users to perform bulk provisioning using Provision Processors. These processors allow users to define their own Excel formatting using a JavaScript script, which adapts the formatting to align with the OpenGate APIs.

Provision Processor object structure

A Provision Processor will include a JSON object with a script field, which contains the JavaScript code responsible for processing inbound data and determining the appropriate actions for provisioning the relevant entities, such as JSON objects, devices, subscriptions and subscribers. When creating or updating a Provision Processor, only minimal parsing of the script will be performed.

Comprehensive API actions

Provision processors

Creating a provision processor

Please note that the Accept field should be set to application/JSON.

Updating a provision processor

All actions are based on application/JSON data formats.

Searching provision processors

Please search for all completed and ongoing bulk processes.

Executing provision processors

Executing plan from selected provision processor

  • As with the Bulk creation process, files will be attached as multipart, with only XLS and XLSX formats permitted.
  • In this instance, the Accept header must be set to application/JSON.

Rather than creating a bulk process, it would be more efficient to return the provision process planning for specified entries. This is a synchronisation process that does not result in changes to the database.

Executing bulk from selected provision processor

  • Files used for bulk processing will be attached to the request as multipart.
  • The attached file must contain a specific Content-Type property to indicate the format of the file.
  • Only XLS and XLSX formats are permitted.
  • The Accept header must match the attached file’s Content-Type.

Reading the bulk summary

Please note that the Accept field should be set to application/JSON.

Reading the bulk details from selected bulk

Please note that the Accept field should be the same used in the bulk creation request.

API specification

Subsections of Provision functions for bulk provisioning

JavaScript API

Introduction to provision processors

This API’s purpose is to facilitate the development of Provision Processors in the simplest possible way.

The API is divided into several modules/scripts:

  • Provision_Processor / provision_processor.js: This is the entry point from Java. It defines a template for Provision Processor execution.
  • Entities_Utils / provision_entity_utils.js: Utility class to facilitate the entities building.
  • Action_Utils / provision_actions_utils.js: Utility functions to create the actions to be returned to Java process.
  • V8_Api / provision_JavaV8_api.js: Functions used to invoke Java V8 methods.
  • V8_Utils / provision_JavaV8_utils.js: Some generic functions to use V8_API. When developing a new Provision Processor, instead of calling directly V8_Api functions is better to use the methods defined here.
  • Error_Api: Facility class to manage and transform caught OpenGate provision error.

Provision Processor

One Provision Processor is a script that, using Provision Javascript API, implements the business logic to transform inbound data into several actions to be done by Java to do correct provisioning actions.

How to Implement Provision Processor

When implementing a Provision Processor it is mandatory to implement two specific functions. These functions are called from Provision_Processor.processRow function:

  • normalizeRowMap(rawObject): This function receives a map with the data to be processed. For example, a map with the data read from an excel file. It takes the inbound parameter and transforms it into an object to be used to calculate and build the actions for this row. In this function, values validation and transformation should be done.
    • Input parameter: JSON object with raw keys and values.
    • Output: JSON object with the desired structure.
  • actionsPlanning(normalizedObject): Takes the result from normalizeRowMap function and calculates the actions to be done in Java.
    • Input parameter: Normalized object.
    • Output: Array of Actions.

It is possible to define extra functions to manage and transform provision errors. This function will be called from Main_Module.transformErrorMessage:

  • customErrorTransformer(errorManager): This function will be called when some provision error is caught (for example: duplicated entity). The goal is to create a customized error message for the Excel row update. This function is not mandatory, and if it is not defined, a default message will be returned by Main_Module.transformErrorMessage.
    • Input parameter: Object with error information (caught exception, failed action specification, and default message) and useful methods to manage this information.
    • Output: This function must return a String with the customized message.

Example of Provision Processor for creating devices and assets with some fields. It uses the functions and classes defined in Provision Javascript API.

   /* *******************
      MANDATORY FUNCTIONS 
      ******************* */

   function normalizeRawObject(rawObject) {

      try {
         var normalizedObject = {
            /* 
            In this case, raw object data comes from an excel
            and to specify the full key, we use the header name and column letter
            */
            organization: readMapValue(rawObject, 'Organization', '', 'A'),
            channel: readMapValue(rawObject, 'Channel Name', '', 'B'),

            /* maybe some values can be defined in the script as constants */
            service_group: 'emptyServiceGroup',

            /* We can do values validation and transformations. For example remove blanks from the value. */
            device_identifier: readMapValue(rawObject, 'Serial number', '', 'D').replace(/\s/g, ''),
            asset_identifier: readMapValue(rawObject, 'Asset Id', '', 'C').replace(/\s/g, '')
         };
         return normalizedObject;
      } catch (e) {
         printLog('>> normalizeRawObject(): exception: ' + e);
         throw e;
      }
   }


   function actionsPlanning(normalizedObject) {
      var actions = [];

      /* 
         In this case, we will create an asset and a device. 
         In the case of the device, if it exists, we are going to update it.
      */

      /* we check if the asset exists before creating it. */
      var assetExist = checkAsset(normalizedObject.asset_identifier);
      if(!assetExist){
         var assetEntity = generateAssetEntity(normalizedObject)
         actions.push(CREATE_ASSET_ACTION(assetEntity));
      }

      /* we check if the device exists. */
      var deviceExist = checkDevice(normalizedObject.device_identifier);
      var deviceEntity = generateDeviceEntity(normalizedObject)
      if(!deviceExist){
         actions.push(CREATE_DEVICE_ACTION(deviceEntity));
      }else{
         actions.push(UPDATE_DEVICE_ACTION(deviceEntity));
      }

      return actions;
   }


   /* ******************************************
      OPTIONAL FUNCTION for error transformation 
      ****************************************** */

   /* This function will be called when a provision exception is caught to get a customized message for excel row update */

   function customErrorTransformer(errorManager) {
      return 'This is customized message for error code: ' + errorManager.getFirstErrorCode() + ' and message: ' + errorManager.getFirstErrorMessage();
   }



   /* *************************
      Other auxiliary functions 
      ************************* */

   function generateDeviceEntity(normalizedObject) {
      try {
         var deviceEntity = new Entity()
               .addDatastream('provision.administration.channel', normalizedObject.channel)
               .addDatastream('provision.administration.serviceGroup', normalizedObject.service_group)
               .addDatastream('provision.administration.organization', normalizedObject.organization)
               .addDatastream('provision.administration.identifier', normalizedObject.device_identifier)
               .addDatastream('provision.device.related', normalizedObject.asset_identifier);

         return deviceEntity.entityJson;
      } catch (e) {
         printLog('>> generateDeviceEntity: Exception: ' + e);
         throw e;
      }
   }



   function generateAssetEntity(normalizedObject) {
      try {
         var assetEntity = new Entity()
               .addDatastream('resourceType', 'entity.asset')
               .addDatastream('provision.administration.channel', normalizedObject.channel)
               .addDatastream('provision.administration.serviceGroup', normalizedObject.service_group)
               .addDatastream('provision.administration.organization', normalizedObject.organization)
               .addDatastream('provision.administration.identifier', normalizedObject.asset_identifier);
         return assetEntity.entityJson;
      } catch (e) {
         printLog('>> generateAssetEntity: Exception: ' + e);
         throw e;
      }

   }
Important tips when writing a Provision Processor script

To add the script to Provision Processor JSON, it is necessary to take into these rules:

  • For strings, use single quotes (’) instead of double quotes (")
  • Use block comments (/**/) instead of line comments (//)
  • Format the script in a unique line script.

Action format

actionsPlanning returns an array of objects specifying the action to be done. Actions must be built with the functions defined in Action_Utils. Just to see the output format and following the previous example:

[
   {
      "action": "POST",
      "resourceType": "entity.asset",
      "actionDescription": "Create Asset",
      "json": {
         "resourceType": {
            "_value": {
               "_current": {
               "value": "entity.asset"
               }
            }
         },
         "provision.administration.channel": {
            "_value": {
               "_current": {
               "value": "some_channel"
               }
            }
         },
         "provision.administration.serviceGroup": {
            "_value": {
               "_current": {
               "value": "some_service_group"
               }
            }
         },
         "provision.administration.organization": {
            "_value": {
               "_current": {
               "value": "some_organization"
               }
            }
         },
         "provision.asset.identifier": {
            "_value": {
               "_current": {
               "value": "some_asset_identifier"
               }
            }
         }
      },
      "full": false
   },
   {
      "action": "POST",
      "entityType": "device",
      "actionDescription": "Create Device without Subscription",
      "json": {
         "resourceType": {
            "_value": {
               "_current": {
               "value": "entity.device"
               }
            }
         },
         "provision.administration.organization": {
            "_value": {
               "_current": {
               "value": "some_organization"
               }
            }
         },
         "provision.administration.channel": {
            "_value": {
               "_current": {
               "value": "some_channel"
               }
            }
         },
         "provision.administration.serviceGroup": {
            "_value": {
               "_current": {
               "value": "some_service_group"
               }
            }
         },
         "provision.device.identifier": {
            "_value": {
               "_current": {
               "value": "some_device_identifier"
               }
            }
         },
         "provision.device.related": {
            "_value": {
               "_current": {
               "value": "some_asset_identifier"
               }
            }
         }
      },
      "full": false
   }
]

Error management

Sometimes, it could be necessary to stop processing and abort all provision processes. For example, because some validation is not passed. In that case, an error must be thrown with a descriptive message. For example:

function actionsPlanning(normalizedObject) {
   var actions = [];

   ...

   if(! someValidation(normalizedObject)){
      throw new Error("Provision Processor Error: some validation not passed");
   }

   ...

   return actions;
}

Main Module

Main Module

Main Script: Defines Provision Processor template to be called from Java

Main_Module~globalParams

Global parameter with a received map of params from the java process. This parameter is set at the beginning of processRow and it can be used in any function in the script.

Kind: inner property of Main_Module

Main_Module~processRow(rawObject, processorParamsMap)

This is the function that will be called from the Java process.

To work correctly this function, it is mandatory to implement in the provision processor script the following functions:

  • normalizeRowMap(rawObject): This function will read and transform inbound rawObject and transform to normalizedObject object that will be used in actionsPlanning() function.
  • actionsPlanning(normalizedObject): This function has to apply business rules and calculate the actions array to be done by the Java process.

Kind: inner method of Main_Module
Returns: String - Json with following properties:

  • scriptDirectResult: OK or descriptive error text,
  • actionsToDo: Array with the list of Actions to be done in Java Process. This array can be empty.
Param Type Description
rawObject Object Json with excel row data
processorParamsMap Object Processor extra params map: can contain necessary parameters for odm api calls (key, organization) or useful parameters to define specific behaviors

Return Example

   {
      "scriptDirectResult": "OK",
      "actionsToDo":[
            {
               "action": "POST",
               "json": {...},
               "actionDescription": "Create Asset",
               "full": false,
               "resourceType": "entity.asset"
            },
            {
               "action": "PUT",
               "json": {...},
               "actionDescription": "Update Device",
               "full": false,
               "resourceType": "entity.device"
            }   
      ]
   }

Main_Module~_testTemplateImplementation()

Auxiliary function to check if main functions are implemented.

Kind: inner method of Main_Module
Throws:

  • Error if the main methods (normalizeRawObject and actionsPlanning) are not correctly defined as functions

Entities Utils

Entities_Utils

This module contains Entity class specifications and other useful functions to convert processor script inbound data to ODM Entities.

Entity

Class used to build Entity Jsons. It contains the necessary properties and methods to build any entity JSON.

  • entityJson: this property contains the Entity JSON.
  • addDatastream: this is the main method to be used to add or update desired datastreams to the Entity
  • deleteDatastream: this is the main method to be used to remove some datastream from Entity
  • getDatastream: this is the main method to be used get the value from specific datastream in the Entity
  • Other internal methods should not be necessary to call them.

Kind: inner class of Entities_Utils

Entity(entityIdentifier)

Init entityJson property with an entity identifier. Use new Entity(entityIdentifier) to create a new Entity.

Param Type Description
entityIdentifier String identifier for current entity.

Example of use:

const entity = new Entity("entityIdentifier");

entity.withPrefix(prefixToBeUsed)

Define the prefix of the datastreams to be used by addDatastream method. Adding a new prefix will override the previously added one. Use this method with an empty or undefined parameter to stop using any prefix.

Kind: instance method of Entity
Returns: Entity - Current Entity instance

Param Type Description
prefixToBeUsed String The prefix that will be used in next addDatastream calls. If it is empty the prefix will be removed.

Example of use:

entity.withPrefix("prefix");

entity.getDatastream(datastream, _index)

Search specified datastream and returns value. This function requires always complete datastream (ignores withPrefix functions calls).

Kind: instance method of Entity
Returns: * - Found datastream’s value, it can be complex. Null if not found.

Param Type Description
datastream String Datastream complete flattened name.
_index String If datastream is an array, index should be provided, if not, first element will be returned.

Example of use:

entity.getDatastream("datastream");

entity.deleteDatastream(datastream, _index)

Delete specified datastream. This function requires always complete datastream (ignores withPrefix functions calls).

Kind: instance method of Entity
Returns: * - Found datastream’s value, it can be complex. Null if not found.

Param Type Description
datastream String Datastream complete flattened name.
_index String If datastream is an array, index should be provided, if not, first element will be returned.

Example of use:

entity.deleteDatastream("datastream");

entity.addDatastream(datastream, value, _index)

Method to be used to add datastreams to current entity. Calling this method more than one time for the same datastream will have two different behaviors:

  • If _index parameter is defined, a new value will be added or updated to the array.
  • If _index parameter is not defined, the previous datastream will be overridden.

Kind: instance method of Entity
Returns: Entity - Current Entity instance

Param Type Description
datastream String Datastream flattened name.
value String Value for the datastream.
_index String If provided, it will create special indexed datastream (for communicationModules[] datastreams).

Example of use:

entity.addDatastream("datastream", "value");

entity._addToEntity(datastream)

Internal method. Attach provided datastream to current Entity’s JSON.

Kind: instance method of Entity
Returns: Entity - Current Entity instance.

Param Type Description
datastream Object Object to be attached to current Entity.

Example of use:

entity._addToEntity({ datastream: "value" });

entity._generateDatastreamJsonWithArray(datastream, valuesArray)

Internal method. Generates an object with datastream as field and provided array as value. This method is helpful for communicationModules[] datastreams.

Internally calls _cleanArray method to add good array.

Kind: instance method of Entity
Returns: Object - Json object with built datastream.

Param Type Description
datastream String Datastream flattened name.
valuesArray Array Array of objects for the datastream.

Example of use:

entity._generateDatastreamJsonWithArray("datastream", ["value"]);

entity._generateDatastreamWithJson(datastream, value)

Internal method. Generates an object with datastream as field and provided value. In this case, value can be a plain value (for example, String) or a complex JSON

Internally calls _generateJsonCurrentValue to build basic json structure.

Kind: instance method of Entity
Returns: Object - Json object with built datastream.

Param Type Description
datastream String Datastream flattened name.
value Object Json object with datastream value.

Example of use:

entity._generateDatastreamWithJson("datastream", { value: "value" });

entity._generateIndexedJson(index, value)

Internal method. Generates a json with provided index and value. This method will be used when creating datastreams with communicationModules[].

Kind: instance method of Entity
Returns: Object - Json object with indexed value structure.

Param Type Description
index String Identifier for _index value.
value * It can be plain value (String,…) or complex Json.

Example of use:

entity._generateIndexedJson("index", "value");

entity._generateJsonCurrentValue(value)

Internal method. Generates a JSON with basic structure datastream value.

Kind: instance method of Entity
Returns: Object - Json object with basic value structure.

Param Type Description
value * It can be plain value (String,…) or complex Json

Example of use:

entity._generateJsonCurrentValue("value");

Return example:

{
    "_value":{
        "_current":{
            "value": value
        }
    }
}

entity._cleanArray(valuesArray)

Internal method. Auxiliary method to clean empty ("", null, undefined) elements from provided array.

Kind: instance method of Entity
Returns: Array - New array without empty elements. null if the array is empty.

Param Type Description
valuesArray Array Array to be checked.

Example of use:

entity._cleanArray(["value", "", null, undefined]);

entity._generateDatastreamEntry(datastream, dsJson)

Internal method. Auxiliary method to build an object with datastream as field and provided JSON as value.

Kind: instance method of Entity
Returns: Object - Json object with built datastream.

Param Type Description
datastream String Datastream flattened name.
dsJson Object Json value for the datastream.

Example of use

entity._generateDatastreamEntry("datastream", { value: "value" });

Return examples:

{
    "datastream.name": {...}
}

or

{
    "datastream.name": [...]
}

readMapValue(map, headerName, defaultValue, headerColumn)

Auxiliary method to read values from the specified map.

A key will be created with headerName and headerColumn and the value for this key will be retrieved. If there is no entry for this key or the value is empty or undefined, defaultValue will be returned.

If headerColumn is null, only headerName will be used as the key.

Kind: inner method of Entities_Utils
Returns: * - Obtained value for specified header name and column or at least defined default value.

Param Type Description
map Object map from which to read values.
headerName String Header name for mapped row.
defaultValue * If no value is read or it is empty or undefined, default value will be returned.
headerColumn String Header column letter for mapped row (if null, only headerName will be used as key).

Example of use:

readMapValue(map, "headerName", "defaultValue", "headerColumn");

newEntityBuilder(fromEntityJson)

Creates Entity class object with specified entity json.

Kind: inner method of Entities_Utils
Returns: Entity - Entity Class instance

Param Type Description
fromEntityJson Object Json with Opengate flattened entity

Example of use:

var entity = newEntityBuilder(fromEntityJson);

Actions Utils

Action_Utils

Functions for building ODM Actions.

Action structure example:

{
   "action": "POST",
   "entityType": "device",
   "actionDescription": "Create Simple Device",
   "json": {...},
   "full": false
}

CREATE_ASSET_ACTION(entityJson, description)

Builds Create Asset action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Asset Entity Json to be created.
description String Action short description.

Example of use:

const assetJson = {
    "name": "asset1",
    "description": "asset1",
    "type": "asset"
}
const action = CREATE_ASSET_ACTION(assetJson, "Create Asset");

UPDATE_ASSET_ACTION(entityJson, description)

Builds Update Asset action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Asset Entity Json to be updated.
description String Action short description.

Example of use:

const assetJson = {
    "name": "asset1",
    "description": "asset1",
    "type": "asset"
}
const action = UPDATE_ASSET_ACTION(assetJson, "Update Asset");

PATCH_ASSET_ACTION(entityJson, description)

Builds Patch Asset action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Asset Entity Json to be updated.
description String Action short description.

Example of use:

const assetJson = {
    "name": "asset1",
    "description": "asset1",
    "type": "asset"
}
const action = PATCH_ASSET_ACTION(assetJson, "Patch Asset");

DELETE_ASSET_ACTION(entityJson, description)

Builds Delete Asset action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Asset Entity Json to be deleted.
description String Action short description.

Example of use:

const assetJson = {
    "name": "asset1",
    "description": "asset1",
    "type": "asset"
}
const action = DELETE_ASSET_ACTION(assetJson, "Delete Asset");

CREATE_DEVICE_ACTION(entityJson, description)

Builds Create Device action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Device Entity Json to be created.
description String Action short description.

Example of use:

const deviceJson = {
    "name": "device1",
    "description": "device1",
    "type": "device"
}
const action = CREATE_DEVICE_ACTION(deviceJson, "Create Device");

UPDATE_DEVICE_ACTION(entityJson, description)

Builds Update Device action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Device Entity Json to be updated.
description String Action short description.

Example of use:

const deviceJson = {
    "name": "device1",
    "description": "device1",
    "type": "device"
}
const action = UPDATE_DEVICE_ACTION(deviceJson, "Update Device");

PATCH_DEVICE_ACTION(entityJson, description)

Builds Patch DEVICE action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Device Entity Json to be updated.
description String Action short description.

Example of use:

const deviceJson = {
    "name": "device1",
    "description": "device1",
    "type": "device"
}
const action = PATCH_DEVICE_ACTION(deviceJson, "Patch Device");

DELETE_DEVICE_ACTION(entityJson, full, description)

Builds Delete Device action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Device Entity Json to be deleted.
full boolean true to delete also related Subscriptions and Subscribers.
description String Action short description.

Example of use:

const deviceJson = {
    "name": "device1",
    "description": "device1",
    "type": "device"
}
const action = DELETE_DEVICE_ACTION(deviceJson, true, "Delete Device");

CREATE_SUBSCRIPTION_ACTION(entityJson, description)

Builds Create Subscription action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscription Entity Json to be created.
description String Action short description.

Example of use:

const subscriptionJson = {
    "name": "subscription1",
    "description": "subscription1",
    "type": "subscription"
}
const action = CREATE_SUBSCRIPTION_ACTION(subscriptionJson, "Create Subscription");

UPDATE_SUBSCRIPTION_ACTION(entityJson, description)

Builds Update Subscription action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscription Entity Json to be updated.
description String Action short description.

Example of use:

const subscriptionJson = {
    "name": "subscription1",
    "description": "subscription1",
    "type": "subscription"
}
const action = UPDATE_SUBSCRIPTION_ACTION(subscriptionJson, "Update Subscription");

PATCH_SUBSCRIPTION_ACTION(entityJson, description)

Builds Patch Subscription action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscription Entity Json to be updated.
description String Action short description.

Example of use:

const subscriptionJson = {
    "name": "subscription1",
    "description": "subscription1",
    "type": "subscription"
}
const action = PATCH_SUBSCRIPTION_ACTION(subscriptionJson, "Patch Subscription");

DELETE_SUBSCRIPTION_ACTION(entityJson, description)

Builds Delete Subscription action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscription Entity Json to be deleted.
description String Action short description.

Example of use:

const subscriptionJson = {
    "name": "subscription1",
    "description": "subscription1",
    "type": "subscription"
}
const action = DELETE_SUBSCRIPTION_ACTION(subscriptionJson, "Delete Subscription");

CREATE_SUBSCRIBER_ACTION(entityJson, description)

Builds Create Subscriber action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscriber Entity Json to be created.
description String Action short description.

Example of use:

const subscriberJson = {
    "name": "subscriber1",
    "description": "subscriber1",
    "type": "subscriber"
}
const action = CREATE_SUBSCRIBER_ACTION(subscriberJson, "Create Subscriber");

UPDATE_SUBSCRIBER_ACTION(entityJson, description)

Builds Update Subscriber action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscriber Entity Json to be updated.
description String Action short description.

Example of use:

const subscriberJson = {
    "name": "subscriber1",
    "description": "subscriber1",
    "type": "subscriber"
}
const action = UPDATE_SUBSCRIBER_ACTION(subscriberJson, "Update Subscriber");

PATCH_SUBSCRIBER_ACTION(entityJson, description)

Builds Patch Subscriber action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscriber Entity Json to be updated.
description String Action short description.

Example of use:

const subscriberJson = {
    "name": "subscriber1",
    "description": "subscriber1",
    "type": "subscriber"
}
const action = PATCH_SUBSCRIBER_ACTION(subscriberJson, "Patch Subscriber");

DELETE_SUBSCRIBER_ACTION(entityJson, description)

Builds Delete Subscriber action with provided JSON.

Kind: inner method of Action_Utils
Returns: Object - Created action.

Param Type Description
entityJson Object Subscriber Entity Json to be deleted.
description String Action short description.

Example of use:

const subscriberJson = {
    "name": "subscriber1",
    "description": "subscriber1",
    "type": "subscriber"
}
const action = DELETE_SUBSCRIBER_ACTION(subscriberJson, "Delete Subscriber");

_createAction(action, entityJson, entityType, full, description)

Internal method. Builds an action object with specified parameters.

Kind: inner method of Action_Utils
Returns: Object - Action object with provided parameters.

Param Type Description
action String Action to be done.
entityJson Object Entity JSON to be processed.
entityType String Entity type to be processed.
full Boolean Only for DELETE device. true to delete also related Subscriptions and Subscribers.
description String Action short description.

Example of use:

const action = _createAction("CREATE", deviceJson, "device", false, "Create Device");

V8 Utils API

V8_Api

Java V8 API: Functions encapsulate the logic for calling Java V8 Methods.

Java V8 Methods are defined in: es.amplia.odm.frontend.ws.provision.bulk.bulkProcessor.jsEngine.ProvisionProcessorScriptExecutor

These are the methods defined:

  • printLogInternal (printLog): writes INFO log messages.
    • params:
      • String msg: message to be printed.
  • getEntityInternal (getEntity): gets specific Entity for provided id.
    • params:
      • String provisionType: it should be always ‘ENTITY’.
      • String resourceType: the entity type to be retrieved.
      • String entityId: entity to be retrieved.
      • Map javaParams: mandatory params to configure the query (api key, organization id…).
    • return:
      • String: Entity json.
  • genericSearchInternal (genericSearch): searches entities with provided filter.
    • params:
      • String searchTypeValue: What kind of elements must be search.
      • String searchQueryValue: Json format filter.
      • Map javaParams: mandatory params to configure the query (api key, organization id…).
    • return:
      • String: Json with found elements and page information.

printLog(msg)

Invokes Java V8 printLogInternal method.

Kind: inner method of V8_Api

Param Type Description
msg String String to be printed in Java logs

Example of use:

printLog('Provision processor started');

getEntity(entityId, resourceType, queryContextParams)

Invokes Java V8 getEntityInternal method.

Use queryContextParams parameter to specify query behavior. It is a JSON with next properties:

  • utc: used to format datetime fields. Default value: false.
  • flattened: used to specify if entity must be returned flattened or not. Default value: true.

Kind: inner method of V8_Api
Returns: Object - Entity Json. null if no entity is found

Param Type Description
entityId String Id of the entity to be retrieved
resourceType String Parameter used to specify the entity type to be retrieved
queryContextParams Object Parameters for query. Not mandatory

Example of use:

var assetEntity = getEntity(normalizedObject.asset_identifier, 'entity.asset');

entitiesGenericSearch(searchFilter, queryContextParams)

Invokes Java V8 genericSearchInternal method for ENTITIES.

Use queryContextParams parameter to specify query behavior. It is a JSON with next properties:

  • utc: used to format datetime fields. Default value: false.
  • flattened: used to specify if entity must be returned flattened or not. Default value: true.
  • defaultSorted: specifies if result must be sorted by default field. Default value: false.

Kind: inner method of V8_Api
Returns: Object - Search result json. null if no result is found.

Param Type Description
searchFilter String json search filter
queryContextParams Object Parameters for query. Not mandatory

Example of use:

var assetEntity = entitiesGenericSearch(normalizedObject.asset_identifier, 'entity.asset');

_minJavaParams(queryContextParams)

Auxiliary method to build params maps for Java Queries

Kind: inner method of V8_Api
Returns: Object - Json object

Param Type Description
queryContextParams Object parameters for query. Not mandatory.

Example of use:

var javaParams = _minJavaParams({ utc: true });

V8_Utils

Java V8 Utils: Some predefined functions for Java V8 calls. These functions internally call V8_Api functions.

checkAsset(id)

Check if an Asset exists for specified id.

Kind: inner method of V8_Utils
Returns: boolean - If the asset exists.

Param Type Description
id String asset identifier.

Example of use:

if (checkAsset(normalizedObject.asset_identifier)) {
  printLog('Check returned true');
}

checkDevice(id)

Check if a Device exists for specified id.

Kind: inner method of V8_Utils
Returns: boolean - If the Device exists.

Param Type Description
id String Device identifier.

Example of use:

if (checkDevice(normalizedObject.device_identifier)) {
  printLog('Check returned true');
}

checkSubscription(id)

Check if a Subscription exists for specified id.

Kind: inner method of V8_Utils
Returns: boolean - If the Subscription exists.

Param Type Description
id String Subscription identifier.

Example of use:

if (checkSubscription(normalizedObject.subscription_identifier)) {
  printLog('Check returned true');
}

checkSubscriber(id)

Check if a Subscriber exists for specified id.

Kind: inner method of V8_Utils
Returns: boolean - If the Subscriber exists.

Param Type Description
id String Subscriber identifier.

Example of use:

if (checkSubscriber(normalizedObject.subscriber_identifier)) {
  printLog('Check returned true');
}

getAssetEntity(id)

Gets specific Asset for specified id.

Kind: inner method of V8_Utils
Returns: Object - Asset entity, null if the Asset does not exist.

Param Type Description
id String Asset identifier.

Example of use:

var assetEntity = getAssetEntity(normalizedObject.asset_identifier);

getDeviceEntity(id)

Gets specific Device for specified id.

Kind: inner method of V8_Utils
Returns: Object - Device entity, null if the Device does not exist.

Param Type Description
id String Device identifier.

Example of use:

var deviceEntity = getDeviceEntity(normalizedObject.device_identifier);

getSubscriptionEntity(id)

Gets specific Subscription for specified id.

Kind: inner method of V8_Utils
Returns: Object - Subscription entity, null if the Subscription does not exist.

Param Type Description
id String Subscription identifier.

Example of use:

var subscriptionEntity = getSubscriptionEntity(normalizedObject.subscription_identifier);

getSubscriberEntity(id)

Gets specific Subscriber for specified id.

Kind: inner method of V8_Utils
Returns: Object - Subscriber entity, null if the Subscriber does not exist.

Param Type Description
id String Subscriber identifier.

Example of use:

var subscriberEntity = getSubscriberEntity(normalizedObject.subscriber_identifier);

duplicatedDsInSubscriptions(currentSubscriptionId, …datastreamsToCheck)

Searches for duplicated datastreams in other Subscriptions (other than currentSubscriptionId).

Kind: inner method of V8_Utils
Returns: boolean - If some Subscription has been found with some of duplicated datastreams.

Param Type Description
currentSubscriptionId String The Subscription id with the datastreams to be checked.
…datastreamsToCheck Object Datastreams to be checked if they are duplicated. Each datastream must be defined as {“datastreamId”: “datastreamValue”}.

Example of use:

if (duplicatedDsInSubscriptions(normalizedObject.subscription_identifier, normalizedObject.datastreams)) {
  printLog('Check returned true');
}

duplicatedDsInSubscribers(currentSubscriberId, …datastreamsToCheck)

Searches for duplicated datastreams in other Subscribers (other than currentSubscriberId).

Kind: inner method of V8_Utils
Returns: boolean - If some Subscriber has been found with some of duplicated datastreams

Param Type Description
currentSubscriberId String The Subscriber id with the datastreams to be checked.
…datastreamsToCheck Object Datastreams to be checked if they are duplicated. Each datastream is defined as a pair {“datastreamId”: “datastreamValue”}.

Example of use:

if (duplicatedDsInSubscribers(normalizedObject.subscriber_identifier, normalizedObject.datastreams)) {
  printLog('Check returned true');
}

duplicatedDsInDevices(currentDeviceId, …datastreamsToCheck)

Searches for duplicated datastreams in other Devices (other than currentDeviceId).

Kind: inner method of V8_Utils
Returns: boolean - If some Device has been found with some of duplicated datastreams.

Param Type Description
currentDeviceId String The Device id with the datastreams to be checked.
…datastreamsToCheck Object Datastreams to be checked if they are duplicated. Each datastream is defined as a pair {“datastreamId”: “datastreamValue”}.

Example of use:

if (duplicatedDsInDevices(normalizedObject.device_identifier, normalizedObject.datastreams)) {
  printLog('Check returned true');
}

duplicatedDsInAssets(currentAssetId, …datastreamsToCheck)

Searches for duplicated datastreams in other Assets (other than currentAssetId).

Kind: inner method of V8_Utils
Returns: boolean - If some Asset has been found with some of duplicated datastreams.

Param Type Description
currentAssetId String The Asset id with the datastreams to be checked.
…datastreamsToCheck Object Datastreams to be checked if they are duplicated. Each datastream is defined as a pair {“datastreamId”: “datastreamValue”}.

Example of use:

if (duplicatedDsInAssets(normalizedObject.asset_identifier, normalizedObject.datastreams)) {
  printLog('Check returned true');
}

_checkEntity(id, resourceType)

Internal method. Check if an ENTITY exists for the specified id and resource type.

Kind: inner method of V8_Utils
Returns: boolean - If the ENTITY exists.

Param Type Description
id String Entity id to be checked.
resourceType String Entity type to be checked.

Example of use:

if (_checkEntity(normalizedObject.asset_identifier, 'asset')) {
  printLog('Check returned true');
}

_checkDuplicatedDS(currentEntityIdentifierDatastream, currentEntityIdentifierValue, …datastreamsToCheck)

Internal method. Searches for duplicated datastreams in other entities than the specified one.

Kind: inner method of V8_Utils
Returns: boolean - If duplicated Datasteams are found in other entities.

Param Type Description
currentEntityIdentifierDatastream String Datastream used to specify the Entity id with the datastreams to be checked.
currentEntityIdentifierValue String Value for currentEntityIdentifierDatastream field.
…datastreamsToCheck Object Datastreams to be checked if they are duplicated. Each datastream is defined as a pair {“datastreamId”: “datastreamValue”}.

Example of use:

if (_checkDuplicatedDS(normalizedObject.subscription_identifier, normalizedObject.subscription_identifier, normalizedObject.datastreams)) {
  printLog('Check returned true');
}

Error API

Error_Api

This module contains ErrorManager class specification.

ErrorManager

Class used to manage and extract information from caught provision action exception. Internally contains following objects:

  • platformErrors: list of ApiPlatformError representation.
  • actionObject: OdmProvisionAction representation.
  • defaultErrorMessage: default error message string.

Kind: inner class of Error_Api

ErrorManager(platformErrors, actionObject, defaultErrorMessage)

Initialize ErrorManager entity. Use new keyword to create an instance of ErrorManager.

Param Type Description
platformErrors Object list of ApiPlatformError representation.
actionObject Object OdmProvisionAction representation.
defaultErrorMessage String default error message.

Example of use:

var errorManager = new ErrorManager(platformErrors, actionObject, defaultErrorMessage);

errorManager.getDefaultMessage()

Kind: instance method of ErrorManager
Returns: string - initialized default message

Example of use:

var defaultMessage = errorManager.getDefaultMessage();

errorManager.getFirstError()

Returns first error object.

Kind: instance method of ErrorManager
Returns: Object - first error. It can be undefined or null.

Example of use:

var firstError = errorManager.getFirstError();

errorManager.getFirstErrorAsString()

Returns first error object as string

Kind: instance method of ErrorManager
Returns: string - first error as string. It can be undefined or null.

Example of use:

var firstErrorAsString = errorManager.getFirstErrorAsString();

errorManager.getFirstErrorMessage()

Returns first error’s message property.

Kind: instance method of ErrorManager
Returns: String - message property value. It can be undefined or null.

Example of use:

var firstErrorMessage = errorManager.getFirstErrorMessage();

errorManager.getFirstErrorCode()

Returns first error’s code property.

Kind: instance method of ErrorManager
Returns: String - code property value. It can be undefined or null.

Example of use:

var firstErrorCode = errorManager.getFirstErrorCode();

errorManager.getFirstErrorContextArray()

Returns first error’s context property.

Kind: instance method of ErrorManager
Returns: array - context property value as array. It can be undefined or null.

Example of use:

var firstErrorContextArray = errorManager.getFirstErrorContextArray();

errorManager.getFirstErrorContextArrayAsString()

Returns first error’s context property.

Kind: instance method of ErrorManager
Returns: string - context property value as string. It can be undefined or null.

Example of use:

var firstErrorContextArrayAsString = errorManager.getFirstErrorContextArrayAsString();

errorManager.getFirstContextName()

Returns first error’s first context’s name property.

Kind: instance method of ErrorManager
Returns: string - context name property value. It can be undefined or null.

Example of use:

var firstContextName = errorManager.getFirstContextName();

errorManager.getFirstContextValue()

Returns first error’s first context’s value property.

Kind: instance method of ErrorManager
Returns: string - context value property value. It can be undefined or null.

Example of use:

var firstContextValue = errorManager.getFirstContextValue();

errorManager.getFirstContext()

Returns first error’s first context object.

Kind: instance method of ErrorManager
Returns: Object - context object. It can be undefined or null.

Example of use:

var firstContext = errorManager.getFirstContext();

errorManager.getFirstContextAsString()

Returns first error’s first context object as string.

Kind: instance method of ErrorManager
Returns: string - context object as string. It can be undefined or null.

Example of use:

var firstContextAsString = errorManager.getFirstContextAsString();

errorManager.getErrorsSize()

Returns number of errors contained.

Kind: instance method of ErrorManager
Returns: number - size of contained errors.

Example of use:

var errorsSize = errorManager.getErrorsSize();

errorManager.getSpecificErrorObject(index)

Returns specific error object

Kind: instance method of ErrorManager
Returns: Object - error object. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorObject = errorManager.getSpecificErrorObject(0);

errorManager.getSpecificErrorObjectAsString(index)

Returns specific error object as a string

Kind: instance method of ErrorManager
Returns: string - error object as string. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorObjectAsString = errorManager.getSpecificErrorObjectAsString(0);

errorManager.getSpecificErrorMessage(index)

Returns specific error’s message

Kind: instance method of ErrorManager
Returns: String - message property value for specified error. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorMessage = errorManager.getSpecificErrorMessage(0);

errorManager.getSpecificErrorCode(index)

Returns specific error’s code

Kind: instance method of ErrorManager
Returns: String - code property value for specified error. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorCode = errorManager.getSpecificErrorCode(0);

errorManager.getSpecificErrorContextArray(index)

Returns specific error’s context property as array.

Kind: instance method of ErrorManager
Returns: array - context property value as array. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorContextArray = errorManager.getSpecificErrorContextArray(0);

errorManager.getSpecificErrorContextArrayAsString(index)

Returns specific error’s context property as string.

Kind: instance method of ErrorManager
Returns: string - context property value for specified error. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var specificErrorContextArrayAsString = errorManager.getSpecificErrorContextArrayAsString(0);

errorManager.getSpecificContext(errorIndex, contextIndex)

Returns specific context in specific error.

Kind: instance method of ErrorManager
Returns: Object - context object. It can be undefined or null.

Param Type Description
errorIndex number error index in errors list
contextIndex number context index in specified error

Example of use:

var specificContext = errorManager.getSpecificContext(0, 0);

errorManager.getSpecificContextAsString(errorIndex, contextIndex)

Returns specific context in specific error as string.

Kind: instance method of ErrorManager
Returns: string - context object. It can be undefined or null.

Param Type Description
errorIndex number error index in errors list
contextIndex number context index in specified error

Example of use:

var specificContextAsString = errorManager.getSpecificContextAsString(0, 0);

errorManager.getSpecificContextName(errorIndex, contextIndex)

Returns specific context’s name in specific error.

Kind: instance method of ErrorManager
Returns: string - name property value for specified context. It can be undefined or null.

Param Type Description
errorIndex number error index in errors list
contextIndex number context index in specified error

Example of use:

var specificContextName = errorManager.getSpecificContextName(0, 0);

errorManager.getSpecificContextValue(errorIndex, contextIndex)

Returns specific context’s value in specific error.

Kind: instance method of ErrorManager
Returns: string - value property value for specified context. It can be undefined or null.

Param Type Description
errorIndex number error index in errors list
contextIndex number context index in specified error

Example of use:

var specificContextValue = errorManager.getSpecificContextValue(0, 0);

errorManager.getAdministrationIdentifier()

Returns entity administration identifier.

Kind: instance method of ErrorManager
Returns: string - It can be undefined or null.

Example of use:

var administrationIdentifier = errorManager.getAdministrationIdentifier();

errorManager.getDatastreamValue(index)

Returns from entity (in OdmProvisionAction) specific datastream value (datastream._value._current.value). It can be an object or plain string.

Kind: instance method of ErrorManager
Returns: Object - Object with specific datastream. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var datastreamValue = errorManager.getDatastreamValue(0);

errorManager.getDatastreamValueAsString(index)

Returns from entity (in OdmProvisionAction) specific datastream value (datastream._value._current.value). It can be a json string.

Kind: instance method of ErrorManager
Returns: string - String with specific datastream. It can be undefined or null.

Param Type Description
index number error index in errors list

Example of use:

var datastreamValueAsString = errorManager.getDatastreamValueAsString(0);

errorManager.getAction()

Returns provision action type (POST, PUT, PATCH, DELETE) from OdmProvisionAction

Kind: instance method of ErrorManager
Returns: string - It can be undefined or null.

Example of use:

var action = errorManager.getAction();

errorManager.isPost()

Kind: instance method of ErrorManager
Returns: boolean - true if provision action is POST.

Example of use:

var isPost = errorManager.isPost();

errorManager.isPut()

Kind: instance method of ErrorManager
Returns: boolean - true if provision action is PUT.

Example of use:

var isPut = errorManager.isPut();

errorManager.isPatch()

Kind: instance method of ErrorManager
Returns: boolean - true if provision action is PATCH.

Example of use:

var isPatch = errorManager.isPatch();

errorManager.isDelete()

Kind: instance method of ErrorManager
Returns: boolean - true if provision action is DELETE.

Example of use:

var isDelete = errorManager.isDelete();

errorManager.getEntityType()

Returns provision entity type (asset, device, subscription, subscriber) from OdmProvisionAction

Kind: instance method of ErrorManager
Returns: string - It can be undefined or null.

Example of use:

var entityType = errorManager.getEntityType();

errorManager.isSubscription()

Kind: instance method of ErrorManager
Returns: boolean - true if provision entity is subscription.

Example of use:

var isSubscription = errorManager.isSubscription();

errorManager.isSubscriber()

Kind: instance method of ErrorManager
Returns: boolean - true if provision entity is subscriber.

Example of use:

var isSubscriber = errorManager.isSubscriber();

errorManager.isDevice()

Kind: instance method of ErrorManager
Returns: boolean - true if provision entity is device.

Example of use:

var isDevice = errorManager.isDevice();

errorManager.isAsset()

Kind: instance method of ErrorManager
Returns: boolean - true if provision entity is asset.

Example of use:

var isAsset = errorManager.isAsset();