Introduction
This microservice will create within the microservice context every x seconds a new temperature measurement for a new created managed object.
Precondition
The tutorial is based on Microservice Tutorial Part 1a, Part 1b, Part 2 & Part 3.
Source code
https://github.com/netperformance/cumulocity-microservice-part4
Microservice preparation
See Microservice Workshop Part 2 for more details:
- Create a new microservice by using postman
- Get the bootstrap credentials by using postman
- Configure your application.properties
Open Weather account & microservice settings
Create a new OpenWeather account.
Here you will find your API key.
API call example/check: Read weather data based on geo position e.g. Düsseldorf
http://api.openweathermap.org/data/2.5/weather?appid=<API_KEY>&lat=51.227741&lon=6.773456
Import the following Open Weather Java client library into your pom.xml.
<!-- https://mvnrepository.com/artifact/net.aksingh/owm-japis -->
<dependency>
<groupId>net.aksingh</groupId>
<artifactId>owm-japis</artifactId>
<version>2.5.3.0</version>
</dependency>
You can now easily send a request to OpenWeater to get the current weather data:
// Read API key from microservice settings
OWM owm = new OWM(microserviceSettingsService.getCredential("api_key"));
// getting current weather by given city id from microservice settings
CurrentWeather currentWeather = owm.currentWeatherByCityId(Integer.parseInt(microserviceSettingsService.get("city")));
As you can see I’m reading the Open Weather API key and the city from the microservice settings by using the MicroserviceSettingsService class.
private final MicroserviceSettingsService microserviceSettingsService;
Use the following endpoint to save a property within your tenant: {{url}}/tenant/options
Body:
{
"category": "microservice-part4",
"key": "credentials.api_key",
"value": "your open weather API key"
}
api.key is the API key you will get from OpenWeather.
You can encrypt data by using “credentials.” as a prefix for your property.
I will also save the city id of the German city Cologne within my tenant property:
Body:
{
"category": "microservice-part4",
"key": "city",
"value": "5021807"
}
Display the data
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)