-
Notifications
You must be signed in to change notification settings - Fork 214
/
DefaultWotThingDescriptionProvider.java
310 lines (281 loc) · 14.3 KB
/
DefaultWotThingDescriptionProvider.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
302
303
304
305
306
307
308
309
310
/*
* 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.wot.integration.provider;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import java.net.URL;
import java.time.Duration;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.signals.FeatureToggle;
import org.eclipse.ditto.internal.utils.akka.logging.DittoLoggerFactory;
import org.eclipse.ditto.internal.utils.akka.logging.ThreadSafeDittoLogger;
import org.eclipse.ditto.internal.utils.config.DefaultScopedConfig;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.things.model.DefinitionIdentifier;
import org.eclipse.ditto.things.model.Feature;
import org.eclipse.ditto.things.model.FeatureDefinition;
import org.eclipse.ditto.things.model.Thing;
import org.eclipse.ditto.things.model.ThingDefinition;
import org.eclipse.ditto.things.model.ThingId;
import org.eclipse.ditto.wot.integration.config.DefaultWotConfig;
import org.eclipse.ditto.wot.integration.config.WotConfig;
import org.eclipse.ditto.wot.integration.generator.WotThingDescriptionGenerator;
import org.eclipse.ditto.wot.integration.generator.WotThingSkeletonGenerator;
import org.eclipse.ditto.wot.model.ThingDefinitionInvalidException;
import org.eclipse.ditto.wot.model.ThingDescription;
import org.eclipse.ditto.wot.model.WotInternalErrorException;
import akka.actor.AbstractExtensionId;
import akka.actor.ActorSystem;
import akka.actor.ExtendedActorSystem;
/**
* Default Ditto specific implementation of {@link WotThingDescriptionProvider}.
*/
@Immutable
final class DefaultWotThingDescriptionProvider implements WotThingDescriptionProvider {
private static final ThreadSafeDittoLogger LOGGER =
DittoLoggerFactory.getThreadSafeLogger(DefaultWotThingDescriptionProvider.class);
public static final String MODEL_PLACEHOLDERS_KEY = "model-placeholders";
private static final Duration MAX_JOIN_WAIT_DURATION = Duration.ofSeconds(20);
private final WotConfig wotConfig;
private final WotThingModelFetcher thingModelFetcher;
private final WotThingDescriptionGenerator thingDescriptionGenerator;
private final WotThingSkeletonGenerator thingSkeletonGenerator;
private final Executor executor;
private DefaultWotThingDescriptionProvider(final ActorSystem actorSystem, final WotConfig wotConfig) {
this.wotConfig = checkNotNull(wotConfig, "wotConfig");
thingModelFetcher = new DefaultWotThingModelFetcher(actorSystem, wotConfig);
thingDescriptionGenerator = WotThingDescriptionGenerator.of(actorSystem, wotConfig, thingModelFetcher);
thingSkeletonGenerator = WotThingSkeletonGenerator.of(actorSystem, thingModelFetcher);
executor = actorSystem.dispatchers().lookup("wot-dispatcher");
}
/**
* Returns a new {@code DefaultWotThingDescriptionProvider} for the given parameters.
*
* @param actorSystem the actor system to use.
* @param wotConfig the WoT config to use.
* @return the DefaultWotThingDescriptionProvider.
* @throws NullPointerException if any argument is {@code null}.
*/
public static DefaultWotThingDescriptionProvider of(final ActorSystem actorSystem, final WotConfig wotConfig) {
return new DefaultWotThingDescriptionProvider(actorSystem, wotConfig);
}
@Override
public ThingDescription provideThingTD(@Nullable final ThingDefinition thingDefinition,
final ThingId thingId,
@Nullable final Thing thing,
final DittoHeaders dittoHeaders) {
if (null != thingDefinition) {
return getWotThingDescriptionForThing(thingDefinition, thingId, thing, dittoHeaders);
} else {
throw ThingDefinitionInvalidException.newBuilder(null)
.dittoHeaders(dittoHeaders)
.build();
}
}
@Override
public ThingDescription provideFeatureTD(final ThingId thingId,
@Nullable final Thing thing,
final Feature feature,
final DittoHeaders dittoHeaders) {
checkNotNull(feature, "feature");
if (feature.getDefinition().isPresent()) {
return getWotThingDescriptionForFeature(thingId, thing, feature, dittoHeaders);
} else {
throw ThingDefinitionInvalidException.newBuilder(null)
.dittoHeaders(dittoHeaders)
.build();
}
}
@Override
public CompletionStage<Optional<Thing>> provideThingSkeletonForCreation(final ThingId thingId,
@Nullable final ThingDefinition thingDefinition,
final DittoHeaders dittoHeaders) {
final ThreadSafeDittoLogger logger = LOGGER.withCorrelationId(dittoHeaders);
if (FeatureToggle.isWotIntegrationFeatureEnabled() &&
wotConfig.getCreationConfig().isThingSkeletonCreationEnabled() &&
null != thingDefinition) {
final Optional<URL> urlOpt = thingDefinition.getUrl();
if (urlOpt.isPresent()) {
final URL url = urlOpt.get();
try {
logger.debug("Fetching ThingModel from <{}> in order to create Thing skeleton for new Thing " +
"with id <{}>", url, thingId);
return thingModelFetcher.fetchThingModel(url, dittoHeaders)
.thenApplyAsync(thingModel -> thingSkeletonGenerator
.generateThingSkeleton(thingId, thingModel, url, dittoHeaders),
executor
)
.thenApply(thingSkeleton -> {
logger.debug("Created Thing skeleton for new Thing with id <{}>: <{}>", thingId,
thingSkeleton);
return thingSkeleton;
});
} catch (final DittoRuntimeException | CompletionException e) {
logger.info("Could not fetch ThingModel or generate Feature skeleton based on it due to: <{}: {}>",
e.getClass().getSimpleName(), e.getMessage(), e);
return CompletableFuture.completedStage(Optional.empty());
}
} else {
return CompletableFuture.completedStage(Optional.empty());
}
} else {
return CompletableFuture.completedStage(Optional.empty());
}
}
@Override
public CompletionStage<Optional<Feature>> provideFeatureSkeletonForCreation(final String featureId,
@Nullable final FeatureDefinition featureDefinition, final DittoHeaders dittoHeaders) {
final ThreadSafeDittoLogger logger = LOGGER.withCorrelationId(dittoHeaders);
if (FeatureToggle.isWotIntegrationFeatureEnabled() &&
wotConfig.getCreationConfig().isFeatureSkeletonCreationEnabled() &&
null != featureDefinition) {
final Optional<URL> urlOpt = featureDefinition.getFirstIdentifier().getUrl();
if (urlOpt.isPresent()) {
final URL url = urlOpt.get();
try {
logger.debug("Fetching ThingModel from <{}> in order to create Feature skeleton for new Feature " +
"with id <{}>", url, featureId);
return thingModelFetcher.fetchThingModel(url, dittoHeaders)
.thenApplyAsync(thingModel -> thingSkeletonGenerator
.generateFeatureSkeleton(featureId, thingModel, url, dittoHeaders),
executor
)
.thenApply(featureSkeleton -> {
logger.debug("Created Feature skeleton for new Feature with id <{}>: <{}>", featureId,
featureSkeleton);
return featureSkeleton;
});
} catch (final DittoRuntimeException | CompletionException e) {
logger.info("Could not fetch ThingModel or generate Feature skeleton based on it due to: <{}: {}>",
e.getClass().getSimpleName(), e.getMessage(), e);
return CompletableFuture.completedStage(Optional.empty());
}
} else {
return CompletableFuture.completedStage(Optional.empty());
}
} else {
return CompletableFuture.completedStage(Optional.empty());
}
}
/**
* Download TM, add it to local cache + build TD + return it
*/
private ThingDescription getWotThingDescriptionForThing(final ThingDefinition definitionIdentifier,
final ThingId thingId,
@Nullable final Thing thing,
final DittoHeaders dittoHeaders) {
final Optional<URL> urlOpt = definitionIdentifier.getUrl();
if (urlOpt.isPresent()) {
final URL url = urlOpt.get();
try {
return thingModelFetcher.fetchThingModel(url, dittoHeaders)
.thenApplyAsync(thingModel -> thingDescriptionGenerator
.generateThingDescription(thingId,
thing,
Optional.ofNullable(thing)
.flatMap(Thing::getAttributes)
.flatMap(a -> a.getValue(MODEL_PLACEHOLDERS_KEY))
.filter(JsonValue::isObject)
.map(JsonValue::asObject)
.orElse(null),
null,
thingModel,
url,
dittoHeaders
),
executor
)
.toCompletableFuture()
.orTimeout(MAX_JOIN_WAIT_DURATION.toSeconds(), TimeUnit.SECONDS)
.join();
} catch (final Exception e) {
throw DittoRuntimeException.asDittoRuntimeException(e, throwable ->
WotInternalErrorException.newBuilder()
.dittoHeaders(dittoHeaders)
.cause(e)
.build()
);
}
} else {
throw ThingDefinitionInvalidException.newBuilder(definitionIdentifier)
.dittoHeaders(dittoHeaders)
.build();
}
}
/**
* Download TM, add it to local cache + build TD + return it
*/
private ThingDescription getWotThingDescriptionForFeature(final ThingId thingId,
@Nullable final Thing thing,
final Feature feature,
final DittoHeaders dittoHeaders) {
final Optional<DefinitionIdentifier> definitionIdentifier = feature.getDefinition()
.map(FeatureDefinition::getFirstIdentifier);
final Optional<URL> urlOpt = definitionIdentifier.flatMap(DefinitionIdentifier::getUrl);
if (urlOpt.isPresent()) {
final URL url = urlOpt.get();
try {
return thingModelFetcher.fetchThingModel(url, dittoHeaders)
.thenApplyAsync(thingModel -> thingDescriptionGenerator
.generateThingDescription(thingId,
thing,
feature.getProperties()
.flatMap(p -> p.getValue(MODEL_PLACEHOLDERS_KEY))
.filter(JsonValue::isObject)
.map(JsonValue::asObject)
.orElse(null),
feature.getId(),
thingModel,
url,
dittoHeaders
),
executor
)
.toCompletableFuture()
.orTimeout(MAX_JOIN_WAIT_DURATION.toSeconds(), TimeUnit.SECONDS)
.join();
} catch (final Exception e) {
throw DittoRuntimeException.asDittoRuntimeException(e, throwable ->
WotInternalErrorException.newBuilder()
.dittoHeaders(dittoHeaders)
.cause(e)
.build()
);
}
} else {
throw ThingDefinitionInvalidException.newBuilder(definitionIdentifier.orElse(null))
.dittoHeaders(dittoHeaders)
.build();
}
}
static final class ExtensionId extends AbstractExtensionId<WotThingDescriptionProvider> {
private static final String WOT_PARENT_CONFIG_PATH = "things";
static final ExtensionId INSTANCE = new ExtensionId();
private ExtensionId() {}
@Override
public WotThingDescriptionProvider createExtension(final ExtendedActorSystem system) {
final WotConfig wotConfig = DefaultWotConfig.of(
DefaultScopedConfig.dittoScoped(system.settings().config()).getConfig(WOT_PARENT_CONFIG_PATH)
);
return of(system, wotConfig);
}
}
}