/
MessageMappingProcessorActorTest.java
301 lines (257 loc) · 14.1 KB
/
MessageMappingProcessorActorTest.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
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/*
* Copyright (c) 2017-2018 Bosch Software Innovations GmbH.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* https://www.eclipse.org/org/documents/epl-2.0/index.php
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.eclipse.ditto.services.connectivity.messaging;
import static org.assertj.core.api.Assertions.assertThat;
import static org.eclipse.ditto.model.base.headers.DittoHeaderDefinition.CORRELATION_ID;
import static org.eclipse.ditto.services.connectivity.messaging.TestConstants.Authorization.AUTHORIZATION_CONTEXT;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import org.eclipse.ditto.json.JsonPointer;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.model.base.auth.AuthorizationContext;
import org.eclipse.ditto.model.base.auth.AuthorizationModelFactory;
import org.eclipse.ditto.model.base.common.DittoConstants;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.connectivity.ConnectionSignalIdEnforcementFailedException;
import org.eclipse.ditto.model.connectivity.ConnectivityModelFactory;
import org.eclipse.ditto.model.connectivity.Enforcement;
import org.eclipse.ditto.model.connectivity.MappingContext;
import org.eclipse.ditto.model.connectivity.UnresolvedPlaceholderException;
import org.eclipse.ditto.protocoladapter.DittoProtocolAdapter;
import org.eclipse.ditto.protocoladapter.ProtocolFactory;
import org.eclipse.ditto.services.models.connectivity.ExternalMessage;
import org.eclipse.ditto.services.models.connectivity.ExternalMessageFactory;
import org.eclipse.ditto.services.models.connectivity.OutboundSignal;
import org.eclipse.ditto.services.models.connectivity.placeholder.EnforcementFactoryFactory;
import org.eclipse.ditto.services.models.connectivity.placeholder.EnforcementFilter;
import org.eclipse.ditto.services.models.connectivity.placeholder.EnforcementFilterFactory;
import org.eclipse.ditto.services.models.connectivity.placeholder.Placeholder;
import org.eclipse.ditto.signals.commands.things.ThingErrorResponse;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAttribute;
import org.eclipse.ditto.signals.commands.things.modify.ModifyAttributeResponse;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mockito;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
import akka.event.DiagnosticLoggingAdapter;
import akka.testkit.javadsl.TestKit;
/**
* Tests {@link MessageMappingProcessorActor}.
*/
public class MessageMappingProcessorActorTest {
private static final String CONNECTION_ID = "testConnection";
private static final DittoProtocolAdapter DITTO_PROTOCOL_ADAPTER = DittoProtocolAdapter.newInstance();
private static ActorSystem actorSystem;
@BeforeClass
public static void setUp() {
actorSystem = ActorSystem.create("AkkaTestSystem", TestConstants.CONFIG);
}
@AfterClass
public static void tearDown() {
if (actorSystem != null) {
TestKit.shutdownActorSystem(actorSystem, scala.concurrent.duration.Duration.apply(5, TimeUnit.SECONDS),
false);
}
}
@Test
public void testExternalMessageInDittoProtocolIsProcessed() {
testExternalMessageInDittoProtocolIsProcessed(null, true);
}
@Test
public void testThingIdEnforcementExternalMessageInDittoProtocolIsProcessed() {
final Enforcement mqttEnforcement =
ConnectivityModelFactory.newEnforcement("{{ test:placeholder }}",
"mqtt/topic/{{ thing:namespace }}/{{ thing:name }}");
final EnforcementFilterFactory<String, String> factory =
EnforcementFactoryFactory.newEnforcementFilterFactory(mqttEnforcement, new TestPlaceholder());
final EnforcementFilter<String> enforcementFilter = factory.getFilter("mqtt/topic/my/thing");
testExternalMessageInDittoProtocolIsProcessed(enforcementFilter, true);
}
@Test
public void testThingIdEnforcementExternalMessageInDittoProtocolIsProcessedExpectErrorResponse() {
final Enforcement mqttEnforcement =
ConnectivityModelFactory.newEnforcement("{{ test:placeholder }}",
"mqtt/topic/{{ thing:namespace }}/{{ thing:name }}");
final EnforcementFilterFactory<String, String> factory =
EnforcementFactoryFactory.newEnforcementFilterFactory(mqttEnforcement, new TestPlaceholder());
final EnforcementFilter<String> enforcementFilter = factory.getFilter("some/invalid/target");
testExternalMessageInDittoProtocolIsProcessed(enforcementFilter, false);
}
private void testExternalMessageInDittoProtocolIsProcessed(@Nullable final EnforcementFilter<String> enforcement,
final boolean expectSuccess) {
new TestKit(actorSystem) {{
final ActorRef messageMappingProcessorActor = createMessageMappingProcessorActor(getRef());
final ModifyAttribute modifyCommand = createModifyAttributeCommand();
final ExternalMessage externalMessage =
ExternalMessageFactory.newExternalMessageBuilder(modifyCommand.getDittoHeaders())
.withText(ProtocolFactory
.wrapAsJsonifiableAdaptable(DITTO_PROTOCOL_ADAPTER.toAdaptable(modifyCommand))
.toJsonString())
.withAuthorizationContext(AUTHORIZATION_CONTEXT)
.withEnforcement(enforcement)
.build();
messageMappingProcessorActor.tell(externalMessage, getRef());
if (expectSuccess) {
final ModifyAttribute modifyAttribute = expectMsgClass(ModifyAttribute.class);
assertThat(modifyAttribute.getType()).isEqualTo(ModifyAttribute.TYPE);
assertThat(modifyAttribute.getDittoHeaders().getCorrelationId()).contains(
modifyCommand.getDittoHeaders().getCorrelationId().orElse(null));
assertThat(modifyAttribute.getDittoHeaders().getAuthorizationContext()).isEqualTo(
AUTHORIZATION_CONTEXT);
} else {
final OutboundSignal errorResponse = expectMsgClass(OutboundSignal.WithExternalMessage.class);
assertThat(errorResponse.getSource()).isInstanceOf(ThingErrorResponse.class);
final ThingErrorResponse response = (ThingErrorResponse) errorResponse.getSource();
assertThat(response.getDittoRuntimeException()).isInstanceOf(
ConnectionSignalIdEnforcementFailedException.class);
}
}};
}
@Test
public void testReplacementOfPlaceholders() {
final String correlationId = UUID.randomUUID().toString();
final AuthorizationContext contextWithPlaceholders = AuthorizationModelFactory.newAuthContext(
AuthorizationModelFactory.newAuthSubject(
"integration:{{header:correlation-id}}:hub-{{ header:content-type }}"),
AuthorizationModelFactory.newAuthSubject(
"integration:{{header:content-type}}:hub-{{ header:correlation-id }}"));
final AuthorizationContext expectedAuthContext = AuthorizationModelFactory.newAuthContext(
AuthorizationModelFactory.newAuthSubject("integration:" + correlationId + ":hub-application/json"),
AuthorizationModelFactory.newAuthSubject("integration:application/json:hub-" + correlationId));
testMessageMapping(correlationId, contextWithPlaceholders, ModifyAttribute.class, modifyAttribute -> {
assertThat(modifyAttribute.getType()).isEqualTo(ModifyAttribute.TYPE);
assertThat(modifyAttribute.getDittoHeaders().getCorrelationId()).contains(correlationId);
assertThat(modifyAttribute.getDittoHeaders().getAuthorizationContext()).isEqualTo(expectedAuthContext);
assertThat(modifyAttribute.getDittoHeaders().getSource()).contains(
"integration:" + correlationId + ":hub-application/json");
});
}
@Test
public void testUnknownPlaceholdersExpectUnresolvedPlaceholderException() {
final String placeholderKey = "header:unknown";
final String placeholder = "{{" + placeholderKey + "}}";
final AuthorizationContext contextWithUnknownPlaceholder = AuthorizationModelFactory.newAuthContext(
AuthorizationModelFactory.newAuthSubject("integration:" + placeholder));
testMessageMapping(UUID.randomUUID().toString(), contextWithUnknownPlaceholder,
OutboundSignal.WithExternalMessage.class, error -> {
final UnresolvedPlaceholderException exception = UnresolvedPlaceholderException.fromMessage(
error.getExternalMessage()
.getTextPayload()
.orElseThrow(() -> new IllegalArgumentException("payload was empty")),
DittoHeaders.of(error.getExternalMessage().getHeaders()));
assertThat(exception.getMessage()).contains(placeholderKey);
});
}
private <T> void testMessageMapping(final String correlationId, final AuthorizationContext context,
final Class<T> expectedMessageClass,
final Consumer<T> verifyReceivedMessage) {
new TestKit(actorSystem) {{
final ActorRef messageMappingProcessorActor = createMessageMappingProcessorActor(getRef());
final Map<String, String> headers = new HashMap<>();
headers.put("correlation-id", correlationId);
headers.put("content-type", "application/json");
final ModifyAttribute modifyCommand = ModifyAttribute.of("my:thing", JsonPointer.of("foo"),
JsonValue.of(42), DittoHeaders.empty());
final ExternalMessage externalMessage = ExternalMessageFactory.newExternalMessageBuilder(headers)
.withText(ProtocolFactory
.wrapAsJsonifiableAdaptable(DITTO_PROTOCOL_ADAPTER.toAdaptable(modifyCommand))
.toJsonString())
.withAuthorizationContext(context)
.build();
messageMappingProcessorActor.tell(externalMessage, getRef());
final T received = expectMsgClass(expectedMessageClass);
verifyReceivedMessage.accept(received);
}};
}
@Test
public void testCommandResponseIsProcessed() {
new TestKit(actorSystem) {{
final ActorRef messageMappingProcessorActor =
createMessageMappingProcessorActor(getRef());
final String correlationId = UUID.randomUUID().toString();
final ModifyAttributeResponse commandResponse =
ModifyAttributeResponse.modified("my:thing", JsonPointer.of("foo"),
DittoHeaders.newBuilder()
.correlationId(correlationId)
.build());
messageMappingProcessorActor.tell(commandResponse, getRef());
final OutboundSignal.WithExternalMessage outboundSignal =
expectMsgClass(OutboundSignal.WithExternalMessage.class);
assertThat(outboundSignal.getExternalMessage().findContentType())
.contains(DittoConstants.DITTO_PROTOCOL_CONTENT_TYPE);
assertThat(outboundSignal.getExternalMessage().getHeaders().get(CORRELATION_ID.getKey()))
.contains(correlationId);
}};
}
@Test
public void testCommandResponseWithResponseRequiredFalseIsNotProcessed() {
new TestKit(actorSystem) {
{
final ActorRef messageMappingProcessorActor =
createMessageMappingProcessorActor(getRef());
final ModifyAttributeResponse commandResponse =
ModifyAttributeResponse.modified("my:thing", JsonPointer.of("foo"),
DittoHeaders.newBuilder()
.responseRequired(false)
.build());
messageMappingProcessorActor.tell(commandResponse, getRef());
expectNoMessage();
}
};
}
private ActorRef createMessageMappingProcessorActor(final ActorRef publisherActor) {
final Props props = MessageMappingProcessorActor.props(
publisherActor,
publisherActor,
getMessageMappingProcessor(null),
CONNECTION_ID);
return actorSystem.actorOf(props);
}
private MessageMappingProcessor getMessageMappingProcessor(@Nullable final MappingContext mappingContext) {
return MessageMappingProcessor.of(CONNECTION_ID, mappingContext, actorSystem,
Mockito.mock(DiagnosticLoggingAdapter.class));
}
private ModifyAttribute createModifyAttributeCommand() {
final Map<String, String> headers = new HashMap<>();
final String correlationId = UUID.randomUUID().toString();
headers.put("correlation-id", correlationId);
headers.put("content-type", "application/json");
return ModifyAttribute.of("my:thing", JsonPointer.of("foo"), JsonValue.of(42), DittoHeaders.of(headers));
}
private static class TestPlaceholder implements Placeholder<String> {
@Override
public String getPrefix() {
return "test";
}
@Override
public List<String> getSupportedNames() {
return Collections.emptyList();
}
@Override
public boolean supports(final String name) {
return true;
}
@Override
public Optional<String> apply(final String source, final String name) {
return Optional.of(source);
}
}
}