Reputation: 87
I developed a microservice which calls the smartrule microservice. I found that: http://www.cumulocity.com/guides/reference/microservice-runtime#Access-to-the-platform-and-other-microservices
However, this doesn’t address if the microservices are subscript to another tenant. This means the base URL can’t be used for that.
I come up with following solution, it is working but I would ask if there is a better approach? I also see the risk of building up URLs which are different to the actual tenant. I can remember at a Cumulocity training that the URL pattern can be differ and the tenant must not be exact in the URL reflected! Maybe the Microservice SDK has some better support to call another microserver in the context?
private boolean callSmartRuleService(SmartRuleRepresentation requestBody, String groupId) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.AUTHORIZATION, "Basic " + getBase64Credentials(contextService.getContext().getUsername(), contextService.getContext().getPassword()));
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<SmartRuleRepresentation> requestEntity = new HttpEntity<>(requestBody, headers);
StringBuilder urlBuilder = new StringBuilder();
urlBuilder.append("https://")
.append(contextService.getContext().getTenant())
.append(c8yBaseURL.substring(c8yBaseURL.indexOf(".", 8)))
.append("/service/smartrule/managedObjects/")
.append(groupId).append("/smartrules");
ResponseEntity<String> response = restTemplate.exchange(urlBuilder.toString(), HttpMethod.POST, requestEntity, String.class);
if (response.getStatusCode().is2xxSuccessful()) {
return true;
} else
return false;
}
Upvotes: 1
Views: 248
Reputation: 2049
You shouldn't try to build your own URL. Simply send to the baseURL provided by the environment variables in your microservice.
You simply need to include the tenant into the credentials (tenant/username:password). Then Cumulocity will take care that it is processed in the correct tenant context. When the tenant is passed as part of the credentials Cumulocity will always build the context from that (regardless of the domain).
Keep in mind when you talking to another microservice that the tenant maybe does not have this microservice or that the microservice is not reachable/crashed etc. Your service should be able to deal with these situations.
Upvotes: 1