-
Notifications
You must be signed in to change notification settings - Fork 214
/
IfEqualPreconditionHeader.java
217 lines (194 loc) · 9.86 KB
/
IfEqualPreconditionHeader.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
/*
* Copyright (c) 2023 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.internal.utils.headers.conditional;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import java.util.Comparator;
import java.util.Optional;
import java.util.function.BooleanSupplier;
import java.util.function.Predicate;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.base.model.entity.Entity;
import org.eclipse.ditto.base.model.headers.DittoHeaderDefinition;
import org.eclipse.ditto.base.model.headers.IfEqual;
import org.eclipse.ditto.base.model.json.FieldType;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.base.model.signals.WithOptionalEntity;
import org.eclipse.ditto.base.model.signals.commands.Command;
import org.eclipse.ditto.json.JsonCollectors;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonField;
import org.eclipse.ditto.json.JsonKey;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonValue;
/**
* Custom Ditto {@code if-equal} precondition header supporting available strategies defined in {@link org.eclipse.ditto.base.model.headers.IfEqual}.
* The default is to always {@link IfEqual#UPDATE update} the entity, no matter if the update will lead to the
* same state. Another option is to {@link IfEqual#SKIP skip} updating an entity when it would be {@code equal}
* after the change.
*
* @param <C> the type of the handled {@link Command}.
* @since 3.3.0
*/
@Immutable
public final class IfEqualPreconditionHeader<C extends Command<?>> implements PreconditionHeader<Entity<?>> {
private static final String IF_EQUAL_KEY = DittoHeaderDefinition.IF_EQUAL.getKey();
private final C command;
private final IfEqual ifEqual;
private final ConditionalHeadersValidator.ValidationSettings validationSettings;
private IfEqualPreconditionHeader(final C command, final IfEqual ifEqual,
final ConditionalHeadersValidator.ValidationSettings validationSettings) {
this.command = checkNotNull(command, "command");
this.ifEqual = checkNotNull(ifEqual, "ifEqual");
this.validationSettings = checkNotNull(validationSettings, "validationSettings");
}
/**
* Extracts an {@link IfEqualPreconditionHeader} from the given {@code command} if present.
*
* @param command The command containing potentially the {@code if-equal} and the value to modify
* @param validationSettings the settings.
* @param <C> the type of the handled {@link Command}.
* @return Optional of {@link IfEqualPreconditionHeader}. Empty if the given {@code command} don't contain an
* {@code if-equal} or if it is not a modifying command.
*/
public static <C extends Command<?>> Optional<IfEqualPreconditionHeader<C>> fromDittoHeaders(
final C command,
final ConditionalHeadersValidator.ValidationSettings validationSettings) {
final Command.Category category = command.getCategory();
if (category == Command.Category.MODIFY || category == Command.Category.MERGE) {
return command.getDittoHeaders().getIfEqual()
.map(ifEqual -> new IfEqualPreconditionHeader<>(command, ifEqual, validationSettings));
} else {
return Optional.empty();
}
}
@Override
public String getKey() {
return IF_EQUAL_KEY;
}
@Override
public String getValue() {
return ifEqual.toString();
}
/**
* Indicates whether this {@link IfEqualPreconditionHeader} passes for the given {@code entity}.
* This means that the {@code command} field which is currently processed would not change the passed {@code entity},
* so the targeted desired state change indicated by the command is already present.
*
* @param entity The entity for which the equality condition should be met.
* @return True if the equality condition is met. False if not.
*/
@Override
public boolean meetsConditionFor(@Nullable final Entity<?> entity) {
if (entity == null) {
return false;
}
if (ifEqual == IfEqual.SKIP) {
if (command.getCategory() == Command.Category.MODIFY &&
command instanceof WithOptionalEntity withOptionalEntity) {
return meetsConditionForModifyCommand(entity, withOptionalEntity);
} else if (command.getCategory() == Command.Category.MERGE &&
command instanceof WithOptionalEntity withOptionalEntity) {
return meetsConditionForMergeCommand(entity, withOptionalEntity);
} else {
// other commands to "MODIFY" and "MERGE" do never match the "if-equal" precondition header
return false;
}
} else {
// for previous default behavior, "if-equal: update", don't match:
return false;
}
}
private Boolean meetsConditionForModifyCommand(final Entity<?> entity,
final WithOptionalEntity withOptionalEntity) {
return withOptionalEntity.getEntity()
.map(newValue -> {
final Predicate<JsonField> nonHiddenAndNamespace =
FieldType.notHidden()
.or(jsonField -> jsonField.getKey().equals(JsonKey.of("_namespace")));
final Optional<JsonValue> previousValue =
entity.toJson(JsonSchemaVersion.LATEST, nonHiddenAndNamespace)
.getValue(command.getResourcePath());
return previousValue.filter(jsonValue -> jsonValue.equals(newValue))
.isPresent();
})
.orElse(false);
}
private Boolean meetsConditionForMergeCommand(final Entity<?> entity, final WithOptionalEntity withOptionalEntity) {
return withOptionalEntity.getEntity()
.map(newValue -> {
final Optional<JsonValue> previousValue = entity.toJson().getValue(command.getResourcePath());
if (newValue.isObject()) {
final JsonObject newObject;
if (command.getResourcePath().isEmpty()) {
// filter "special fields" for e.g. on thing level the inline "_policy":
newObject = newValue.asObject()
.stream()
.filter(jsonField -> !jsonField.getKeyName().startsWith("_"))
.collect(JsonCollectors.fieldsToObject());
} else {
newObject = newValue.asObject();
}
return previousValue.filter(JsonValue::isObject)
.map(JsonValue::asObject)
.filter(previousObject -> {
final JsonObject patchedAndSortedNewObject =
JsonFactory.mergeJsonValues(newObject, previousObject)
.asObject().stream()
.sorted(Comparator.comparing(j -> j.getKey().toString()))
.collect(JsonCollectors.fieldsToObject());
final JsonObject sortedOldObject = previousObject.stream()
.sorted(Comparator.comparing(j -> j.getKey().toString()))
.collect(JsonCollectors.fieldsToObject());
return patchedAndSortedNewObject.equals(sortedOldObject);
}).isPresent();
} else {
return previousValue.filter(jsonValue -> jsonValue.equals(newValue))
.isPresent();
}
})
.orElse(false);
}
/**
* Handles the {@link #command} field of this class by invoking the passed {@code isCompletelyEqualSupplier} to
* check whether the affected entity would be completely equal after applying the {@link #command}.
*
* @return the potentially adjusted Command.
*/
C handleCommand(final BooleanSupplier isCompletelyEqualSupplier) {
final C potentiallyAdjustedCommand;
if (ifEqual == IfEqual.UPDATE) {
// default behavior - no change, just use the complete modify command, not matter what:
potentiallyAdjustedCommand = command;
} else if (ifEqual == IfEqual.SKIP) {
// lazily check for equality as this might be expensive to do:
final boolean completelyEqual = isCompletelyEqualSupplier.getAsBoolean();
final Command.Category category = command.getCategory();
if (completelyEqual &&
(category == Command.Category.MODIFY || category == Command.Category.MERGE)) {
potentiallyAdjustedCommand = respondWithPreconditionFailed();
} else {
potentiallyAdjustedCommand = command;
}
} else {
potentiallyAdjustedCommand = command;
}
return potentiallyAdjustedCommand;
}
private C respondWithPreconditionFailed() {
throw validationSettings
.createPreconditionFailedForEqualityExceptionBuilder()
.dittoHeaders(command.getDittoHeaders())
.build();
}
}