-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathAttachmentHttpMessageWriter.java
More file actions
75 lines (62 loc) · 2.36 KB
/
AttachmentHttpMessageWriter.java
File metadata and controls
75 lines (62 loc) · 2.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
/*
* Copyright 2016-2025 Berry Cloud Ltd. All rights reserved.
*/
package dev.learning.xapi.client;
import dev.learning.xapi.model.Attachment;
import java.util.List;
import java.util.Map;
import org.reactivestreams.Publisher;
import org.springframework.core.ResolvableType;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.core.io.buffer.DataBufferUtils;
import org.springframework.http.MediaType;
import org.springframework.http.ReactiveHttpOutputMessage;
import org.springframework.http.codec.HttpMessageWriter;
import org.springframework.http.codec.multipart.MultipartWriterSupport;
import org.springframework.lang.Nullable;
import reactor.core.publisher.Mono;
/**
* {@link HttpMessageWriter} for writing {@link Attachment} data into multipart/mixed requests.
*
* @author István Rátkai (Selindek)
*/
public class AttachmentHttpMessageWriter extends MultipartWriterSupport
implements HttpMessageWriter<Attachment> {
/**
* Default constructor.
*/
public AttachmentHttpMessageWriter() {
super(List.of(MediaType.MULTIPART_MIXED));
}
/**
* {@inheritDoc}
*/
@Override
public boolean canWrite(ResolvableType elementType, @Nullable MediaType mediaType) {
return Attachment.class.isAssignableFrom(elementType.toClass());
}
/**
* {@inheritDoc}
*/
@Override
public Mono<Void> write(Publisher<? extends Attachment> parts, ResolvableType elementType,
@Nullable MediaType mediaType, ReactiveHttpOutputMessage outputMessage,
Map<String, Object> hints) {
return Mono.from(parts).flatMap(part -> {
// set attachment part headers
outputMessage.getHeaders().setContentType(MediaType.valueOf(part.getContentType()));
outputMessage.getHeaders().set("Content-Transfer-Encoding", "binary");
outputMessage.getHeaders().set("X-Experience-API-Hash", part.getSha2());
// write attachment content
return outputMessage.writeWith(encodePart(part, outputMessage.bufferFactory()));
}).doOnDiscard(DataBuffer.class, DataBufferUtils::release);
}
private Mono<DataBuffer> encodePart(Attachment part, DataBufferFactory bufferFactory) {
return Mono.fromCallable(() -> {
final var buffer = bufferFactory.allocateBuffer(part.getContent().length);
buffer.write(part.getContent());
return buffer;
});
}
}