I have implemented it using restTemplates:
Created two pojos EventBinary and BinaryInfo:
@Data
public class BinaryInfo {
/**
* Name of the binary object.
*/
private String name;
/**
* Media type of the file.
*/
private String type;
}
@Data
public class EventBinary {
/**
* Name of the attachment. If it is not provided in the request, it will be set as the event ID.
*/
private String name;
/**
* A URL linking to this resource.
*/
private String self;
/**
* Unique identifier of the event.
*/
private String source;
/**
* Media type of the attachment.
*/
private String type;
}
And Api:
@Slf4j
@Service
public class EventAttachmentApi {
private ContextService<MicroserviceCredentials> contextService;
private EventApi eventApi;
@Autowired
public EventAttachmentApi(ContextService<MicroserviceCredentials> contextService, EventApi eventApi) {
super();
this.contextService = contextService;
this.eventApi = eventApi;
}
public EventBinary uploadEventAttachment(final BinaryInfo binaryInfo, Resource resource, final String eventId) {
EventRepresentation event = eventApi.getEvent(GId.asGId(eventId));
if(event == null) {
return null;
}
HttpHeaders headers = new HttpHeaders();
headers.set("Authorization", contextService.getContext().toCumulocityCredentials().getAuthenticationString());
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
headers.setContentType(MediaType.MULTIPART_FORM_DATA);
MultipartBodyBuilder multipartBodyBuilder = new MultipartBodyBuilder();
multipartBodyBuilder.part("object", binaryInfo, MediaType.APPLICATION_JSON);
multipartBodyBuilder.part("file", resource, MediaType.TEXT_PLAIN);
MultiValueMap<String,HttpEntity<?>> body = multipartBodyBuilder.build();
HttpEntity<MultiValueMap<String, HttpEntity<?>>> requestEntity = new HttpEntity<>(body, headers);
String serverUrl = event.getSelf() + "/binaries";
RestTemplate restTemplate = new RestTemplate();
ResponseEntity<EventBinary> response = restTemplate.postForEntity(serverUrl, requestEntity, EventBinary.class);
if(response.getStatusCodeValue() >= 300) {
log.error("Upload event binary failed with http code {}", response.getStatusCode().toString());;
return null;
}
return response.getBody();
}
}