/
CreateThingStrategy.java
208 lines (180 loc) · 8.83 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
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
/*
* 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.services.things.persistence.actors.strategies.commands;
import static org.eclipse.ditto.services.things.persistence.actors.strategies.commands.ResultFactory.newErrorResult;
import static org.eclipse.ditto.services.things.persistence.actors.strategies.commands.ResultFactory.newMutationResult;
import java.time.Instant;
import java.util.Objects;
import java.util.Optional;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.model.base.auth.AuthorizationContext;
import org.eclipse.ditto.model.base.auth.AuthorizationSubject;
import org.eclipse.ditto.model.base.common.Validator;
import org.eclipse.ditto.model.base.exceptions.DittoRuntimeException;
import org.eclipse.ditto.model.base.headers.DittoHeaders;
import org.eclipse.ditto.model.base.json.JsonSchemaVersion;
import org.eclipse.ditto.model.things.AccessControlList;
import org.eclipse.ditto.model.things.AclInvalidException;
import org.eclipse.ditto.model.things.AclNotAllowedException;
import org.eclipse.ditto.model.things.AclValidator;
import org.eclipse.ditto.model.things.PolicyIdMissingException;
import org.eclipse.ditto.model.things.Thing;
import org.eclipse.ditto.model.things.ThingBuilder;
import org.eclipse.ditto.model.things.ThingLifecycle;
import org.eclipse.ditto.model.things.ThingsModelFactory;
import org.eclipse.ditto.signals.commands.things.modify.CreateThing;
import org.eclipse.ditto.signals.commands.things.modify.CreateThingResponse;
import org.eclipse.ditto.signals.events.things.ThingCreated;
/**
* This strategy handles the {@link CreateThingStrategy} command.
*/
@Immutable
public final class CreateThingStrategy
extends AbstractConditionalHeadersCheckingCommandStrategy<CreateThing, Thing> {
private static final CreateThingStrategy INSTANCE = new CreateThingStrategy();
/**
* Constructs a new {@link CreateThingStrategy} object.
*/
private CreateThingStrategy() {
super(CreateThing.class);
}
public static CreateThingStrategy getInstance() {
return INSTANCE;
}
@Override
public boolean isDefined(final CreateThing command) {
return true;
}
@Override
public boolean isDefined(final Context 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.getThingId(), command.getId());
}
@Override
protected Result doApply(final Context context, @Nullable final Thing thing,
final long nextRevision, final CreateThing command) {
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);
}
// before persisting, check if the Thing is valid and reject if not:
final Result validateThingError =
validateThing(context, command.getImplementedSchemaVersion(), newThing, commandHeaders);
if (validateThingError != null) {
return validateThingError;
}
// for v2 upwards, set the policy-id to the thing-id if none is specified:
final boolean isV2Upwards = !JsonSchemaVersion.V_1.equals(command.getImplementedSchemaVersion());
if (isV2Upwards && !newThing.getPolicyId().isPresent()) {
newThing = newThing.setPolicyId(context.getThingId());
}
final Instant modified = Instant.now();
// provide modified and revision only in the response, not in the event (it is defined by the persistence)
final Thing newThingWithModifiedAndRevision = newThing.toBuilder()
.setModified(modified)
.setRevision(nextRevision)
.build();
final ThingCreated thingCreated = ThingCreated.of(newThing, nextRevision, modified, commandHeaders);
final CreateThingResponse createThingResponse =
CreateThingResponse.of(newThingWithModifiedAndRevision, commandHeaders);
return newMutationResult(command, thingCreated, createThingResponse, true, false, this);
}
private Thing handleCommandVersion(final Context context, final JsonSchemaVersion version, final Thing thing,
final DittoHeaders dittoHeaders) {
if (JsonSchemaVersion.V_1.equals(version)) {
return enhanceNewThingWithFallbackAcl(setLifecycleActive(thing),
dittoHeaders.getAuthorizationContext());
}
// default case handle as v2 and upwards:
else {
//acl is not allowed to be set in v2
if (thing.getAccessControlList().isPresent()) {
throw AclNotAllowedException.newBuilder(context.getThingId()).dittoHeaders(dittoHeaders).build();
}
// policyId is required for v2
if (!thing.getPolicyId().isPresent()) {
throw PolicyIdMissingException.fromThingIdOnCreate(context.getThingId(), 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();
}
/**
* Retrieves the Thing with first authorization subjects as fallback for the ACL of the Thing if the passed
* {@code newThing} has no ACL set.
*
* @param newThing the new Thing to take as a "base" and to check for presence of ACL inside.
* @param authContext the AuthorizationContext to take the first AuthorizationSubject as fallback from.
* @return the really new Thing with guaranteed ACL.
*/
private Thing enhanceNewThingWithFallbackAcl(final Thing newThing, final AuthorizationContext authContext) {
final ThingBuilder.FromCopy newThingBuilder = ThingsModelFactory.newThingBuilder(newThing);
final Boolean isAclEmpty = newThing.getAccessControlList()
.map(AccessControlList::isEmpty)
.orElse(true);
if (isAclEmpty) {
// do the fallback and use the first authorized subject and give all permissions to it:
final AuthorizationSubject authorizationSubject = authContext.getFirstAuthorizationSubject()
.orElseThrow(() -> new NullPointerException("AuthorizationContext does not contain an " +
"AuthorizationSubject!"));
newThingBuilder.setPermissions(authorizationSubject, Thing.MIN_REQUIRED_PERMISSIONS);
}
return newThingBuilder.build();
}
@Nullable
private Result validateThing(final Context context, final JsonSchemaVersion version, final Thing thing,
final DittoHeaders headers) {
final Optional<AccessControlList> accessControlList = thing.getAccessControlList();
if (JsonSchemaVersion.V_1.equals(version)) {
if (accessControlList.isPresent()) {
final Validator aclValidator =
AclValidator.newInstance(accessControlList.get(), Thing.MIN_REQUIRED_PERMISSIONS);
// before persisting, check if the ACL is valid and reject if not:
if (!aclValidator.isValid()) {
final AclInvalidException aclInvalidException =
AclInvalidException.newBuilder(context.getThingId())
.dittoHeaders(headers)
.build();
return newErrorResult(aclInvalidException);
}
} else {
final AclInvalidException aclInvalidException =
AclInvalidException.newBuilder(context.getThingId())
.dittoHeaders(headers)
.build();
return newErrorResult(aclInvalidException);
}
}
return null;
}
@Override
public Optional<Thing> determineETagEntity(final CreateThing command, @Nullable final Thing thing) {
return Optional.ofNullable(thing);
}
}