-
Notifications
You must be signed in to change notification settings - Fork 214
/
CreateThingStrategy.java
176 lines (149 loc) · 7.05 KB
/
CreateThingStrategy.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
/*
* Copyright (c) 2017 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.things.service.persistence.actors.strategies.commands;
import static org.eclipse.ditto.internal.utils.persistentactors.results.ResultFactory.newErrorResult;
import static org.eclipse.ditto.internal.utils.persistentactors.results.ResultFactory.newMutationResult;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletionStage;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.base.model.entity.metadata.Metadata;
import org.eclipse.ditto.base.model.exceptions.DittoRuntimeException;
import org.eclipse.ditto.base.model.headers.DittoHeaders;
import org.eclipse.ditto.base.model.headers.WithDittoHeaders;
import org.eclipse.ditto.base.model.headers.entitytag.EntityTag;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.internal.utils.persistentactors.results.Result;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonValue;
import org.eclipse.ditto.policies.model.PolicyId;
import org.eclipse.ditto.things.model.PolicyIdMissingException;
import org.eclipse.ditto.things.model.Thing;
import org.eclipse.ditto.things.model.ThingId;
import org.eclipse.ditto.things.model.ThingLifecycle;
import org.eclipse.ditto.things.model.ThingsModelFactory;
import org.eclipse.ditto.things.model.signals.commands.modify.CreateThing;
import org.eclipse.ditto.things.model.signals.commands.modify.CreateThingResponse;
import org.eclipse.ditto.things.model.signals.events.ThingCreated;
import org.eclipse.ditto.things.model.signals.events.ThingEvent;
import org.eclipse.ditto.wot.integration.provider.WotThingDescriptionProvider;
import akka.actor.ActorSystem;
/**
* This strategy handles the {@link CreateThingStrategy} command.
*/
@Immutable
final class CreateThingStrategy extends AbstractThingCommandStrategy<CreateThing> {
private final WotThingDescriptionProvider wotThingDescriptionProvider;
/**
* Constructs a new {@link CreateThingStrategy} object.
*
* @param actorSystem the actor system to use for loading the WoT extension.
*/
CreateThingStrategy(final ActorSystem actorSystem) {
super(CreateThing.class);
wotThingDescriptionProvider = WotThingDescriptionProvider.get(actorSystem);
}
@Override
protected Optional<Metadata> calculateRelativeMetadata(@Nullable Thing entity, CreateThing command) {
return super.calculateRelativeMetadata(command.getThing(), command);
}
@Override
public boolean isDefined(final CreateThing command) {
return true;
}
@Override
public boolean isDefined(final Context<ThingId> context, @Nullable final Thing thing, final CreateThing command) {
final boolean thingExists = Optional.ofNullable(thing)
.map(t -> !t.isDeleted())
.orElse(false);
return !thingExists && Objects.equals(context.getState(), command.getEntityId());
}
@Override
protected Result<ThingEvent<?>> doApply(final Context<ThingId> context,
@Nullable final Thing thing,
final long nextRevision,
final CreateThing command,
@Nullable final Metadata metadata) {
final DittoHeaders commandHeaders = command.getDittoHeaders();
// Thing not yet created - do so ..
Thing newThing;
try {
newThing =
handleCommandVersion(context, command.getImplementedSchemaVersion(), command.getThing(),
commandHeaders);
} catch (final DittoRuntimeException e) {
return newErrorResult(e, command);
}
// for v2 upwards, set the policy-id to the thing-id if none is specified:
if (newThing.getPolicyId().isEmpty()) {
newThing = newThing.setPolicyId(PolicyId.of(context.getState()));
}
final Instant now = Instant.now();
final Thing finalNewThing = newThing;
final CompletionStage<Thing> thingStage = wotThingDescriptionProvider.provideThingSkeletonForCreation(
command.getEntityId(),
newThing.getDefinition().orElse(null),
commandHeaders
)
.thenApply(opt -> opt.map(wotBasedThingSkeleton ->
JsonFactory.mergeJsonValues(finalNewThing.toJson(), wotBasedThingSkeleton.toJson())
)
.filter(JsonValue::isObject)
.map(JsonValue::asObject)
.map(ThingsModelFactory::newThing)
.orElse(finalNewThing)
).thenApply(enhancedThing -> enhancedThing.toBuilder()
.setModified(now)
.setCreated(now)
.setRevision(nextRevision)
.setMetadata(metadata)
.build()
);
final CompletionStage<ThingEvent<?>> eventStage =
thingStage.thenApply(newThingWithImplicits ->
ThingCreated.of(newThingWithImplicits, nextRevision, now, commandHeaders, metadata)
);
final CompletionStage<WithDittoHeaders> responseStage = thingStage.thenApply(newThingWithImplicits ->
appendETagHeaderIfProvided(command, CreateThingResponse.of(newThingWithImplicits, commandHeaders),
newThingWithImplicits)
);
return newMutationResult(command, eventStage, responseStage, true, false);
}
private Thing handleCommandVersion(final Context<ThingId> context, final JsonSchemaVersion version,
final Thing thing,
final DittoHeaders dittoHeaders) {
// policyId is required for v2
if (thing.getPolicyId().isEmpty()) {
throw PolicyIdMissingException.fromThingIdOnCreate(context.getState(), dittoHeaders);
}
return setLifecycleActive(thing);
}
private static Thing setLifecycleActive(final Thing thing) {
if (ThingLifecycle.ACTIVE.equals(thing.getLifecycle().orElse(null))) {
return thing;
}
return ThingsModelFactory.newThingBuilder(thing)
.setLifecycle(ThingLifecycle.ACTIVE)
.build();
}
@Override
public Optional<EntityTag> previousEntityTag(final CreateThing command, @Nullable final Thing previousEntity) {
return Optional.empty();
}
@Override
public Optional<EntityTag> nextEntityTag(final CreateThing command, @Nullable final Thing newEntity) {
return Optional.ofNullable(newEntity).flatMap(EntityTag::fromEntity);
}
}