-
Notifications
You must be signed in to change notification settings - Fork 215
/
CloudEventsMapper.java
197 lines (181 loc) · 9.11 KB
/
CloudEventsMapper.java
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
/*
* Copyright (c) 2022 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.connectivity.service.mapping;
import static java.util.Collections.singletonList;
import static org.eclipse.ditto.json.JsonFactory.newObject;
import java.time.Instant;
import java.util.Base64;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import org.eclipse.ditto.base.model.exceptions.DittoJsonException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.connectivity.api.ExternalMessage;
import org.eclipse.ditto.connectivity.api.ExternalMessageFactory;
import org.eclipse.ditto.connectivity.model.MessageMappingFailedException;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.protocol.Adaptable;
import org.eclipse.ditto.protocol.JsonifiableAdaptable;
import org.eclipse.ditto.protocol.ProtocolFactory;
/**
* A message mapper implementation for the Mapping incoming CloudEvents to Ditto Protocol.
*/
@PayloadMapper(alias = {"CloudEvents",
// legacy full qualified name
"org.eclipse.ditto.connectivity.service.mapping.CloudEventsMapper"})
public final class CloudEventsMapper extends AbstractMessageMapper {
static final String CE_ID = "ce-id";
static final String CE_TYPE = "ce-type";
static final String CE_SOURCE = "ce-source";
static final String CE_SPECVERSION = "ce-specversion";
static final String STRUCTURED_CONTENT_TYPE = "application/cloudevents+json";
static final String DITTO_PROTOCOL_CONTENT_TYPE = "application/vnd.eclipse.ditto+json";
static final String SPECVERSION = "specversion";
static final String ID = "id";
static final String SOURCE = "source";
static final String TYPE = "type";
static final String OUTBOUNDTYPE = "org.eclipse.ditto.outbound";
static final String OUTBOUNDSPECVERSION = "1.0";
static final String OUTBOUNDSOURCE = "https://github.com/eclipse/ditto";
static final String DATA = "data";
static final String DATA_BASE64 = "data_base64";
static final String OUTBOUND_DATA_CONTENT_TYPE = "datacontenttype";
static final String OUTBOUND_TIME = "time";
static final String OUTBOUND_SUBJECT = "subject";
static final String DEFAULT_MAPPING_ERROR_MESSAGE = "This is not a CloudEvent";
@Override
public List<Adaptable> map(final ExternalMessage message) {
final String payload = extractPayloadAsString(message);
final String contentType = message.findContentType().orElse("");
if (contentType.equals(DITTO_PROTOCOL_CONTENT_TYPE)) {
if (isBinaryCloudEvent(message)) {
final JsonifiableAdaptable binaryAdaptable = DittoJsonException.wrapJsonRuntimeException(
() -> ProtocolFactory.jsonifiableAdaptableFromJson(newObject(payload)));
final DittoHeaders headers = binaryAdaptable.getDittoHeaders()
.toBuilder()
.correlationId(message.getHeaders().get(CE_ID))
.build();
return singletonList(
ProtocolFactory.newAdaptableBuilder(binaryAdaptable).withHeaders(headers).build());
} else {
throw MessageMappingFailedException.newBuilder(message.findContentType().orElse(""))
.description(DEFAULT_MAPPING_ERROR_MESSAGE)
.dittoHeaders(DittoHeaders.of(message.getHeaders()))
.build();
}
} else if (contentType.equals(STRUCTURED_CONTENT_TYPE)) {
if (isStructuredCloudEvent(payload)) {
final JsonifiableAdaptable adaptable = extractData(payload);
final DittoHeaders headers = adaptable.getDittoHeaders()
.toBuilder()
.correlationId(getInboundId(payload))
.build();
return singletonList(
ProtocolFactory.newAdaptableBuilder(adaptable).withHeaders(headers).build());
} else {
throw MessageMappingFailedException.newBuilder(message.findContentType().orElse(""))
.description(DEFAULT_MAPPING_ERROR_MESSAGE)
.dittoHeaders(DittoHeaders.of(message.getHeaders()))
.build();
}
} else {
return Collections.emptyList();
}
}
@Override
public DittoHeaders getAdditionalInboundHeaders(ExternalMessage message) {
return DittoHeaders.empty();
}
@Override
public List<ExternalMessage> map(final Adaptable adaptable) {
return List.of(
ExternalMessageFactory.newExternalMessageBuilder(
Map.of(ExternalMessage.CONTENT_TYPE_HEADER, STRUCTURED_CONTENT_TYPE)
)
.withTopicPath(adaptable.getTopicPath())
.withText(getExternalCloudEventSpecifications(adaptable))
.asResponse(isResponse(adaptable))
.asError(isError(adaptable))
.build()
);
}
boolean isStructuredCloudEvent(final String payload) {
final JsonObject jsonObject = newObject(payload);
return jsonObject.getValue(SPECVERSION).isPresent() &&
jsonObject.getValue(TYPE).isPresent() &&
jsonObject.getValue(ID).isPresent() &&
jsonObject.getValue(SOURCE).isPresent();
}
boolean isBinaryCloudEvent(final ExternalMessage message) {
final Map<String, String> headers = message.getHeaders();
return message.getHeaders().containsKey(CE_ID) &&
headers.containsKey(CE_SOURCE) &&
headers.containsKey(CE_TYPE) &&
headers.containsKey(CE_SPECVERSION);
}
private JsonifiableAdaptable extractData(final String message) {
final JsonObject payloadJson = newObject(message);
final Optional<JsonValue> base64Opt = payloadJson.getValue(DATA_BASE64);
final Optional<JsonValue> dataOpt = payloadJson.getValue(DATA);
if (base64Opt.isPresent()) {
final String base64Data = base64Opt.get().asString();
final String decodedData = base64decoding(base64Data);
return DittoJsonException.wrapJsonRuntimeException(
() -> ProtocolFactory.jsonifiableAdaptableFromJson(newObject(decodedData)));
} else if (dataOpt.isPresent()) {
final String structuredData = dataOpt.get().toString();
return DittoJsonException.wrapJsonRuntimeException(
() -> ProtocolFactory.jsonifiableAdaptableFromJson(newObject(structuredData)));
} else {
throw MessageMappingFailedException.newBuilder(STRUCTURED_CONTENT_TYPE)
.description(DEFAULT_MAPPING_ERROR_MESSAGE)
.build();
}
}
private String base64decoding(final String base64Message) {
byte[] messageByte = Base64.getDecoder().decode(base64Message);
return new String(messageByte);
}
private static String getExternalCloudEventSpecifications(final Adaptable adaptable) {
final String outboundID = adaptable.getDittoHeaders().getCorrelationId()
.orElseGet(() -> UUID.randomUUID().toString());
JsonObject dataObject = JsonFactory.newObject(getJsonString(adaptable));
final String topicPathWithoutEntityId = adaptable.getTopicPath().getPath().split("/", 3)[2];
final String type = OUTBOUNDTYPE + ":" + topicPathWithoutEntityId;
final String time = adaptable.getPayload().getTimestamp().orElse(Instant.now()).toString();
final String subject = adaptable.getTopicPath().getNamespace() + ":" + adaptable.getTopicPath().getEntityName();
final JsonObject externalMessageObject = JsonObject.newBuilder()
.set(DATA, dataObject)
.set(SPECVERSION, OUTBOUNDSPECVERSION)
.set(ID, outboundID)
.set(SOURCE, OUTBOUNDSOURCE)
.set(TYPE, type)
.set(OUTBOUND_DATA_CONTENT_TYPE, DITTO_PROTOCOL_CONTENT_TYPE)
.set(OUTBOUND_TIME, time)
.set(OUTBOUND_SUBJECT, subject)
.build();
return externalMessageObject.toString();
}
private static String getInboundId(final String message) {
JsonObject inboundMessageObject = JsonFactory.newObject(message);
return inboundMessageObject.getValue(ID).orElse(JsonValue.of("")).asString();
}
private static String getJsonString(final Adaptable adaptable) {
final var jsonifiableAdaptable = ProtocolFactory.wrapAsJsonifiableAdaptable(adaptable);
return jsonifiableAdaptable.toJsonString();
}
}