-
Notifications
You must be signed in to change notification settings - Fork 215
/
ImmutablePolicy.java
executable file
·611 lines (516 loc) · 23.8 KB
/
ImmutablePolicy.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
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
/*
* 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.policies.model;
import static org.eclipse.ditto.base.model.common.ConditionChecker.checkNotNull;
import static org.eclipse.ditto.policies.model.PoliciesModelFactory.emptyResources;
import static org.eclipse.ditto.policies.model.PoliciesModelFactory.newPolicyEntry;
import static org.eclipse.ditto.policies.model.PoliciesModelFactory.newResources;
import java.text.MessageFormat;
import java.time.Instant;
import java.time.format.DateTimeParseException;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
import org.eclipse.ditto.base.model.entity.metadata.Metadata;
import org.eclipse.ditto.base.model.entity.metadata.MetadataModelFactory;
import org.eclipse.ditto.base.model.exceptions.DittoJsonException;
import org.eclipse.ditto.base.model.json.FieldType;
import org.eclipse.ditto.base.model.json.JsonSchemaVersion;
import org.eclipse.ditto.json.JsonCollectors;
import org.eclipse.ditto.json.JsonFactory;
import org.eclipse.ditto.json.JsonField;
import org.eclipse.ditto.json.JsonObject;
import org.eclipse.ditto.json.JsonObjectBuilder;
import org.eclipse.ditto.json.JsonParseException;
import org.eclipse.ditto.json.JsonValue;
/**
* Immutable implementation of {@link Policy}.
*/
@Immutable
final class ImmutablePolicy implements Policy {
@Nullable private final PolicyId policyId;
@Nullable private final PolicyImports imports;
private final Map<Label, PolicyEntry> entries;
@Nullable private final String namespace;
@Nullable private final PolicyLifecycle lifecycle;
@Nullable private final PolicyRevision revision;
@Nullable private final Instant modified;
@Nullable private final Instant created;
@Nullable private final Metadata metadata;
private ImmutablePolicy(@Nullable final PolicyId policyId,
@Nullable final PolicyImports theImports,
final Map<Label, PolicyEntry> theEntries,
@Nullable final PolicyLifecycle lifecycle,
@Nullable final PolicyRevision revision,
@Nullable final Instant modified,
@Nullable final Instant created,
@Nullable final Metadata metadata) {
this.policyId = policyId;
imports = theImports;
entries = Collections.unmodifiableMap(new LinkedHashMap<>(theEntries));
namespace = policyId == null ? null : policyId.getNamespace();
this.lifecycle = lifecycle;
this.revision = revision;
this.modified = modified;
this.created = created;
this.metadata = metadata;
}
/**
* Returns a new Policy which is initialised with the specified entries.
*
* @param policyId the ID of the new Policy.
* @param lifecycle the lifecycle of the Policy to be created.
* @param revision the revision of the Policy to be created.
* @param modified the modified timestamp of the Policy to be created.
* @param created the created timestamp of the Policy to be created.
* @param metadata the metadata of the Thing to be created.
* @param imports the PolicyImports of the Policy to be created.
* @param entries the entries of the Policy to be created.
* @return a new initialised Policy.
* @throws NullPointerException if {@code entries} is {@code null}.
*/
public static Policy of(@Nullable final PolicyId policyId,
@Nullable final PolicyLifecycle lifecycle,
@Nullable final PolicyRevision revision,
@Nullable final Instant modified,
@Nullable final Instant created,
@Nullable final Metadata metadata,
@Nullable final PolicyImports imports,
final Iterable<PolicyEntry> entries) {
checkNotNull(entries, "Policy entries");
final Map<Label, PolicyEntry> entryMap = new LinkedHashMap<>();
entries.forEach(policyEntry -> entryMap.put(policyEntry.getLabel(), policyEntry));
return new ImmutablePolicy(policyId, imports, entryMap, lifecycle, revision, modified, created, metadata);
}
/**
* Creates a new {@code Policy} object from the specified JSON object.
*
* @param jsonObject a JSON object which provides the data for the Policy to be created.
* @return a new Policy which is initialised with the extracted data from {@code jsonObject}.
* @throws NullPointerException if {@code jsonObject} is {@code null}.
* @throws PolicyEntryInvalidException if an Policy entry does not contain any known permission which evaluates to
* {@code true} or {@code false}.
* @throws PolicyIdInvalidException if the parsed policy ID did not comply to
* {@link org.eclipse.ditto.base.model.entity.id.RegexPatterns#ID_REGEX}.
*/
public static Policy fromJson(final JsonObject jsonObject) {
final PolicyId policyId = jsonObject.getValue(JsonFields.ID).map(PolicyId::of).orElse(null);
final PolicyLifecycle readLifecycle = jsonObject.getValue(JsonFields.LIFECYCLE)
.flatMap(PolicyLifecycle::forName)
.orElse(null);
final PolicyRevision readRevision = jsonObject.getValue(JsonFields.REVISION)
.map(PolicyRevision::newInstance)
.orElse(null);
final Instant readModified = jsonObject.getValue(JsonFields.MODIFIED)
.map(ImmutablePolicy::tryToParseModified)
.orElse(null);
final PolicyImports readImports = jsonObject.getValue(JsonFields.IMPORTS)
.map(PoliciesModelFactory::newPolicyImports)
.orElse(null);
final Instant readCreated = jsonObject.getValue(JsonFields.CREATED)
.map(ImmutablePolicy::tryToParseModified)
.orElse(null);
final JsonObject readEntries = jsonObject.getValue(JsonFields.ENTRIES).orElseGet(JsonObject::empty);
final Function<JsonField, PolicyEntry> toPolicyEntry = jsonField -> {
final JsonValue jsonValue = jsonField.getValue();
if (!jsonValue.isObject()) {
throw new DittoJsonException(JsonParseException.newBuilder()
.message(MessageFormat.format("<{0}> is not a JSON object!", jsonValue))
.build());
}
return ImmutablePolicyEntry.fromJson(jsonField.getKey(), jsonValue.asObject());
};
final Collection<PolicyEntry> policyEntries = readEntries.stream()
.filter(jsonField -> !Objects.equals(jsonField.getKey(), JsonSchemaVersion.getJsonKey()))
.map(toPolicyEntry)
.collect(Collectors.toCollection(LinkedHashSet::new));
final Metadata readMetadata = jsonObject.getValue(JsonFields.METADATA)
.map(MetadataModelFactory::newMetadata)
.orElse(null);
return of(policyId, readLifecycle, readRevision, readModified, readCreated, readMetadata, readImports,
policyEntries);
}
private static Instant tryToParseModified(final CharSequence dateTime) {
try {
return Instant.parse(dateTime);
} catch (final DateTimeParseException e) {
throw new JsonParseException("The JSON object's field '" + JsonFields.MODIFIED.getPointer() + "' " +
"is not in ISO-8601 format as expected");
}
}
@Override
public Optional<PolicyId> getEntityId() {
return Optional.ofNullable(policyId);
}
@Override
public Optional<String> getNamespace() {
return Optional.ofNullable(namespace);
}
@Override
public Optional<PolicyLifecycle> getLifecycle() {
return Optional.ofNullable(lifecycle);
}
@Override
public Optional<PolicyRevision> getRevision() {
return Optional.ofNullable(revision);
}
@Override
public Optional<Instant> getModified() {
return Optional.ofNullable(modified);
}
@Override
public Optional<Instant> getCreated() {
return Optional.ofNullable(created);
}
@Override
public Optional<Metadata> getMetadata() {
return Optional.ofNullable(metadata);
}
@Override
public boolean isDeleted() {
return PolicyLifecycle.DELETED.equals(lifecycle);
}
@Override
public Policy setEntry(final PolicyEntry policyEntry) {
checkNotNull(policyEntry, "entry to be set to this Policy");
final Policy result;
final PolicyEntry existingPolicyEntry = entries.get(policyEntry.getLabel());
if (null != existingPolicyEntry) {
if (existingPolicyEntry.equals(policyEntry)) {
result = this;
} else {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.put(policyEntry.getLabel(), policyEntry);
result = new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created,
metadata);
}
} else {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.put(policyEntry.getLabel(), policyEntry);
result = new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created,
metadata);
}
return result;
}
@Override
public Set<Label> getLabels() {
return entries.keySet();
}
@Override
public boolean contains(final CharSequence label) {
return entries.containsKey(Label.of(label));
}
@Override
public Optional<PolicyEntry> getEntryFor(final CharSequence label) {
return Optional.ofNullable(entries.get(Label.of(label)));
}
@Override
public Policy removeEntry(final CharSequence label) {
final Label lbl = Label.of(label);
if (!entries.containsKey(lbl)) {
return this;
}
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.remove(lbl);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Policy removeEntries(final Iterable<CharSequence> labels) {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
StreamSupport.stream(labels.spliterator(), false)
.map(Label::of)
.forEach(entriesCopy::remove);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Policy removeEntry(final PolicyEntry entry) {
checkNotNull(entry, "Policy entry to be removed");
return removeEntry(entry.getLabel());
}
@Override
public Policy setSubjectsFor(final CharSequence label, final Subjects subjects) {
final Label lbl = Label.of(label);
checkNotNull(subjects, "subjects to set to the Policy entry");
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
final PolicyEntry modifiedEntry;
if (!entriesCopy.containsKey(lbl)) {
modifiedEntry = newPolicyEntry(lbl, subjects, emptyResources());
} else {
final PolicyEntry policyEntry = entriesCopy.get(lbl);
modifiedEntry = newPolicyEntry(lbl, subjects, policyEntry.getResources(), policyEntry.getImportableType());
}
entriesCopy.put(lbl, modifiedEntry);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Policy setSubjectFor(final CharSequence label, final Subject subject) {
final Label lbl = Label.of(label);
checkNotNull(subject, "subject to set to the Policy entry");
final Policy result;
final PolicyEntry existingPolicyEntry = entries.get(lbl);
if (null != existingPolicyEntry) {
final Subjects existingSubjects = existingPolicyEntry.getSubjects();
final Subjects newSubjects = existingSubjects.setSubject(subject);
if (!Objects.equals(existingSubjects, newSubjects)) {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.put(lbl, newPolicyEntry(lbl, newSubjects, existingPolicyEntry.getResources()));
result = new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created,
metadata);
} else {
result = this;
}
} else {
result = setSubjectsFor(label, Subjects.newInstance(subject));
}
return result;
}
@Override
public Policy removeSubjectFor(final CharSequence label, final SubjectId subjectId) {
final Label lbl = Label.of(label);
Policy result = this;
final PolicyEntry existingPolicyEntry = entries.get(lbl);
if (null != existingPolicyEntry) {
final Subjects existingSubjects = existingPolicyEntry.getSubjects();
final Subjects newSubjects = existingSubjects.removeSubject(subjectId);
if (!Objects.equals(existingSubjects, newSubjects)) {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.put(lbl, newPolicyEntry(lbl, newSubjects, existingPolicyEntry.getResources()));
result = new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created,
metadata);
}
}
return result;
}
@Override
public Policy setResourcesFor(final CharSequence label, final Resources resources) {
final Label lbl = Label.of(label);
checkNotNull(resources, "resources to set to the Policy entry");
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
final PolicyEntry policyEntry = entriesCopy.get(lbl);
final PolicyEntry modifiedEntry;
if (null == policyEntry) {
modifiedEntry = newPolicyEntry(lbl, PoliciesModelFactory.emptySubjects(), resources);
} else {
modifiedEntry = newPolicyEntry(lbl, policyEntry.getSubjects(), resources,
policyEntry.getImportableType());
}
entriesCopy.put(lbl, modifiedEntry);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Policy setResourceFor(final CharSequence label, final Resource resource) {
final Label lbl = Label.of(label);
checkNotNull(resource, "resource to set to the Policy entry");
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
final PolicyEntry modifiedEntry;
if (!entriesCopy.containsKey(lbl)) {
modifiedEntry = newPolicyEntry(label, PoliciesModelFactory.emptySubjects(), newResources(resource));
} else {
final PolicyEntry policyEntry = entriesCopy.get(lbl);
final Resources modifiedResources = policyEntry.getResources().setResource(resource);
modifiedEntry = newPolicyEntry(label, policyEntry.getSubjects(), modifiedResources,
policyEntry.getImportableType());
}
entriesCopy.put(lbl, modifiedEntry);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Policy removeResourceFor(final CharSequence label, final ResourceKey resourceKey) {
final Label lbl = Label.of(label);
Policy result = this;
final PolicyEntry existingEntry = entries.get(lbl);
if (null != existingEntry) {
final Resources existingResources = existingEntry.getResources();
final Resources newResources = existingResources.removeResource(resourceKey);
if (!Objects.equals(existingResources, newResources)) {
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
entriesCopy.put(lbl, newPolicyEntry(lbl, existingEntry.getSubjects(), newResources));
result = new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created,
metadata);
}
}
return result;
}
@Override
public Policy setImportableFor(final CharSequence label, final ImportableType importableType) {
final Label lbl = Label.of(label);
final Map<Label, PolicyEntry> entriesCopy = copyEntries();
final PolicyEntry modifiedEntry;
if (!entriesCopy.containsKey(lbl)) {
modifiedEntry =
newPolicyEntry(label, PoliciesModelFactory.emptySubjects(), emptyResources(), importableType);
} else {
final PolicyEntry policyEntry = entriesCopy.get(lbl);
modifiedEntry = newPolicyEntry(label, policyEntry.getSubjects(),
policyEntry.getResources(), importableType);
}
entriesCopy.put(lbl, modifiedEntry);
return new ImmutablePolicy(policyId, imports, entriesCopy, lifecycle, revision, modified, created, metadata);
}
@Override
public Optional<EffectedPermissions> getEffectedPermissionsFor(final CharSequence label, final SubjectId subjectId,
final ResourceKey resourceKey) {
final Label lbl = Label.of(label);
Optional<EffectedPermissions> result = Optional.empty();
final PolicyEntry policyEntry = entries.get(lbl);
if (null != policyEntry) {
final Subjects subjects = policyEntry.getSubjects();
final Optional<Subject> subjectOptional = subjects.getSubject(subjectId);
if (subjectOptional.isPresent()) {
final Resources resources = policyEntry.getResources();
result = resources.getResource(resourceKey).map(Resource::getEffectedPermissions);
}
}
return result;
}
@Override
public boolean isEmpty() {
return entries.isEmpty();
}
@Override
public int getSize() {
return entries.size();
}
@Override
public Optional<PolicyImports> getPolicyImports() {
return Optional.ofNullable(imports);
}
@Override
public Set<PolicyEntry> getEntriesSet() {
return stream().collect(Collectors.toCollection(LinkedHashSet::new));
}
@Override
public Stream<PolicyEntry> stream() {
return entries.values().stream();
}
@Override
public boolean isSemanticallySameAs(final Collection<PolicyEntry> otherPolicyEntries) {
// sorting via the policy entry label is required in order to not depend on the order:
final Iterator<PolicyEntry> others = otherPolicyEntries.stream()
.sorted(Comparator.comparing(e -> e.getLabel().toString()))
.collect(Collectors.toCollection(LinkedHashSet::new))
.iterator();
final Iterator<PolicyEntry> owns = entries.values()
.stream()
.sorted(Comparator.comparing(e -> e.getLabel().toString()))
.collect(Collectors.toCollection(LinkedHashSet::new))
.iterator();
boolean semanticallyTheSame = true;
while (others.hasNext() && owns.hasNext()) {
semanticallyTheSame &= others.next().isSemanticallySameAs(owns.next());
}
semanticallyTheSame &= !others.hasNext() && !owns.hasNext();
return semanticallyTheSame;
}
@Override
public boolean isSemanticallySameAs(final Policy otherPolicy) {
return getPolicyImports().equals(otherPolicy.getPolicyImports()) &&
isSemanticallySameAs(otherPolicy.getEntriesSet());
}
@Override
public Iterator<PolicyEntry> iterator() {
final Set<PolicyEntry> policyEntries = getEntriesSet();
return policyEntries.iterator();
}
@Override
public JsonObject toJson(final JsonSchemaVersion schemaVersion, final Predicate<JsonField> thePredicate) {
checkNotNull(schemaVersion, "schema version");
checkNotNull(thePredicate, "predicate");
final Predicate<JsonField> predicate = schemaVersion.and(thePredicate);
final JsonObjectBuilder jsonObjectBuilder = JsonFactory.newObjectBuilder();
if (null != lifecycle) {
jsonObjectBuilder.set(JsonFields.LIFECYCLE, lifecycle.name(), predicate);
}
if (null != revision) {
jsonObjectBuilder.set(JsonFields.REVISION, revision.toLong(), predicate);
}
if (null != modified) {
jsonObjectBuilder.set(JsonFields.MODIFIED, modified.toString(), predicate);
}
if (null != created) {
jsonObjectBuilder.set(JsonFields.CREATED, created.toString(), predicate);
}
if (null != policyId) {
jsonObjectBuilder.set(JsonFields.NAMESPACE, namespace, predicate);
jsonObjectBuilder.set(JsonFields.ID, String.valueOf(policyId), predicate);
}
if (null != imports) {
jsonObjectBuilder.set(JsonFields.IMPORTS, imports.toJson(schemaVersion, thePredicate), predicate);
}
jsonObjectBuilder.set(JsonFields.ENTRIES, stream()
.map(policyEntry -> JsonFactory.newObjectBuilder()
.set(policyEntry.getLabel().getJsonFieldDefinition(),
policyEntry.toJson(schemaVersion, thePredicate.and(FieldType.notHidden())),
predicate) // notice: only "not HIDDEN" sub-fields of PolicyEntry are included
.build())
.collect(JsonCollectors.objectsToObject()), predicate);
if (null != metadata) {
jsonObjectBuilder.set(JsonFields.METADATA, metadata.toJson(schemaVersion, thePredicate), predicate);
}
return jsonObjectBuilder.build();
}
private Map<Label, PolicyEntry> copyEntries() {
return new LinkedHashMap<>(entries);
}
@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final ImmutablePolicy that = (ImmutablePolicy) o;
return Objects.equals(policyId, that.policyId) &&
Objects.equals(namespace, that.namespace) &&
lifecycle == that.lifecycle &&
Objects.equals(revision, that.revision) &&
Objects.equals(modified, that.modified) &&
Objects.equals(created, that.created) &&
Objects.equals(metadata, that.metadata) &&
Objects.equals(imports, that.imports) &&
Objects.equals(entries, that.entries);
}
@Override
public int hashCode() {
return Objects.hash(policyId, namespace, lifecycle, revision, modified, created, metadata, imports, entries);
}
@Override
public String toString() {
return getClass().getSimpleName() + " [" +
"policyId=" + policyId +
", namespace=" + namespace +
", lifecycle=" + lifecycle +
", revision=" + revision +
", modified=" + modified +
", created=" + created +
", metadata=" + metadata +
", imports=" + imports +
", entries=" + entries +
"]";
}
}