I have a scenario where in my code creates a file and an event in cumulocity as well. I need to attach the binary file to the event, however none of the API's provide me the functionality, any guidance as to how to go ahead please?
Update:
On having a look at the documentation https://cumulocity.com/api/10.11.0/#tag/Attachments , the binaryElement has a following structure
I have modified my JAVA code in the following manner:
String pathEvent = platform.getUrl().get()+"/event/events/{{eventId}}/binaries";
String pathEventAttachment = pathEvent.replace("{{eventId}}", event.getId().getValue());
HttpHeaders headers = RequestAuthenticationEncoder.encode(getCredentials());
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
map.add("file",new ByteArrayResource(FileUtils.readFileToByteArray(file)));//anychanges here fails the code
map.add("filename", file.getName().getBytes());
HttpEntity<MultiValueMap<String, Object>> request = new HttpEntity<>(map,headers);
restTemplate.postForObject(pathEventAttachment, request, String.class);
log.info("Binary file added to the event {}", event.getId().getValue());
Binary is created for the event, however the filename is incorrect:
Please let me know some insights as to why the name is not changing?
You need to create a POST on /event/events/{{eventId}}/binaries with the appropriate Content-Type and body.
Here is a code snippet in python where a binary (log file) is attached to an event. It just POSTs the file content (bytes) as application/octet-stream
# Create event
logfileEvent = {
'type': 'c8y_Logfile',
'text': 'See attached logfile',
'time': datetime.utcnow().strftime('%Y-%m-%dT%H:%M:%S.%f')[:-3] + 'Z',
'source': {
'id': DEVICE_ID
}
}
res = client.post(C8Y_BASE + '/event/events/', data=json.dumps(logfileEvent))
eventId = res.json()['id']
# Attach Binary
res = client.post(C8Y_BASE + '/event/events/' + eventId + '/binaries', data=bytes(FILE_CONTENT, 'utf-8'), headers={'Content-Type': 'application/octet-stream'})
binaryRef = res.json()['self']
# Update operation
logfileFragment = logfileOperation['c8y_LogfileRequest']
logfileFragment['file'] = binaryRef
updatedOperation = {
'status': 'SUCCESSFUL',
'c8y_LogfileRequest': logfileFragment
}
client.put(C8Y_BASE + '/devicecontrol/operations/' + logfileOperation['id'], data=json.dumps(updatedOperation))