Skills are instructions for AI agents and step-by-step guides for people, for the tasks on this page. Give a skill's SKILL.md to your agent. The Skills page has all skills to download.
This section describes how to develop and deploy microservices on top of Cumulocity using the Microservice SDK for Java. It also contains a Hello world tutorial that you may follow to get the basics of developing microservices using Java. After you have successfully deployed your first microservice to Cumulocity, you may also continue with the section Developing microservices to learn more about other features and capabilities of the SDK.
Info
You can develop microservices for Cumulocity with any IDE and build tool that you prefer, but this section focuses on Maven and some troubleshooting for Eclipse.
These are some useful references to get started with the basic technologies underlying the SDK:
The client libraries use the Cumulocity REST interfaces as underlying communication protocol as described in the section Using the REST interface.
You must have at least version 11 of the Java Development Kit installed in your development environment as older versions of the JRE and JDK are not updated with the latest security patches and are not recommended for use in production.
If you face any issue or need support, refer to Cumulocity Tech Community. You will find plenty of useful information there.
Hello world tutorial for Java
Here you will learn how to create your first microservice that can be deployed on the Cumulocity platform using the Microservice SDK for Java.
Requests to a microservice can be authenticated using basic authentication or OAuth. Refer to Authentication and authorization for more details.
Prerequisites
You must have Cumulocity credentials and a dedicated tenant. In case you do not have that yet, create an account on the Cumulocity platform, for example by using a free trial. At this step you will be provided with a dedicated URL address for your tenant.
Verify that you have a recommended Java version installed together with Maven 3 or higher. It can be downloaded from the Maven website.
$ mvn -v
Apache Maven 3.8.5
Maven home: /Library/Maven/apache-maven-3.8.5
Java version: 17.0.6, vendor: Oracle Corporation
Java home (runtime): /Library/Java/JavaVirtualMachines/jdk-17.0.6.jdk/Contents/Home
OS name: "mac os x", version: "10.14.6", arch: "x86_64", family: "mac"
You will also need a Docker installation, and in case that you don’t have it yet, go to the Docker website to download and install it.
Cumulocity microservices are Docker containers for the Linux/Amd64 platform. Other architectures are currently not supported. The Docker engine must provide the API version 1.38 or newer. This is the case for Docker versions 18.06 and later. Use the following command to verify your Docker installation:
$ docker version
Client: Docker Engine - Community
Version: 20.10.14
API version: 1.41
Go version: go1.16.15
Git commit: a224086
Built: Thu Mar 24 01:47:57 2022 OS/Arch: linux/amd64
Context: default
Experimental: trueServer: Docker Engine - Community
Engine:
Version: 20.10.14
API version: 1.41 (minimum version 1.12)
Go version: go1.16.15
Git commit: 87a90dc
Built: Thu Mar 24 01:45:46 2022 OS/Arch: linux/amd64
Experimental: false containerd:
Version: 1.5.11
GitCommit: 3df54a852345ae127d1fa3092b95168e4a88e2f8
runc:
Version: 1.0.3
GitCommit: v1.0.3-0-gf46b6ba
docker-init:
Version: 0.19.0
GitCommit: de40ad0
Developing the “Hello world” microservice
You can download the source code of this example from our GitHub repository to build and run it using your favorite IDE, or follow the instructions below to guide you step-by-step for you to have a better understanding of the code and what must be done/configured.
Important
This microservice example has been tested under macOS, Ubuntu and Windows 10 with Java 17, Maven 3.8.5, Docker 20.10.14; latest version of IntelliJ IDEA as IDE. Other tools or Java versions may require different configurations.
Create a Maven project
Use the Maven Archetype Plugin to create a Java project from an existing Maven template. Use c8y.example as your groupId, hello-microservice-java as your artifactId, and set the version following the SemVer format as specified in Microservice manifest.
This will create a folder hello-microservice-java in the current directory with a skeleton structure for your project.
Specify the properties
You will find the pom.xml file inside the hello-microservice-java folder. Edit this file and add a <properties> element to set the -source and -target of the Java Compiler using version 17. This example uses Spring Boot to quickly build and create the application using the Spring Framework. Hence, also specify in the <properties> element the version to use as follows:
You must specify the version of the Cumulocity’s microservice library to be used. This version is based on the platform version (“cumulocity”). To find the platform version, click the user icon at the top right and in the right drawer, under Platform info, download the platform details.
Alternatively, you can retrieve the backend version with a GET request to /tenant/system/options/system/version.
See also Tenants in the Cumulocity OpenAPI Specification.
For yearly releases, you should use the release with matching major and minor versions and the latest maintenance version from the Cumulocity maven repository.
For the continous deployment version you should use the latest version from the Cumulocity maven repository.
In the <properties> element specified above, add a child element <c8y.version> with the backend version of your tenant. Also add a <microservice.name> child element to name your microservice application.
When naming your microservice application use only lower-case letters, digits and dashes. The maximum length for the name is 23 characters.
Add repositories and dependencies
Your pom.xml file must have <repository> and <pluginRepository> elements to point to the Cumulocity Maven repository which stores the client libraries.
Your microservice application must be packed as a Docker image in a ZIP file including all the required dependencies. To achieve that, include in your pom.xml file build plugins as follows:
The name of the generated ZIP file is specified in the image element as <image>${microservice.name}</image>. It takes the name from the previously defined property microservice.name, which in this case is hello-microservice-java.
Create a Java application
Edit the App.java file located in the folder /src/main/java/c8y/example with the following content:
The code uses four annotations; three are part of the Spring Framework and one of the Cumulocity Microservice SDK. The @RestController annotation marks the class as a controller where every method returns a domain object instead of a view. The @RequestMapping annotation ensures that HTTP requests to the /service/<microservice-name>/hello endpoint are mapped to the greeting() method. @RequestParam binds the value of the query string parameter name into the you parameter of the greeting() method. Refer to the Spring Guides for more details about building RESTful Web Services using the Spring Framework.
Employing the @MicroserviceApplication annotation is a simple way to add the required behavior for Cumulocity microservices including:
Security
Subscription
Health check endpoint at /service/<microservice-name>/health
Context
Settings
Internal platform API
Spring Boot application
Configure the microservice application
Create the directory src/main/resources to contain an application.properties file specifiying the name of the microservice application and the server port:
Create the directory src/main/configuration to contain a cumulocity.json file. This is the manifest file and it is required to deploy the microservice in the Cumulocity platform.
In a terminal, navigate to the folder where your pom.xml is located and execute the following Maven command:
$ mvn clean install
After a successful build, you will find a ZIP file inside the target directory.
$ ls target | grep zip
hello-microservice-java-1.0.0-SNAPSHOT.zip
Deploying the “Hello world” microservice
To deploy your microservice on the Cumulocity platform you need:
A valid tenant, a user and a password in order to access Cumulocity.
The ZIP file built with Maven on the previous steps.
Important
The Microservice hosting feature must be activated on your tenant, otherwise your request will return an error message like “security/Forbidden, access is denied”. This feature is not assigned to tenants by default, so trial accounts won’t have it. Contact product support so that we can assist you with the activation. Note that this is a paid feature.
In the Administration application, navigate to Ecosystem > Microservices, and click Add microservice.
Upload the ZIP file for your microservice application and click Subscribe to subscribe the microservice to your tenant.
Once the ZIP file has been uploaded successfully, you will see a new microservice application created.
Test the deployed microservice
Employing your tenant credentials, you can test the microservice on any web browser using the URL as follows:
You can also use third-party applications or commands to make a GET request to your microservice endpoint. To do so, you need:
A valid tenant, a user and a password in order to access Cumulocity.
A basic authorization header "Authorization: Basic <Base64(<tenantID>/<username>:<password>)>".
For instance, if your tenant ID, username and password are t0071234, testuser and secret123 respectively, you can get the Base64 string with the following command:
and your authorization header would look like Authorization: Basic dDAwNzEyMzQvdGVzdHVzZXI6c2VjcmV0MTIz. Employing the cURL command you can test your microservice as follows:
Most tools should already support the Cumulocity Authorization header out of the box. Simply use <tenantId>/<username> as username and <password> as password. In modern versions, for example, the above cURL command can also look like below, and the header will be generated automatically:
You must replace the values <URL> with the URL of your Cumulocity tenant (domain), <AUTHORIZATION> is Basic with a Base64 encoded string, and for <APPLICATION_NAME> use the desired name for your microservice application and its key name.
Important
When naming your microservice application use only lower-case letters, digits and dashes. The maximum length for the name is 23 characters.
The cURL command can be used to create the application with a POST request:
In case of errors, such as invalid names, you will get the details printed in the console. When the application is created successfully, you will get a response in JSON format similar to the following example:
The Docker image was built using your local Docker repository during the Maven build. Note, that by default the image is deleted to keep your registry clean during development. You can change this by adding the property microservice.package.deleteImage=false to the maven command or pom.xml.
You can list all the Docker images available with the following command:
$ docker images
It yields an output similar to this:
REPOSITORY TAG IMAGE ID CREATED SIZE
hello-microservice-java 1.0.0-SNAPSHOT 3e5e7aeea7bc 52 minutes ago 143MB
Get your IMAGE ID and TAG from the list. While not strictly a means of identifying a container, you can specify a version of an image (TAG) you would like to run the container with. Run the Docker container for the microservice:
-p 8082:80 will expose your port 80 to a port on your host system, for example, 8082.
If your Docker image has run successfully, you shall see the output on the console similar to the one below.
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v3.3.5)
2022-10-21 15:53:07.510 INFO 7 --- [main] c8y.example.App : Starting App on dff01acae6d8 with PID 7 (/data/hello-microservice-java.jar started by root in /)
...
2022-10-21 15:53:17.583 INFO 7 --- [main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 80 (http)
2022-10-21 15:53:17.598 INFO 7 --- [main] c8y.example.App : Started App in 11.32 seconds (JVM running for 12.192)
Subscribe to the microservice
In the Administration application, navigate to Ecosystem > Microservices. Locate your microservice application and click it to open its details. On the top right, click Subscribe.
At this point, you may open your favorite browser and test your microservice at http://localhost:8082/hello. Enter your bootstrap user credentials using <tenant>/<username> and your password.
Now that you have done your first steps, check out the section Developing microservices to find out what else can be implemented. Review also the Java example in this guide to learn using more features of the microservice SDK and REST API by employing third-party services.
IP-tracker microservice
Important
Visit our Hello world tutorial for Java and follow the setup steps there before starting the IP-tracker microservice tutorial. The basic configuration steps are not explained here.
Developing the IP-tracker microservice
This microservice application creates a warning alarm message (for demonstration purposes) and it exposes endpoints to:
Verify that the microservice is up and running.
Pass a parameter to the platform and return a formatted string.
Get some of the environment variables and the microservice service settings.
Track a user’s approximate location and store it in the platform.
Get the tracked IPs and locations.
It also uses the Cumulocity UI to display the tracked locations on a map.
Update the Project Object Model
Assuming that you have the base code presented in our Hello world tutorial for Java, edit your pom.xml file changing the artifactId and microservice.name of your microservice to iptracker-microservice.
Also add a child element <java.version> to the <properties> element to specify the Java version you want to use.
Your pom.xml file should contain a snippet similar to:
This example was implemented using Java 17 and Spring Boot 2. You may install the JDK 17 or adjust this example to the version you already have, for example, JDK 11. Note that since Java 13 some API methods were removed or deprecated, so you may get some warning messages during build time but they won’t affect the microservice application.
Add the required permissions (using the requiredRoles field) to be able to create events and alarms.
Add the readiness and liveness probes.
Add two keys for the microservice settings: "ipstack.key" and "tracker.id".
Set the isolation level to "PER_TENANT". This means that there will be a separate instance for each tenant. For more details see the Settings section in Microservice manifest.
An alarm must be associated with a source and it requires an ID.
Hence, you must create a managed object to be your source and use its ID in your microservice application.
The same managed object will track the locations when the microservice gets accessed on a particular endpoint.
First, get your current location (latitude, longitude) using any free service.
Create a managed object as a device named “Microservice tracker” via POST request as follows:
You will get the ID of your managed object in the response.
Assign this ID to the "tracker.id" key in your cumulocity.json file.
On the Cumulocity platform, navigate to Devices > All devices in the Device Management application to verify that your device has been created and its location is displayed on the map.
Getting the client’s location
The microservice will get the approximate location based on the client’s IP.
To achieve this, it uses the free service ipstack and you must get a free API key.
Once you have it, assign it to the "ipstack.key" key in your cumulocity.json file.
A GET request to the ipstack API using your key will return a location object. Therefore, you must create a new file named Location.java in the same directory of your App.java with the following content:
Add a post-construct init method to get a subset of the environment variables and the microservice settings.
Add an event listener to the microservice subscription. Each time a tenant subscribes to the microservice, an alarm will be created.
Define a method to create LocationUpdate events based on the client’s IP.
Add the application endpoints.
Your code should look similar to:
package c8y.example;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.context.event.EventListener;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.cumulocity.microservice.autoconfigure.MicroserviceApplication;
import com.cumulocity.microservice.context.ContextService;
import com.cumulocity.microservice.context.credentials.MicroserviceCredentials;
import com.cumulocity.microservice.settings.service.MicroserviceSettingsService;
import com.cumulocity.microservice.subscription.model.MicroserviceSubscriptionAddedEvent;
import com.cumulocity.model.idtype.GId;
import com.cumulocity.rest.representation.alarm.AlarmRepresentation;
import com.cumulocity.rest.representation.event.EventRepresentation;
import com.cumulocity.rest.representation.inventory.ManagedObjectRepresentation;
import com.cumulocity.sdk.client.Platform;
import com.cumulocity.sdk.client.event.EventFilter;
import net.minidev.json.JSONObject;
@MicroserviceApplication@RestControllerpublicclassApp {
@Autowiredprivate MicroserviceSettingsService settingsService;
@Autowiredprivate ContextService<MicroserviceCredentials> contextService;
@Autowiredprivate Platform platform;
private Map<String, String> c8yEnv;
publicstaticvoidmain (String[] args) {
SpringApplication.run(App.class, args);
}
/**
* Get some of the environment variables of the container and load the
* microservice settings
*/@PostConstructprivatevoidinit () {
// Environment variablesvar env = System.getenv();
c8yEnv = new HashMap<>();
c8yEnv.put("app.name", env.get("APPLICATION_NAME"));
c8yEnv.put("url", env.get("C8Y_BASEURL"));
c8yEnv.put("jdk", env.get("JAVA_VERSION"));
c8yEnv.put("tenant", env.get("C8Y_TENANT"));
c8yEnv.put("user", env.get("C8Y_USER"));
c8yEnv.put("password", env.get("C8Y_PASSWORD"));
c8yEnv.put("isolation", env.get("C8Y_MICROSERVICE_ISOLATION"));
c8yEnv.put("memory.limit", env.get("MEMORY_LIMIT"));
// Required ID and key c8yEnv.put("tracker.id", settingsService.get("tracker.id"));
c8yEnv.put("ipstack.key", settingsService.get("ipstack.key"));
}
/**
* Create a warning alarm on microservice subscription
*/@EventListener(MicroserviceSubscriptionAddedEvent.class)
publicvoidcreateAlarm (MicroserviceSubscriptionAddedEvent event) {
contextService.callWithinContext(event.getCredentials(), () -> {
var source = new ManagedObjectRepresentation();
source.setId(GId.asGId(c8yEnv.get("tracker.id")));
var alarm = new AlarmRepresentation();
alarm.setSource(source);
alarm.setSeverity("WARNING");
alarm.setStatus("ACTIVE");
alarm.setDateTime(DateTime.now());
alarm.setType("c8y_Application__Microservice_subscribed");
alarm.setText("The microservice " + c8yEnv.get("app.name") + " has been subscribed to tenant " + c8yEnv.get("tenant"));
platform.getAlarmApi().create(alarm);
returntrue;
});
}
/**
* Create a LocationUpdate event based on the client's IP
*
* @param String The public IP of the client
* @return The created event
*/public EventRepresentation createLocationUpdateEvent (String ip) {
// Get location details from ipstackvar rest = new RestTemplate();
var apiURL = "http://api.ipstack.com/" + ip + "?access_key=" + c8yEnv.get("ipstack.key");
var location = rest.getForObject(apiURL, Location.class);
// Prepare a LocationUpdate event using Cumulocity's APIvar c8y_Position = new JSONObject();
c8y_Position.put("lat", location.getLatitude());
c8y_Position.put("lng", location.getLongitude());
var source = new ManagedObjectRepresentation();
source.setId(GId.asGId(c8yEnv.get("tracker.id")));
var event = new EventRepresentation();
event.setSource(source);
event.setType("c8y_LocationUpdate");
event.setDateTime(DateTime.now());
event.setText("Accessed from " + ip + " (" + (location.getCity() != null ? location.getCity() + ", " : "")
+ location.getCountry_code() + ")");
event.setProperty("c8y_Position", c8y_Position);
event.setProperty("ip", ip);
// Create the event in the platform platform.getEventApi().create(event);
return event;
}
/* * * * * * * * * * Application endpoints * * * * * * * * * */// Check the microservice status/health (implemented by default)// GET /health// Greeting endpoints@RequestMapping("hello")
public String greeting (@RequestParam(value = "name", defaultValue = "World") String you) {
return"Hello " + you + "!";
}
@RequestMapping("/")
public String root () {
return greeting("World");
}
// Return the environment values@RequestMapping("environment")
public Map<String, String> environment () {
return c8yEnv;
}
// Track client's approximate location@RequestMapping(value = "location/track", produces="application/json")
public String trackLocation (HttpServletRequest request) {
// Get the public IP address and create the eventreturn createLocationUpdateEvent(request.getHeader("x-real-ip")).toJSON();
}
// Get the tracked IPs and locations@RequestMapping("location/locations")
public ArrayList<Object> getLocations (@RequestParam(value = "max", defaultValue = "5") int max) {
var filter = new EventFilter().byType("c8y_LocationUpdate");
var locations = new ArrayList<Object>();
var eventCollection = platform.getEventApi().getEventsByFilter(filter).get(max);
eventCollection.getEvents().forEach((event) -> {
var map = new HashMap<String, Object>();
map.put("ip", event.getProperty("ip"));
map.put("coordinates", event.getProperty("c8y_Position"));
map.put("when", event.getCreationDateTime().toString("yyyy-MM-dd hh:mm:ss"));
locations.add(map);
});
return locations;
}
}
Building and deploying the application
Use the command mvn clean install and follow the same steps of the Hello world tutorial for Java to deploy your microservice.
You may also employ the cURL command to deploy the microservice.
You can test any endpoint of your application using the command line or a web browser.
For example, a GET request to location/track will obtain the client’s IP from the request header and use the createLocationUpdateEvent method to get the approximate location.
The response will be similar to:
Using the endpoint location/locations will return five stored events by default.
You can use the max parameter to specify a higher number.
In the Device Management application, navigate to Devices > All devices and locate your microservice tracker.
Under Tracking you will see a map with the tracked locations.
You can also develop your own web application and customize a “Map” widget.
For details, refer to the Web developer codex.
Run the Docker container
The Docker image is built and added to the local Docker repository during the Maven build if the following property is set microservice.package.deleteImage=false.
As you have learned in our Hello world tutorial for Java, you can run the Docker container locally.
Note that in this case the isolation was changed to PER_TENANT.
You can also use your Docker image name and tag to run it as follows:
If your Docker image has run successfully, you can test the microservice on any web browser.
For instance, using http://localhost:8082/location/locations will return all the tracked locations.
The Cumulocity Microservice SDK is an open source toolkit for building microservices using the popular Spring Boot framework and the Cumulocity platform APIs. It accelerates development by offering preconfigured annotations, built-in services, and a Maven plugin for creating Docker containers and Cumulocity applications. The SDK source code is available on GitHub in the
cumulocity-clients-java repository.
In this section, you will learn how to:
Use SDK annotations to simplify the setup.
Access platform APIs via dependency injection.
Authenticate towards the platform APIs.
Secure access to your microservice APIs.
Handle subscriptions and multi-tenant access.
Configure your microservice.
Upload and run your microservice.
Manage and monitor your microservice.
Set up external or legacy deployments.
Using annotations
As shown in the “Hello world” tutorial, the easiest way to enable default microservice behavior is to annotate your main class with @MicroserviceApplication. This composite annotation includes:
Annotation
Description
@SpringBootApplication
Enables Spring Boot’s auto-configuration
@EnableContextSupport
Allows use of @UserScope and @TenantScope for method-level context switching
@EnableHealthIndicator
Exposes a standard health endpoint for platform monitoring
@EnableMicroserviceSecurity
Enables security by verifying users and roles against the platform
@EnableMicroserviceSubscription
Manages subscriptions, metadata updates, and listens to tenant subscription changes
@EnableMicroservicePlatformInternalApi
Injects platform API services into the Spring context
@EnableTenantOptionSettings
Allows configuration through tenant options and supports overriding default properties via files
Accessing platform APIs
The Cumulocity Microservice SDK includes a set of Java APIs that are automatically injected into the Spring context and allow you to operate the REST APIs from Java in a simple manner. The REST APIs correspond to Java APIs as follows:
Alarm - AlarmApi
AuditRecord - AuditRecordApi
Operation - DeviceControlApi
Event - EventApi
EventBinary - EventBinaryApi
ExternalID - IdentityApi
Binary - BinariesApi
ManagedObject - InventoryApi
Measurement - MeasurementApi
DeviceCredentials - DeviceCredentialsApi
User - UserApi
TenantOption - TenantOptionApi
SystemOption - SystemOptionApi
Token - TokenApi
Notification - NotificationSubscriptionApi
Each API supports standard “CRUD” operations (create, read, update, delete). For example, the AlarmApi interface provides:
More details on using the APIs are available in the Client library section.
Authenticating and authorizing towards the platform
API requests in Cumulocity microservices can run in two authentication scopes:
Tenant scope – uses the service user’s credentials.
User scope – uses the credentials of the authenticated user who triggered the request.
Each microservice has a service user whose roles are defined in the cumulocity.json manifest.
API requests must be executed in one of these contexts: tenant scope or user scope.
To execute API requests in the tenant scope in any thread of the application, the MicroserviceSubscriptionsService can be used to wrap the request like in the next example:
In these cases, the MicroserviceSubscriptionsService is not needed.
The API service beans like eventApi or inventoryApi are executed in the tenant scope by default:
@EventListener annotation and scope
Example for @EventListener annotation and tenant scope:
The @EnableMicroserviceSecurity annotation sets up the standard security configuration for microservices.
It enforces basic authentication or other standard authentication mechanisms (refer to Authentication and authorization)
for all endpoints – except for the health check endpoint configured via @EnableHealthIndicator.
You can configure security for your endpoints using standard Spring Security annotations. For example, you can restrict access based on platform roles using @PreAuthorize("hasRole('ROLE_A')").
Microservice subscription
The microservice subscription module handles two core functions:
Registration
Tenant subscription event listening
The default behavior for the package is self-registration, which means that after you run the application it will try to register and use the generated credentials for the communication with the platform. The self-registration is required to correctly deploy the microservice on the platform.
The other way to register an application to the platform is to do it manually. This can be done by creating a new application on the platform with the same application name and providing the following properties into the microservice:
The subscription package provides means to monitor and it acts upon changes in tenant subscriptions to a microservice. To add a custom behavior, a developer can add an event listener for MicroserviceSubscriptionAddedEvent and MicroserviceSubscriptionRemovedEvent as the following example:
On application startup, the MicroserviceSubscriptionAddedEvent is triggered for all subscribed tenants.
Configuration files
The application.properties file used by the hosted deployment must be located in src/main/resources/.
The following properties are used by a microservice:
General properties
Property
Description
application.name
The name of the microservice application.
C8Y.bootstrap.register
Indicates if a microservice should follow the self-registration process. True by default.
C8Y.baseURL
Address of the platform. Provided by the deployment process.
C8Y.baseURL.mqtt
Address of the MQTT service. Provided by the platform.
C8Y.bootstrap.tenant
The tenant ID, owner of the microservice.
C8Y.bootstrap.user
Username used by a microservice or by the microservice registration process.
C8Y.bootstrap.password
Password used by a microservice or by the microservice registration process.
C8Y.bootstrap.delay
Subscription refresh delay (milliseconds).
C8Y.bootstrap.initialDelay
Initial subscription delay (milliseconds).
C8Y.microservice.isolation
Microservice isolation. Only PER_TENANT or MULTI_TENANT values are available. MULTI_TENANT by default.
HTTP client configuration properties
Property
Description
Default value
C8Y.httpClient.httpReadTimeout
HTTP read timeout (milliseconds).
180000
C8Y.httpClient.pool.enabled
HTTP connection pooling enabled.
true
C8Y.httpClient.pool.perHost
Max connections per host if the connection pooling is enabled.
50
C8Y.httpClient.pool.max
Max total connections if the connection pooling is enabled.
100
C8Y.httpClient.pool.awaitTimeout
Connection manager timeout (milliseconds).
10000
Info
No changes should be made unless the request/connection timeouts or HTTP client related exceptions are being experienced for the requests to the microservice where the network environment is fully understood.
Microservice settings
The microservice settings module provides two features:
Configure a microservice by defining tenant options
Override existing properties - Tenant options can override default values from properties files
By default the microservice loads the tenant options for the category specified by the microservice context path.
The custom settings category can be specified by the manifest parameter: settingsCategory.
Note that the defined tenant option category must be unique within the tenant.
When neither settings category nor context path is provided in the microservice manifest, the application name is used.
Info
Once the microservice is deployed it is not possible to change the category during application upgrade.
Options can be configured for the application owner or the subscriber. The subscriber can override the owner’s option value only when such option is defined as editable.
Settings are lazy cached for 10 minutes, so when they were accessed previously, the user must wait the remaining time to see the change being applied.
When the access attempt occurs to fetch settings without the tenant context being specified, the application owner is used to complete the request.
Info
For security reasons, the functionality is not available when running the microservice in legacy mode, that is, local development or RPM installation.
Tenant option settings can be accessed in two ways:
@Autowiredprivate MicroserviceSettingsService settingsService;
public String getAccessTimeout() {
return settingsService.get("access.timeout");
}
Settings can be encrypted by using the credentials. prefix for the tenant option key. They will be decrypted and become available within the microservice environment.
Defining tenant options for a microservice with the same key as it was defined in the configuration files, such as .properties or the manifest file, will override the particular property.
For instance, there is a property defined in the application.properties file of the microservice hello-world with context path helloworld:
access.timeout=25
Now the microservice owner can override it by defining the following setting in the cumulocity.json manifest file:
You cannot override a property injected by Spring @Value("${property.name}").
Logging
The standard output should be used for hosted deployments.
For more details on how to use your own log configuration file refer to Logging.
Maven plugin
The package module provides a Maven plugin to prepare a ZIP file required by the microservice deployment. The build requires an executable JAR file. To create one, a developer can use spring-boot-maven-plugin. An example with minimum configuration is presented below:
The package plugin is responsible for the creation of a Docker container, RPM file and for creating a ZIP file that can be deployed on the platform.
It can be configured with the following parameters:
(If a single xml tag is specified as parameter in the following list, use embracing xml tags like <tag>…</tag> to set those parameters. “…” must be replaced by the respective value of the corresponding data type.)
Parameter short form for pom.xml entries in <configuration> section
Data type
Parmameter command line name
Default value
Description
<arguments>
List<String>
‑Dagent-package.arguments=[…,]…
""
General command line arguments for jar startup. Specify with “,” separated arguments.
<containerSkip>
Boolean
‑Dskip.agent.package.container=…
false
Skip the container packaging
<description>
String
‑Dpackage.description=…
${project.description}
Microservice description
<dockerBuildTimeout>
Int
‑Dmicroservice.package.dockerBuildTimeout=…
360
Timeout value in seconds for the generation of a docker build
<encoding>
String
‑Dproject.build.sourceEncoding=…
UTF-8
Define String encoding
<heap> <min>…</min> <max>…<max> </heap>
min, max : <Int>m (m:megabytes; for available units refer to Java documentation)
Java runtime arguments for the microservice startup. Specify with “,” separated arguments. Default values will be overwritten if other options are provided.
<metaspace> parameter is combined with <perm> parameter values if available which results in ‑XX:MetaspaceSize=<min> ‑XX:MaxMetaspaceSize=<max> Java runtime arguments for the microservice startup.
<name>
String
‑Dpackage.name=…
${project.artifactId}
Microservice name
<perm> <min>…</min> <max>…<max> </perm>
min, max : <Int>m (m:megabytes; for available units refer to Java documentation)
<perm> parameter is combined with <metaspace> parameter values for compatibility reasons if available which results in ‑XX:MetaspaceSize=<min> ‑XX:MaxMetaspaceSize=<max> Java runtime arguments for the microservice startup.
Settings for heap and metaspace must be aligned with your settings of resources/memory in the microservice manifest
file cumulocity.json. You have to be sure about the effect those parameters might have. Those parameters are directly
used for the microservice start without further verification. For example be sure that the heap values meet the
condition: Xms < Xmx.
Setting parameters on command line
For information about how and whether it is possible to set parameters on command line refer to column
“Parameter command line name” of table in chapter Package goal.
Primitive configuration values
Primitive configuration values or lists can be set on the Maven command line directly as usual for Maven command line
properties. Items of lists are specified with , as separation character.
Complex data types as for heap and metaspace parameter
Properties must be used if you want to specify data of complex data types on the command line. This is the case for
memory data like heap and metaspace. In this case you have to specify each primitive value separately as pom property
which is then used inside the configuration of the microservice-package-maven-plugin.
Example for the definition of primitive default parameters in pom.xml:
These properties can be used inside the configuration section of the microservice-package-maven-plugin
defined in the pom.xml file of your microservice project:
Available since version 2026.29.0, the validate REST security goal scans compiled classes to ensure all REST controller endpoints have proper security annotations. This provides build-time verification that your microservice endpoints are adequately secured.
The goal verifies that all REST endpoints are either secured with one of the recognized security annotations or explicitly marked as unsecured.
Configuring the goal
Add the following to your microservice pom.xml file:
Use the @UnauthorizedEndpoint annotation from the com.cumulocity.microservice.security.annotation package to mark endpoints that intentionally do not require authentication. The annotation accepts an optional parameter to document why the endpoint is unsecured.
Example build output
When validation succeeds, you see a message similar to:
[INFO] Starting REST endpoint security validation...
[INFO] Found 5 REST controller classes
[INFO] ✓ All REST endpoints are properly secured!
When validation fails with unsecured endpoints, the build stops with error messages:
[ERROR] Found 2 unsecured REST endpoints:
[ERROR] - REST endpoint not secured: com.example.UserController.deleteAll.
[ERROR] Must be annotated with @PreAuthorize, @Secured, @RolesAllowed, or @UnauthorizedEndpoint.
[ERROR] - REST endpoint not secured: com.example.ConfigController.reset.
[ERROR] Must be annotated with @PreAuthorize, @Secured, @RolesAllowed, or @UnauthorizedEndpoint.
Push goal
The push plugin is responsible for pushing the Docker image to a registry. The registry can be configured by:
containerSkip (alias skip.agent.package.container) - Prevents the push to execute. True by default
The upload goal is responsible for deploying the microservice to a server.
There are three options to configure the server URL and credentials:
settings.xml - Maven global configuration placed at ~/.m2/settings.xml
pom.xml - Maven project configuration file
Command line
All three ways can be used together, for example, a goal partially can be configured in the settings.xml and partially in the pom.xml.
In case of conflicts, the command line configuration has the highest priority and settings.xml configuration the lowest.
To upload a microservice to the server you must configure the following properties:
url - Mandatory URL that will be used for deployment. Empty by default.
username - Mandatory tenant ID and username used for authorization. Empty by default.
password - Mandatory password used for authorization. Empty by default.
name - Optional name of the uploaded application. By default it is the same as package.name property or artifactId if package.name is not provided.
skipMicroserviceUpload (alias skip.microservice.upload) - Controls if the microservice upload should be skipped. True by default so for the goal to work it must be set to false)
settings.xml
To configure the goal in the settings.xml file, add the server configuration as follows:
To configure the plugin in the pom.xml file, add the server configuration as follows:
<plugin><groupId>com.nsn.cumulocity.clients-java</groupId><artifactId>microservice-package-maven-plugin</artifactId><configuration><application><name>helloworld</name></application><!-- please note that the credentials are optional if they are already configured in settings.xml --><credentials><url>https://demos.cumulocity.com</url><username>demos/username</username><password>******</password></credentials><skipMicroserviceUpload>false</skipMicroserviceUpload></configuration></plugin>
Command line
To pass the configuration only to the particular build, execute the following command:
Running Maven CLI commands in debug mode (for example, mvn clean install --debug ...) may
generate a very large volume of HTTP-related log output, such as logs from resource downloads.
Analyzing this data might quickly become tedious.
To reduce such logging information, HTTP logging can be suppressed with these command line options:
Besides off, error or warn might also be appropriate values. The parameters can also be added to the Maven configuration file ${MAVEN_HOME}/conf/logging/simplelogger.properties
or to the MAVEN_OPTS environment variable. Related documentation can be found in Maven logging.
Heap and perm/metadata
To calculate heap and perm/metadata, it takes the limit defined in the microservice manifest (resources/memory) and it is converted into Megabytes (MB). For Java applications developed using the Java Microservice SDK the minimal value is 178MB.
10% is reserved for “system”, but not less than 50 MB.
10% is taken for metaspace, but not less than 64 MB and not more than 1024MB.
The rest is allocated for heap size.
Refer to Package goal for information on how to change the heap and metaspace settings.
Deployment
Hosted deployment
Info
For your convenience, Cumulocity provides a Microservice utility tool for easy packaging, deployment and subscription.
To deploy an application on an environment you need the following:
URL address of your tenant
Authorization header as “Basic <Base64(:)>”
Tenant - tenant ID
ZIP build from previous steps
Step 1 - Create the application
If the application does not exist, create a new application on the platform:
To deploy the application on a local Docker container, one must inject the environment variables into a container. This is done with the Docker run -e command. The full description of available parameters is available in Environment variables.
An example execution could be:
$ docker run -e "C8Y_BASEURL=<C8Y_BASEURL>" -e "C8Y_BASEURL_MQTT=<C8Y_BASEURL_MQTT>" -e "C8Y_BASEURL_PULSAR=<C8Y_BASEURL_PULSAR>" <IMAGE_NAME>
Monitoring
The microservice’s health endpoint can be checked to verify if a hosted microservice is running successfully.
This endpoint is enabled by default for all microservices that are developed using the Java Microservice SDK.
GET <URL>/service/<APPLICATION_NAME>/health
Example response when the microservice is functional:
HTTP/1.1200{
"status": "UP"}
or in case it is not working:
HTTP/1.1503{
"status": "DOWN"}
Legacy Deployment
Properties
For external/legacy deployment, the following paths will be searched in order to find a properties file specific for the environment the application is run on:
To customize the logging configuration for your microservice instead of using the default configuration, create a log
configuration file in the configuration folder of your microservice project.
The file must adhere to the naming convention <application-name>-logging.xml.
This ensures that your custom log configuration replaces the default configuration file
with the same name in the resulting Docker image.
Once deployed, the customized log configuration file will be located in the /etc/<artifactId>
directory within the microservice pod.
Locations to be searched for log configuration file
For external/legacy deployments, logging into the application implies using Spring Logging.
The following locations are searched for the logback configuration file:
Jackson 2.12.x does not provide the Joda Module by default, it might be required to add jackson-datatype-joda dependency and define Joda Module:
new ObjectMapper().addModule(new JodaModule()); in a custom Microservice code.
Spring Boot 2.5.8 does not provide the Bean Validation 2.0 provider as a transitive dependency anymore. Developers may have to explicitly define a validation provider, for example hibernate-validator, or add the spring-boot-starter-validation dependency.
The message field and binding errors are disabled by default for Spring Boot native error responses. This can be enabled by overriding the microservice_error_attributes.properties file.
A Spring Boot library was upgraded to 2.7.6, hence upgrading Microservice SDK to 10.17+ may require some additional development.
There was a change in the internal microservice security configuration following
the deprecation of WebSecurityConfigurerAdapter by Spring Security. The Microservice SDK now uses a direct
declaration of the SecurityFilterChain bean in its internal configuration instead. At the same time, Spring Security
only allows one of these configuration approaches in a single application. This means that if the old,
adapter-based method has been used in your code before, you will have to migrate to the new, direct filters
declaration for applications to start. Refer to the Spring Security release notes for more details.
Client library
This section provides an overview on how to access Cumulocity from Java clients, starting from connecting to the platform over accessing data to remote control of devices. It also discusses how to extend the Cumulocity domain model from Java for new devices and other business objects. Finally, this section describes how to configure the logging service in order to control the level of diagnostic messages generated by the client.
The client library is tightly linked to the design of the REST interfaces, which are described in REST implementation in the Cumulocity OpenAPI Specification.
Connecting to the platform
The root interface for connecting to Cumulocity from Java is called Platform (see Root interface in REST implementation in the Cumulocity OpenAPI Specification). It provides access to all other interfaces of the platform, such as the inventory. In its simplest form, it is instantiated as follows:
Platform platform = new PlatformImpl("<URL>", CumulocityBasicCredentials.from("<TENANT_ID>/<USERNAME>:<PASSWORD>"));
As an example:
Platform platform = new PlatformImpl("https://demos.cumulocity.com", CumulocityBasicCredentials.from("mytenant/myuser:mypassword"));
If you use the Java client for developing an application, you must register an application key (through Managing applications in the Cumulocity Administration application, or through the Application API).
For testing purposes, every tenant is subscribed to the demo application key “uL27no8nhvLlYmW1JIK1CA==”. The platform is then initialized like this:
new PlatformImpl("<URL>", "<TENANT_ID>", "<USERNAME>", "<PASSWORD>", "<APPLICATION_KEY>");
The constructor for PlatformImpl also allows you to specify the default number of objects returned from the server in one reply with the parameter pageSize:
new PlatformImpl("<URL>", "<TENANT_ID>", "<USERNAME>", "<PASSWORD>", "<APPLICATION_KEY>", <PAGE_SIZE>);
Accessing the inventory
The following code snippet shows how to obtain a handle to the inventory:
Using this handle, you can create, retrieve and update managed objects. For example, if you would like to retrieve all objects that have a geographical position, use the following:
InventoryFilter inventoryFilter = new InventoryFilter();
inventoryFilter.byFragmentType(Position.class);
ManagedObjectCollection moc = inventory.getManagedObjectsByFilter(inventoryFilter);
Note that it returns a query to get the objects but it does not actually get them. In practice, such a list of objects could be very large. Hence, it is returned in pages from the server. To get all pages and iterate over them, use the following:
for (ManagedObjectRepresentation mo : moc.get().allPages()) {
System.out.println(mo.getName());
}
Important
By default, allPages() doesn’t return all elements at once, rather in batches of 5 elements (paginated). A separate request is made for each subsequent page after the iteration of the previous page is completed. Hence, it is not recommended to change/edit those objects while iterating through them, otherwise the filters may include/exclude different elements. It is better to collect them all and save them in memory, and only then perform edit operations.
To create a new managed object, construct a local representation of the object and send it to the platform. The following code snippet shows how to create a new electricity meter with a relay in it:
ManagedObjectRepresentation mo = new ManagedObjectRepresentation();
mo.setName("MyMeter-1");
Relay relay = new Relay();
mo.set(relay);
SinglePhaseElectricitySensor meter = new SinglePhaseElectricitySensor();
mo.set(meter);
// Set additional properties, for example, tariff tablesmo = inventory.create(mo);
System.out.println(mo.getId());
By invoking the create() method, a new managed object is created with an auto-generated unique identifier.
Assume that you would like to store additional custom properties along with the device. This can be done by creating a new fragment in the form of a Java bean. For example, assume that you would like to store tariff information along with your meter. There is a day and a night time tariff, and you must store the hours during which the night time tariff is active:
Now, you can add the tariff information to your meter:
Tariff tariff = new Tariff();
mo.set(tariff);
Accessing the identity service
A device typically has a technical identifier that an agent must know to be able to contact the device. Examples are meter numbers, IP addresses and REST URLs. To associate such identifiers with the unique identifier of Cumulocity, agents can use the identity service. Again, to create the association, create an object of type ExternalIDRepresentation and send it to the platform.
The code snippet below shows how to register a REST URL for a device. It assumes that mo is the managed object from the above example and deviceUrl is a string with the REST URL of the device.
final String ASSET_TYPE = "com_cumulocity_idtype_AssetTag";
final String deviceUrl = "SAMPLE-A-239239232";
ExternalIDRepresentation externalIDGid = new ExternalIDRepresentation();
externalIDGid.setType(ASSET_TYPE);
externalIDGid.setExternalId(deviceUrl);
externalIDGid.setManagedObject(mo);
IdentityApi identityApi= platform.getIdentityApi();
identityApi.create(externalIDGid);
Now, if you need the association back, you can just query the identity service as follows:
ID id = new ID();
id.setType(ASSET_TYPE);
id.setValue(deviceUrl);
externalIDGid = identityApi.getExternalId(id);
The returned object will contain the unique identifier and a link to the managed object.
Accessing events and measurements
Events and measurements can be accessed in a very similar manner as described above for the inventory. The following example queries the signal strength of the mobile connection of devices in the past two weeks and prints the device ID, the time of the measurement, the received signal strength and the bit error rate.
MeasurementApi measurementApi = platform.getMeasurementApi();
MeasurementFilter measurementFilter = new MeasurementFilter();
Calendar cal = Calendar.getInstance();
Date toDate = cal.getTime();
cal.add(Calendar.DATE, -14);
Date fromDate = cal.getTime();
measurementFilter.byDate(fromDate, toDate);
measurementFilter.byFragmentType(SignalStrength.class);
MeasurementCollection mc = measurementApi.getMeasurementsByFilter(measurementFilter);
MeasurementCollectionRepresentation measurements = mc.get();
for (; measurements != null; measurements = mc.getNextPage(measurements)) {
for (MeasurementRepresentation measurement : measurements.getMeasurements()) {
SignalStrength signal = measurement.get(SignalStrength.class);
System.out.println(measurement.getSource().getId() + " " + measurement.getTime() + " " + signal.getRssiValue() + " " + signal.getBerValue());
}
}
Controlling devices
The DeviceControlResource enables you to manipulate devices remotely. It has two sides: You can create operations in applications to be sent to devices, and you can query operations from agents.
In order to control a device it must be in the child devices hierarchy of an agent managed object. The agent managed object represents your agent in the inventory. It is identified by a fragment com_cumulocity_model_Agent. This is how Cumulocity identifies where to send operations to control a particular device.
The following code demonstrates the setup:
ManagedObjectRepresentation agent = new ManagedObjectRepresentation();
agent.set(new com.cumulocity.model.Agent()); // agents must include this fragment// ... create agent in inventoryManagedObjectRepresentation device;
// ... create device in inventoryManagedObjectReferenceRepresentation child2Ref = new ManagedObjectReferenceRepresentation();
child2Ref.setManagedObject(device);
inventory.getManagedObject(agent.getId()). addChildDevice(child2Ref);
For example, assume that you would like to switch off a relay in a meter from an application. Similar to the previous examples, you create the operation to be executed locally, and then send it to the platform:
DeviceControlApi control = platform.getDeviceControlApi();
OperationRepresentation operation = new OperationRepresentation();
operation.setDeviceId(mo.getId());
relay.setRelayState(RelayState.OPEN);
operation.set(relay);
control.create(operation);
Now, if you want to query the pending operations from an agent, the following code must be executed:
Again, the returned result may come in several pages due to its potential size.
OperationCollectionRepresentation opCollectionRepresentation;
for (opCollectionRepresentation = oc.get(); opCollectionRepresentation != null; opCollectionRepresentation = oc.getNextPage(opCollectionRepresentation)) {
for (OperationRepresentation op : opCollectionRepresentation.getOperations()) {
System.out.println(op.getStatus());
}
}
Realtime features
The Java client libraries fully support the real-time APIs of Cumulocity. For example, to get immediately notified when someone sends an operation to your agent, use the following code:
“agentId” is the ID of your agent in the inventory.
To unsubscribe from a subscription, use the following code:
subscription.unsubscribe();
If you wish to disconnect, the following code must be used:
subscriber.disconnect();
Subscribing to Notifications 2.0
The Notifications 2.0 API can be accessed in a very similar manner as described above in Accessing the inventory.
See Notifications 2.0 for more details about the API.
The following snippet shows how users can create, query and delete notification subscriptions. It also shows how a token string can be obtained.
// Obtain a handle to the Subscription and Token APIs:privatefinal NotificationSubscriptionApi notificationSubscriptionApi = platform.getNotificationSubscriptionApi();
privatefinal TokenApi tokenApi = platform.getTokenApi();
// Create subscription filterfinal NotificationSubscriptionFilterRepresentation filterRepresentation = new NotificationSubscriptionFilterRepresentation();
filterRepresentation.setApis(List.of("measurements"));
filterRepresentation.setTypeFilter("c8y_Speed");
// Construct subscription for managed object contextfinal NotificationSubscriptionRepresentation subscriptionRepresentation1 = new NotificationSubscriptionRepresentation();
subscriptionRepresentation1.setContext("mo");
subscriptionRepresentation1.setSubscription("testSubscription1");
subscriptionRepresentation1.setSource(mo);
subscriptionRepresentation1.setSubscriptionFilter(filterRepresentation);
subscriptionRepresentation1.setFragmentsToCopy(List.of("c8y_SpeedMeasurement", "c8y_MaxSpeedMeasurement"));
// Create subscription for managed object contextsubscriptionApi.subscribe(subscriptionRepresentation1);
// Construct subscription for tenant contextfinal NotificationSubscriptionRepresentation subscriptionRepresentation2 = new NotificationSubscriptionRepresentation();
subscriptionRepresentation2.setContext("tenant");
subscriptionRepresentation2.setSubscription("testSubscription2");
// Create subscription for tenant contextsubscriptionApi.subscribe(subscriptionRepresentation2);
// Obtain access tokenfinal NotificationTokenRequestRepresentation tokenRequestRepresentation = new NotificationTokenRequestRepresentation(
properties.getSubscriber(), // The subscriber name with which the client wishes to be identified."testSubscription1", // The subscription name. This value should be the same as with which the subscription was created. The access token will be only valid for the subscription specified here. 1440, // The token expiration duration in minutes.false);
// The obtained token is required for establishing a WebSocket connection. Refer to [Notifications 2.0](https://cumulocity.com/api/core/#tag/Notification-2.0-API) for more details.final String token = tokenApi.create(tokenRequestRepresentation).getTokenString();
// Query all subscriptionsfinal NotificationSubscriptionCollection notificationSubscriptionCollection = subscriptionApi.getSubscriptions();
final List<NotificationSubscriptionRepresentation> subscriptions = notificationSubscriptionCollection.get().getSubscriptions();
for (NotificationSubscriptionRepresentation subscriptionRepresentation : subscriptions) {
System.out.println(subscriptionRepresentation);
}
// Query subscriptions by filterfinal NotificationSubscriptionCollection filteredNotificationSubscriptionCollection = subscriptionApi
.getSubscriptionsByFilter(new NotificationSubscriptionFilter().byContext("mo"));
final List<NotificationSubscriptionRepresentation> filteredSubscriptions = filteredNotificationSubscriptionCollection.get().getSubscriptions();
for (NotificationSubscriptionRepresentation subscriptionRepresentation : filteredSubscriptions) {
System.out.println(subscriptionRepresentation);
}
// Delete all tenant subscriptionssubscriptionApi.deleteTenantSubscriptions();
// Delete by sourcesubscriptionApi.deleteBySource(mo.getId().getValue());
In particular on mobile devices, Internet connectivity might be unreliable. To support such environments, the Java client libraries support local buffering. This means that you can pass data to the client libraries regardless of an Internet connection being available or not. If a connection is available, the data will be sent immediately. If not, the data will be buffered until the connection is back again. For this, asynchronous variants of the API calls are offered. For example, to send an alarm:
The createAsync method returns immediately. The Future object can be used to determine the result of the request whenever it was actually carried out.
Logging configuration
Logging in the Java client SDK is handled through slf4j with a logback backend. For a detailed description on how to use and configure logging, see the logback documentation.
Since version 10.11, the default logging level of the SDK is set to “Error” for all components, which means that logging messages are suppressed unless their level is “Error”. If everything runs smoothly, there should be no log messages generated by the SDK. By default, log messages are sent to the console only.
The default logging configuration can be changed by providing a new configuration file. Two methods for providing the configuration file are discussed here: via an absolute filename passed using a system property; and via an OSGi fragment. Note that both of these methods override the default behaviour, rather than extending it.
Services platform and SMS API
This section describes the Cumulocity SMS API and shows how to access it using the Cumulocity Java Client. You will also learn how to send and receive SMS messages via the Java Client API.
Using the services platform
The services platform interface is responsible for connecting to the Java services (SMS) API.
ServicesPlatform platform = new ServicesPlatformImpl("<URL>", new CumulocityCredentials("<tenant>", "<user>", "<password>", "<application key>"));
The URL pointing to the platform must be of the form <tenant>.cumulocity.com, for example https://demos.cumulocity.com, which will process all the API requests.
Info
You must have appropriate credentials to be able to access the Services API from outside. See the example above.
Accessing the SMS Messaging API
The following code snippet shows how to obtain a handle to the SMS API from Java.
Using this handle, you can send and retrieve the SMS messages from Java by calling its functions.
Assigning required permissions and roles
To use the SMS messaging API, the user must have the ADMIN and READ permission for “SMS” (SMS_ADMIN and SMS_READ) for sending and receiving messages respectively.
Refer to Managing permissions and roles for more information.
Sending a message
To send a SMS message using the API, prepare the message with the SendMessageRequest builder and call the sendMessage function of the API with the prepared message.
You can use the API as follows to receive a specific SMS message identified by message ID. Note that not every SMS provider supports receiving messages.
Cumulocity supports the OpenTelemetry (OTLP) framework for exporting telemetry data (metrics, logs, and traces) from your microservice to help you analyze your application’s performance and behavior.
The Java Microservice SDK leverages the OpenTelemetry Java agent which provides automatic instrumentation for many popular libraries and frameworks.
Enabling auto-instrumentation
The instrumentation of the microservice application by the OpenTelemetry Java agent is controlled by the otel.javaagent.enabled parameter. Setting this parameter to true enables instrumentation.
If enabled, the Java agent JAR file is attached to the microservice JVM at startup time.
Important
To enable or disable instrumentation, the microservice must be unsubscribed and subscribed again.
Configuring auto-instrumentation for selected libraries or frameworks, or opting for manual instrumentation only, is described
in the OpenTelemetry instrumention documentation.
Maven configuration
Besides setting up the OTLP configuration in tenant options, the Java agent JAR file must be included in the microservice image at build time.
By default, this JAR file is not contained in the image.
To download and copy the Java agent JAR file to the microservice image, the microservice-package-maven-plugin must be
configured with the otelJavaAgentInclude element set to true in the Maven pom.xml file:
The Java agent JAR file download URL can be set with the parameter otelJavaAgentDownloadUrl.
Important
If the Java agent JAR file is not contained in the microservice image
and otel.javaagent.enabled is set to true, then the microservice will fail to start.
The error message will be like “Error opening … opentelemetry-javaagent.jar”.
Manual instrumentation
In addition to automatic instrumentation, microservices can be manually instrumented.
The Java agent creates the GlobalOpenTelemetry object which can be used as a starting point to create
individual Tracer or Meter objects for custom instrumentation.
Java code example:
import io.opentelemetry.api.GlobalOpenTelemetry;
import io.opentelemetry.api.metrics.Meter;
Meter meter = GlobalOpenTelemetry.getMeter("application");
If instrumentation with the Java agent is disabled, complete manual instrumentation without the Java agent can be applied as well.
Detailed examples for various use cases can be found in the OpenTelemetry GitHub repository.
Maven dependencies
The Maven pom.xml file of the microservice application needs to be extended with the required OTLP library dependencies according to the manual instrumentation code.
Troubleshooting
Some common problems and their solutions have been identified and documented below.
SSL or certificate errors
You can use both HTTP and HTTPS from the Java client libraries. To use HTTPS, you may need to import the Cumulocity production certificate into your Java Runtime Environment. Download the certificate with the following command:
If you use Eclipse/OSGi, open the Run Configurations… dialog in the Run menu. Double-click OSGi Framework, then open the Arguments tab on the right side. In the VM arguments text box, add the above parameter.
Since the Java SDK comes with its own set of trusted root certificates, you might still get the error message “java.security.cert.CertificateException: Certificate Not Trusted”. In this case, make sure that the GoDaddy Certificate Authority (CACert) is available for your Java environment using the following command:
The gd_bundle.crt certificate can be downloaded directly from the GoDaddy repository.
When I install the SDK, Eclipse complains about compatibility problems
Make sure that you use the Target Platform preferences page to install the SDK as described in the instructions. Install New Software installs software into your running Eclipse IDE, but you must install the SDK as a separate server software.
I get “Expected to find an object at table index” when running a microservice or application
This error occurs due to a bug in particular Eclipse versions. As a workaround, select Run from the main menu and then Run Configurations …. On the left, select the launch configuration that you have been using, for example, OSGi Framework. On the right, click the Arguments tab. Append a " -clean" to the Program Arguments and click Apply.
The microservice or application won’t start
Verify that all required plugins are checked in your launch configuration. Go to Run > Run Configurations and select the OSGi Framework launch configuration. Click Select All and try running it again.
Check if the required plugins are started. While the application or microservice is running, type “ss” into the console and hit the return key. All listed plugins should be either in the ACTIVE or RESOLVED state.
Check if you are using the correct target platform. Go to the Target Platform page in the preferences and check if “Cumulocity runtime” is checked.
The microservice application does not compile. I get “Access Restriction” messages
This error may be caused because of a missing package import. Navigate to the Dependencies tab of the project manifest file and check if the package of the type that contains the method giving the access restriction is present in the Import-Package section.
You can find the package by opening the declaration of the method (right-click and select Open Declaration from the context menu).
When starting an application I get “address already in use” messages
Check if you are running another instance of the application. Click on the Display Selected Console icon in the console toolbar (the terminal icon) to browse through your consoles. Terminate other running instances by clicking the red Stop icon in the toolbar.
Under Unix/macOS you can also use the lsof command to see which process is using a particular port. For example, to see which process is using TCP port 8080 enter:
$ lsof -i tcp:8080
It will return something like:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
java 12985 neo 45u IPv6 0x077c76d0 0t0 TCP *:8080 (LISTEN)
This means that the process 12985 is using the 8080 port and it can be killed if necessary.
When trying to build an application I get a “BeanCreationException: Error creating bean with name methodSecurityInterceptor” error
This is caused mainly by versions incompatibility between the SDK and Spring Boot specified in your pom.xml file. If you want to use a recent version of the SDK, for example, 1016.0.0, the version of Spring Boot must be compatible or equal to version 2.5.4.
When using the SDK endpoints /env, /configprops, or /quartz I get return values masked with “******”
This behavior changed with the update to Spring Boot version 3.2 in the Microservice SDK. To configure or restore the previous behavior, refer to the Spring Boot documentation.
Endpoints with a trailing slash like /some/greeting/ are no longer accepted
This behavior changed with the update to Spring Boot version 3.2 in the Microservice SDK. To configure the previous behaviour, refer to the Spring Boot Migration guide.
Missing Docker permissions in Linux
When you build a microservice application via mvn, you might get this error:
[ERROR] Failed to execute goal com.nsn.cumulocity.clients-java:microservice-package-maven-plugin:1004.6.12:package (package) on project hello-microservice-java: Execution package of goal com.nsn.cumulocity.clients-java:microservice-package-maven-plugin:1004.6.12:package failed: org.apache.maven.plugin.MojoExecutionException: Exception caught: java.util.concurrent.ExecutionException: com.spotify.docker.client.shaded.javax.ws.rs.ProcessingException: java.io.IOException: Permission denied -> [Help 1]
This is an issue with Docker in Linux OS.
You can verify that your user is lacking permissions for Docker by running:
$ docker ps
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix /var/run/docker.sock: connect: permission denied
In order to fix this, do the following:
Create the Docker group.
$ sudo groupadd docker
Add your user to the Docker group.
$ sudo usermod -aG docker $your_user_name
Log out and log back in, so that your group membership is updated. Alternatively, run