Cumulocity Microservice Tutorial Part 6 (send a REST request via SDK to get the latest measurement)

Introduction

This microservice will create every x seconds a new custom temperature measurement. You will ask for the latest measurement by using the SDK.

Precondition

The tutorial is based on Microservice Tutorial Part 1a, Part 1b, Part 2, Part 3, Part 4 & Part 5.

Source code

https://github.com/netperformance/cumulocity-microservice-part6

Microservice preparation

  1. Create a new microservice by using postman
  2. Get the bootstrap credentials by using postman
  3. Configure your application.properties
  4. Configure your cumulocity.json
  5. Subscribe to your microservice

Result

The new endpoint we are going to create will deliver the following result:

Send a REST request (query parameter) via SDK to get the latest measurement

Get the measurement collection object by using the measurement API. Reduce the number of results by using filter criteria:

MeasurementCollection measurementCollection = measurementApi.getMeasurementsByFilter(new MeasurementFilter().byType("c8y_CustomTemperatureMeasurement")

.byDate(new Date(0), new Date())

.byValueFragmentTypeAndSeries("c8y_example_CustomTemperatureMeasurement", "temperatureOutside")

.bySource(managedObjectRepresentation.getId()));

The filter “.byDate(new Date(0), new Date())” will not deliver the measurements in the needed order. 

We need to send a REST request via SDK to get only 1 measurement and to change the order of the measurement list:

List<MeasurementRepresentation> measurementList = measurementCollection.get(1, new QueryParam(new Param() {

    @Override

    public String getName() {

        return "revert";
    }

}, "true")).getMeasurements();

Update of the required roles

We need to add the role ‘ROLE_MEASUREMENT_READ’ to the list of the required roles to get access to the measurements. 

{
  "requiredRoles": [
      "ROLE_INVENTORY_ADMIN",
      "ROLE_IDENTITY_ADMIN",
      "ROLE_MEASUREMENT_READ"
  ]
}

List of all tutorials

Cumulocity Microservice Tutorial Part 1a (Hello World)
Cumulocity Microservice Tutorial Part 1b (local testing)
Cumulocity Microservice Tutorial Part 2 (Managed Object CRUD)
Cumulocity Microservice Tutorial Part 3 (Microservice/User-Context, external ID & measurement creation
Cumulocity Microservice Tutorial Part 4 (Read and display data from an external weather API & microservice settings/configuration)
Cumulocity Microservice Tutorial Part 5 (Creation of custom measurements)
Cumulocity Microservice Tutorial Part 6 (send a REST request via SDK to get the latest measurement)
Cumulocity Microservice Tutorial Part 7 (Alarm handling)
Cumulocity Microservice Tutorial Part 8 (Event handling)
Cumulocity Microservice Tutorial Part 9 (Operation handling)