-
Notifications
You must be signed in to change notification settings - Fork 5
/
ValidationUtils.java
391 lines (360 loc) · 15.8 KB
/
ValidationUtils.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
/*
* © 2021. TU Dortmund University,
* Institute of Energy Systems, Energy Efficiency and Energy Economics,
* Research group Distribution grid planning and operation
*/
package edu.ie3.datamodel.utils.validation;
import edu.ie3.datamodel.exceptions.*;
import edu.ie3.datamodel.models.UniqueEntity;
import edu.ie3.datamodel.models.input.AssetInput;
import edu.ie3.datamodel.models.input.AssetTypeInput;
import edu.ie3.datamodel.models.input.MeasurementUnitInput;
import edu.ie3.datamodel.models.input.NodeInput;
import edu.ie3.datamodel.models.input.connector.*;
import edu.ie3.datamodel.models.input.connector.type.LineTypeInput;
import edu.ie3.datamodel.models.input.connector.type.Transformer2WTypeInput;
import edu.ie3.datamodel.models.input.connector.type.Transformer3WTypeInput;
import edu.ie3.datamodel.models.input.container.GridContainer;
import edu.ie3.datamodel.models.input.graphics.GraphicInput;
import edu.ie3.datamodel.models.input.system.SystemParticipantInput;
import edu.ie3.datamodel.models.input.system.type.*;
import edu.ie3.datamodel.models.input.thermal.ThermalUnitInput;
import edu.ie3.datamodel.utils.options.Failure;
import edu.ie3.datamodel.utils.options.Success;
import edu.ie3.datamodel.utils.options.Try;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import javax.measure.Quantity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Basic Sanity validation tools for entities */
public class ValidationUtils {
protected static final Logger logger = LoggerFactory.getLogger(ValidationUtils.class);
/** Private Constructor as this class is not meant to be instantiated */
protected ValidationUtils() {
throw new IllegalStateException("Don't try and instantiate a Utility class.");
}
/**
* Creates a new {@link NotImplementedException}, if there is no check available for the class of
* the given object
*
* @param obj Object, that cannot be checked
* @return Exception with predefined error string
*/
protected static NotImplementedException checkNotImplementedException(Object obj) {
return new NotImplementedException(
String.format(
"Cannot validate object of class '%s', as no routine is implemented.",
obj.getClass().getSimpleName()));
}
/**
* This is a "distribution" method, that forwards the check request to specific implementations to
* fulfill the checking task, based on the class of the given object.
*
* @param obj Object to check
* @return a list of try objects either containing a {@link ValidationException} or an empty
* Success
*/
public static Try<Void, ValidationException> check(Object obj) {
try {
checkNonNull(obj, "an object");
} catch (InvalidEntityException e) {
return new Failure<>(e);
}
List<Try<Void, ? extends ValidationException>> exceptions = new ArrayList<>();
if (AssetInput.class.isAssignableFrom(obj.getClass())) {
exceptions.addAll(checkAsset((AssetInput) obj));
} else if (GridContainer.class.isAssignableFrom(obj.getClass())) {
exceptions.addAll(GridContainerValidationUtils.check((GridContainer) obj));
} else if (GraphicInput.class.isAssignableFrom(obj.getClass())) {
exceptions.addAll(GraphicValidationUtils.check((GraphicInput) obj));
} else if (AssetTypeInput.class.isAssignableFrom(obj.getClass())) {
exceptions.addAll(checkAssetType((AssetTypeInput) obj));
} else {
exceptions.add(
new Failure<>(
new FailedValidationException(checkNotImplementedException(obj).getMessage())));
}
List<? extends ValidationException> list =
exceptions.stream().filter(Try::isFailure).map(Try::getException).toList();
if (list.size() > 0) {
return new Failure<>(new FailedValidationException(list));
} else {
return Success.empty();
}
}
/**
* Validates an asset if: <br>
* - it is not null <br>
* - its id is not null <br>
* - its operation time is not null <br>
* - in case operation time is limited, start time is before end time <br>
* A "distribution" method, that forwards the check request to specific implementations to fulfill
* the checking task, based on the class of the given object.
*
* @param assetInput AssetInput to check
* @return a list of try objects either containing a {@link ValidationException} or an empty
* Success
*/
private static List<Try<Void, ? extends ValidationException>> checkAsset(AssetInput assetInput) {
try {
checkNonNull(assetInput, "an asset");
} catch (InvalidEntityException e) {
return List.of(
new Failure<>(
new InvalidEntityException(
"Validation not possible because received object {" + assetInput + "} was null",
e)));
}
List<Try<Void, ? extends ValidationException>> exceptions = new ArrayList<>();
if (assetInput.getId() == null) {
exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetInput)));
}
if (assetInput.getOperationTime() == null) {
return List.of(
new Failure<>(
new InvalidEntityException(
"Operation time of the asset is not defined", assetInput)));
}
// Check if start time and end time are not null and start time is before end time
if (assetInput.getOperationTime().isLimited()) {
assetInput
.getOperationTime()
.getEndDate()
.ifPresent(
endDate ->
assetInput
.getOperationTime()
.getStartDate()
.ifPresent(
startDate -> {
if (endDate.isBefore(startDate))
exceptions.add(
new Failure<>(
new InvalidEntityException(
"Operation start time of the asset has to be before end time",
assetInput)));
}));
}
// Further checks for subclasses
if (NodeInput.class.isAssignableFrom(assetInput.getClass()))
exceptions.addAll(NodeValidationUtils.check((NodeInput) assetInput));
else if (ConnectorInput.class.isAssignableFrom(assetInput.getClass()))
exceptions.addAll(ConnectorValidationUtils.check((ConnectorInput) assetInput));
else if (MeasurementUnitInput.class.isAssignableFrom(assetInput.getClass()))
exceptions.add(MeasurementUnitValidationUtils.check((MeasurementUnitInput) assetInput));
else if (SystemParticipantInput.class.isAssignableFrom(assetInput.getClass()))
exceptions.addAll(
SystemParticipantValidationUtils.check((SystemParticipantInput) assetInput));
else if (ThermalUnitInput.class.isAssignableFrom(assetInput.getClass()))
exceptions.addAll(ThermalUnitValidationUtils.check((ThermalUnitInput) assetInput));
else {
exceptions.add(
new Failure<>(
new FailedValidationException(
checkNotImplementedException(assetInput).getMessage())));
}
return exceptions;
}
/**
* Validates an asset type if: <br>
* - it is not null <br>
* A "distribution" method, that forwards the check request to specific implementations to fulfill
* the checking task, based on the class of the given object.
*
* @param assetTypeInput AssetTypeInput to check
* @return a list of try objects either containing a {@link ValidationException} or an empty
* Success
*/
private static List<Try<Void, ? extends ValidationException>> checkAssetType(
AssetTypeInput assetTypeInput) {
try {
checkNonNull(assetTypeInput, "an asset type");
} catch (InvalidEntityException e) {
return List.of(
new Failure<>(
new InvalidEntityException(
"Validation not possible because received object {"
+ assetTypeInput
+ "} was null",
e)));
}
List<Try<Void, ? extends ValidationException>> exceptions = new ArrayList<>();
if (assetTypeInput.getUuid() == null)
exceptions.add(new Failure<>(new InvalidEntityException("No UUID assigned", assetTypeInput)));
if (assetTypeInput.getId() == null)
exceptions.add(new Failure<>(new InvalidEntityException("No ID assigned", assetTypeInput)));
// Further checks for subclasses
if (LineTypeInput.class.isAssignableFrom(assetTypeInput.getClass()))
exceptions.addAll(ConnectorValidationUtils.checkLineType((LineTypeInput) assetTypeInput));
else if (Transformer2WTypeInput.class.isAssignableFrom(assetTypeInput.getClass()))
exceptions.addAll(
ConnectorValidationUtils.checkTransformer2WType((Transformer2WTypeInput) assetTypeInput));
else if (Transformer3WTypeInput.class.isAssignableFrom(assetTypeInput.getClass()))
exceptions.addAll(
ConnectorValidationUtils.checkTransformer3WType((Transformer3WTypeInput) assetTypeInput));
else if (SystemParticipantTypeInput.class.isAssignableFrom(assetTypeInput.getClass()))
exceptions.addAll(
SystemParticipantValidationUtils.checkType((SystemParticipantTypeInput) assetTypeInput));
else {
exceptions.add(
new Failure<>(
new FailedValidationException(
checkNotImplementedException(assetTypeInput).getMessage())));
}
return exceptions;
}
/**
* Checks the validity of the ids for a given set of {@link AssetInput}.
*
* @param inputs a set of asset inputs
* @return a list of try objects either containing an {@link UnsafeEntityException} or an empty
* Success
*/
protected static List<Try<Void, UnsafeEntityException>> checkIds(
Set<? extends AssetInput> inputs) {
List<String> ids = new ArrayList<>();
List<Try<Void, UnsafeEntityException>> exceptions = new ArrayList<>();
inputs.forEach(
input -> {
String id = input.getId();
if (!ids.contains(id)) {
ids.add(id);
exceptions.add(Success.empty());
} else {
exceptions.add(
new Failure<>(
new UnsafeEntityException(
"There is already an entity with the id " + id, input)));
}
});
return exceptions;
}
/**
* Checks, if the given object is null. If so, an {@link InvalidEntityException} is thrown.
*
* @param obj Object to check
* @param expectedDescription Further description, of what has been expected.
*/
protected static void checkNonNull(Object obj, String expectedDescription) {
if (obj == null)
throw new InvalidEntityException(
"Expected " + expectedDescription + ", but got nothing. :-(", new NullPointerException());
}
/**
* Goes through the provided quantities and reports those, that have negative value via synoptic
* {@link UnsafeEntityException}
*
* @param quantities Array of quantities to check
* @param entity Unique entity holding the malformed quantities
*/
protected static void detectNegativeQuantities(Quantity<?>[] quantities, UniqueEntity entity) {
Predicate<Quantity<?>> predicate = quantity -> quantity.getValue().doubleValue() < 0d;
detectMalformedQuantities(
quantities, entity, predicate, "The following quantities have to be zero or positive");
}
/**
* Goes through the provided quantities and reports those, that are zero or have negative value
* via synoptic {@link UnsafeEntityException}
*
* @param quantities Array of quantities to check
* @param entity Unique entity holding the malformed quantities
*/
protected static void detectZeroOrNegativeQuantities(
Quantity<?>[] quantities, UniqueEntity entity) {
Predicate<Quantity<?>> predicate = quantity -> quantity.getValue().doubleValue() <= 0d;
detectMalformedQuantities(
quantities, entity, predicate, "The following quantities have to be positive");
}
/**
* Goes through the provided quantities and reports those, that have positive value via
*
* @param quantities Array of quantities to check
* @param entity Unique entity holding the malformed quantities
*/
protected static void detectPositiveQuantities(Quantity<?>[] quantities, UniqueEntity entity) {
Predicate<Quantity<?>> predicate = quantity -> quantity.getValue().doubleValue() > 0d;
detectMalformedQuantities(
quantities, entity, predicate, "The following quantities have to be negative");
}
/**
* Goes through the provided quantities and reports those, that do fulfill the given predicate via
* synoptic {@link UnsafeEntityException}
*
* @param quantities Array of quantities to check
* @param entity Unique entity holding the malformed quantities
* @param predicate Predicate to detect the malformed quantities
* @param msg Message prefix to use for the exception message: [msg]: [malformedQuantities]
*/
protected static void detectMalformedQuantities(
Quantity<?>[] quantities, UniqueEntity entity, Predicate<Quantity<?>> predicate, String msg) {
String malformedQuantities =
Arrays.stream(quantities)
.filter(predicate)
.map(Quantity::toString)
.collect(Collectors.joining(", "));
if (!malformedQuantities.isEmpty()) {
throw new InvalidEntityException(msg + ": " + malformedQuantities, entity);
}
}
/**
* Determines if the provided set only contains elements with distinct UUIDs
*
* @param entities the set that should be checked
* @return true if all UUIDs of the provided entities are unique, false otherwise
*/
private static boolean distinctUuids(Set<? extends UniqueEntity> entities) {
return entities.stream()
.filter(distinctByKey(UniqueEntity::getUuid))
.collect(Collectors.toSet())
.size()
== entities.size();
}
/**
* Predicate that can be used to filter elements based on a given Function
*
* @param keyExtractor the function that should be used for the filter operations
* @param <T> the type of the returning predicate
* @return the filter predicate that filters based on the provided function
*/
public static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Set<Object> seen = ConcurrentHashMap.newKeySet();
return t -> seen.add(keyExtractor.apply(t));
}
/**
* Checks if the provided set of unique entities only contains elements with distinct UUIDs and
* either returns a string with duplicated UUIDs or an empty optional otherwise.
*
* @param entities the entities that should be checkd for UUID uniqueness
* @return either a string wrapped in an optional with duplicate UUIDs or an empty optional
*/
protected static Optional<String> checkForDuplicateUuids(Set<UniqueEntity> entities) {
if (distinctUuids(entities)) {
return Optional.empty();
}
String duplicationsString =
entities.stream()
.collect(Collectors.groupingBy(UniqueEntity::getUuid, Collectors.counting()))
.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.map(
entry -> {
String duplicateEntitiesString =
entities.stream()
.filter(entity -> entity.getUuid().equals(entry.getKey()))
.map(UniqueEntity::toString)
.collect(Collectors.joining("\n - "));
return entry.getKey()
+ ": "
+ entry.getValue()
+ "\n - "
+ duplicateEntitiesString;
})
.collect(Collectors.joining("\n\n"));
return Optional.of(duplicationsString);
}
}