-
Notifications
You must be signed in to change notification settings - Fork 188
/
OperationResult.java
2435 lines (2111 loc) · 87 KB
/
OperationResult.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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) 2010-2017 Evolveum and contributors
*
* This work is dual-licensed under the Apache License 2.0
* and European Union Public License. See LICENSE file for details.
*/
package com.evolveum.midpoint.schema.result;
import java.io.Serializable;
import java.util.*;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.xml.namespace.QName;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.Visitable;
import com.evolveum.midpoint.prism.Visitor;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.util.CloneUtil;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.schema.util.LocalizationUtil;
import com.evolveum.midpoint.util.*;
import com.evolveum.midpoint.util.logging.*;
import com.evolveum.midpoint.util.statistics.OperationInvocationRecord;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.Validate;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.util.ParamsTypeUtil;
import com.evolveum.midpoint.util.exception.CommonException;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import static com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultImportanceType.*;
import static java.util.Collections.emptyList;
import static java.util.Collections.singletonList;
import static org.apache.commons.collections4.CollectionUtils.emptyIfNull;
import static org.apache.commons.lang3.ObjectUtils.defaultIfNull;
/**
* Nested Operation Result.
*
* This class provides information for better error handling in complex
* operations. It contains a status (success, failure, warning, ...) and an
* error message. It also contains a set of sub-results - results on inner
* operations.
*
* This object can be used by GUI to display smart (and interactive) error
* information. It can also be used by the client code to detect deeper problems
* in the invocations, retry or otherwise compensate for the errors or decide
* how severe the error was and it is possible to proceed.
*
* @author lazyman
* @author Radovan Semancik
*
*/
public class OperationResult implements Serializable, DebugDumpable, ShortDumpable, Cloneable, OperationResultBuilder, Visitable<OperationResult> {
private static final long serialVersionUID = -2467406395542291044L;
private static final String VARIOUS_VALUES = "[various values]";
private static final String INDENT_STRING = " ";
private static final String TASK_OID_PREFIX = "taskOid:";
private static final String CASE_OID_PREFIX = "caseOid:";
/**
* This constant provides count threshold for same subresults (same operation and
* status) during summarize operation.
*/
private static final int DEFAULT_SUBRESULT_STRIP_THRESHOLD = 10;
@NotNull private static final OperationResultHandlingStrategyType DEFAULT_HANDLING_STRATEGY = new OperationResultHandlingStrategyType();
@NotNull private volatile static List<OperationResultHandlingStrategyType> handlingStrategies = emptyList();
@NotNull private static OperationResultHandlingStrategyType globalHandlingStrategy = DEFAULT_HANDLING_STRATEGY;
private static final ThreadLocal<OperationResultHandlingStrategyType> LOCAL_HANDLING_STRATEGY =
new ThreadLocal<>();
private static final AtomicInteger LOG_SEQUENCE_COUNTER = new AtomicInteger(0);
public static final String CONTEXT_IMPLEMENTATION_CLASS = "implementationClass";
public static final String CONTEXT_PROGRESS = "progress";
public static final String CONTEXT_OID = "oid";
public static final String CONTEXT_OBJECT = "object";
public static final String CONTEXT_ITEM = "item";
public static final String CONTEXT_TASK = "task";
public static final String CONTEXT_RESOURCE = "resource";
public static final String CONTEXT_REASON = "reason";
public static final String PARAM_OID = "oid";
public static final String PARAM_NAME = "name";
public static final String PARAM_TYPE = "type";
public static final String PARAM_OPTIONS = "options";
public static final String PARAM_TASK = "task";
public static final String PARAM_OBJECT = "object";
public static final String PARAM_QUERY = "query";
public static final String PARAM_PROJECTION = "projection";
public static final String PARAM_LANGUAGE = "language";
public static final String RETURN_COUNT = "count";
public static final String RETURN_BACKGROUND_TASK_OID = "backgroundTaskOid";
public static final String RETURN_COMMENT = "comment";
public static final String DEFAULT = "";
private static long tokenCount = 1000000000000000000L;
private String operation;
private OperationResultStatus status;
// Values of the following maps should NOT be null. But in reality it does happen.
// If there is a null value, it should be stored as a single-item collection, where the item is null.
// But the collection should not be null. TODO; fix this
private Map<String, Collection<String>> params;
private Map<String, Collection<String>> context;
private Map<String, Collection<String>> returns;
private final List<String> qualifiers = new ArrayList<>();
private long token;
private String messageCode;
private String message;
private LocalizableMessage userFriendlyMessage;
private Throwable cause;
private int count = 1;
private int hiddenRecordsCount;
private List<OperationResult> subresults;
private List<String> details;
private boolean summarizeErrors;
private boolean summarizePartialErrors;
private boolean summarizeSuccesses;
private OperationResultImportanceType importance = NORMAL;
private boolean building; // experimental (NOT SERIALIZED)
private OperationResult futureParent; // experimental (NOT SERIALIZED)
private Long start;
private Long end;
private Long microseconds;
private Long invocationId;
private final List<LogSegmentType> logSegments = new ArrayList<>();
private CompiledTracingProfile tracingProfile; // NOT SERIALIZED
private boolean collectingLogEntries; // NOT SERIALIZED
private boolean startedLoggingOverride; // NOT SERIALIZED
/**
* After a trace rooted at this operation result is stored, the dictionary that was extracted is stored here.
* It is necessary to correctly interpret traces in this result and its subresults.
*/
private TraceDictionaryType extractedDictionary; // NOT SERIALIZED
private final List<TraceType> traces = new ArrayList<>();
// Caller can specify the reason of the operation invocation.
// (Normally, the reason is known from the parent opResult; but it might be an overkill to create operation result
// only to specify the reason.)
//
// Use of this attribute assumes that the callee will ALWAYS create OperationResult as its first step.
// TODO reconsider ... it looks like a really ugly hack
private transient String callerReason;
/**
* Reference to an asynchronous operation that can be used to retrieve
* the status of the running operation. This may be a task identifier,
* identifier of a ticket in ITSM system or anything else. The exact
* format of this reference depends on the operation which is being
* executed.
*/
private String asynchronousOperationReference;
private OperationInvocationRecord invocationRecord;
private static final Trace LOGGER = TraceManager.getTrace(OperationResult.class);
public OperationResult(String operation) {
this(operation, null, OperationResultStatus.UNKNOWN, 0, null, null, null, null, null);
}
public OperationResult(String operation, OperationResultStatus status, LocalizableMessage userFriendlyMessage) {
this(operation, null, status, 0, null, null, userFriendlyMessage, null, null);
}
public OperationResult(String operation, OperationResultStatus status, String message) {
this(operation, null, status, 0, null, message, null, null, null);
}
public OperationResult(String operation, Map<String, Collection<String>> params, OperationResultStatus status,
long token, String messageCode, String message, LocalizableMessage userFriendlyMessage, Throwable cause, List<OperationResult> subresults) {
this(operation, params, null, null, status, token, messageCode, message, userFriendlyMessage, cause,
subresults);
}
public OperationResult(String operation, Map<String, Collection<String>> params, Map<String, Collection<String>> context,
Map<String, Collection<String>> returns, OperationResultStatus status, long token, String messageCode,
String message, LocalizableMessage userFriendlyMessage, Throwable cause, List<OperationResult> subresults) {
if (StringUtils.isEmpty(operation)) {
throw new IllegalArgumentException("Operation argument must not be null or empty.");
}
if (status == null) {
throw new IllegalArgumentException("Operation status must not be null.");
}
this.operation = operation;
this.params = params;
this.context = context;
this.returns = returns;
this.status = status;
this.token = token;
this.messageCode = messageCode;
this.message = message;
this.userFriendlyMessage = userFriendlyMessage;
this.cause = cause;
this.subresults = subresults;
this.details = new ArrayList<>();
}
public static OperationResult keepRootOnly(OperationResult result) {
return result != null ? result.keepRootOnly() : null;
}
private OperationResult keepRootOnly() {
return new OperationResult(getOperation(), null, getStatus(), 0, getMessageCode(), getMessage(), null, null, null);
}
public OperationResultBuilder subresult(String operation) {
OperationResult subresult = new OperationResult(operation);
subresult.building = true;
subresult.futureParent = this;
subresult.tracingProfile = tracingProfile;
return subresult;
}
public static OperationResultBuilder createFor(String operation) {
OperationResult rv = new OperationResult(operation);
rv.building = true;
return rv;
}
@Override
public OperationResult build() {
if (!building) {
throw new IllegalStateException("Not being built");
}
recordStart(this, operation, createArguments());
building = false;
if (futureParent != null) {
futureParent.addSubresult(this);
recordCallerReason(futureParent);
}
return this;
}
private void recordCallerReason(OperationResult parent) {
if (parent.getCallerReason() != null) {
addContext(CONTEXT_REASON, parent.getCallerReason());
parent.setCallerReason(null);
}
}
private static void recordStart(OperationResult result, String operation, Object[] arguments) {
result.collectingLogEntries = result.tracingProfile != null && result.tracingProfile.isCollectingLogEntries();
if (result.collectingLogEntries) {
LoggingLevelOverrideConfiguration loggingOverrideConfiguration = result.tracingProfile.getLoggingLevelOverrideConfiguration();
if (loggingOverrideConfiguration != null && !LevelOverrideTurboFilter.isActive()) {
LevelOverrideTurboFilter.overrideLogging(loggingOverrideConfiguration);
result.startedLoggingOverride = true;
}
TracingAppender.openSink(result::appendLoggedEvents);
}
// TODO for very minor operation results (e.g. those dealing with mapping and script execution)
// we should consider skipping creation of invocationRecord. It includes some string manipulation(s)
// and a call to System.nanoTime that could unnecessarily slow down midPoint operation.
result.invocationRecord = OperationInvocationRecord.create(operation, arguments);
result.invocationId = result.invocationRecord.getInvocationId();
result.start = System.currentTimeMillis();
}
private void appendLoggedEvents(LoggingEventSink loggingEventSink) {
if (!loggingEventSink.getEvents().isEmpty()) {
LogSegmentType segment = new LogSegmentType();
segment.setSequenceNumber(LOG_SEQUENCE_COUNTER.getAndIncrement());
for (LoggedEvent event : loggingEventSink.getEvents()) {
segment.getEntry().add(event.getText());
}
logSegments.add(segment);
loggingEventSink.clearEvents();
}
}
private Object[] createArguments() {
List<String> arguments = new ArrayList<>();
getParams().forEach((key, value) -> arguments.add(key + " => " + value)); // todo what with large values?
getContext().forEach((key, value) -> arguments.add("c:" + key + " => " + value));
return arguments.toArray();
}
public OperationResult createSubresult(String operation) {
return createSubresult(operation, false, new Object[0]);
}
public OperationResult createMinorSubresult(String operation) {
return createSubresult(operation, true, null);
}
// public static OperationResult createProfiled(String operation) {
// return createProfiled(operation, new Object[0]);
// }
//
// public static OperationResult createProfiled(String operation, Object[] arguments) {
// OperationResult result = new OperationResult(operation);
// recordStart(result, operation, arguments);
// return result;
// }
private OperationResult createSubresult(String operation, boolean minor, Object[] arguments) {
OperationResult subresult = new OperationResult(operation);
subresult.recordCallerReason(this);
addSubresult(subresult);
recordStart(subresult, operation, arguments);
subresult.importance = minor ? MINOR : NORMAL;
return subresult;
}
// todo determine appropriate places where recordEnd() should be called
public void recordEnd() {
if (invocationRecord != null) {
// TODO use lambda here to avoid string manipulation if not necessary (i.e. if profiling logging is turned off)
String returnValue = getReturns().toString();
if (cause != null) {
returnValue += "; " + cause.getClass().getName() + ": " + cause.getMessage();
}
// This is not quite clean. We should report the exception via processException method - but that does not allow
// showing return values that can be present in operation result. So this is a hack until InvocationRecord is fixed.
invocationRecord.processReturnValue(returnValue);
invocationRecord.afterCall();
microseconds = invocationRecord.getElapsedTimeMicros();
if (collectingLogEntries) {
TracingAppender.closeCurrentSink();
collectingLogEntries = false;
}
invocationRecord = null;
}
end = System.currentTimeMillis();
if (startedLoggingOverride) {
LevelOverrideTurboFilter.cancelLoggingOverride();
startedLoggingOverride = false;
}
}
// This is not quite useful: We want to record the "real" end, i.e. when the control leaves the region belonging to
// the operation result. So it's actually OK to rewrite the end timestamp, even if it was already set.
// A small price to pay is that "end" could get a bit inconsistent with "microseconds", that was presumably set earlier.
// But that's quite good - when analyzing we can see that such an inconsistency arose and we can deal with it.
// public void recordEndIfNeeded() {
// if (invocationRecord != null || end == null) {
// recordEnd();
// }
// }
/**
* Reference to an asynchronous operation that can be used to retrieve
* the status of the running operation. This may be a task identifier,
* identifier of a ticket in ITSM system or anything else. The exact
* format of this reference depends on the operation which is being
* executed.
*/
public String getAsynchronousOperationReference() {
return asynchronousOperationReference;
}
public void setAsynchronousOperationReference(String asynchronousOperationReference) {
this.asynchronousOperationReference = asynchronousOperationReference;
}
/**
* This method partially duplicates functionality of computeStatus. However, computeStatus
* currently does not propagate taskOid from tasks switched to background, because switchToBackground
* sets its result to SUCCESS (not IN_PROGRESS) because of some historical reasons. So,
* until this is fixed somehow, this is a bit of hack to fetch asynchronous operation reference
* even in such cases.
*/
public String findAsynchronousOperationReference() {
if (asynchronousOperationReference != null) {
return asynchronousOperationReference;
}
for (OperationResult subresult : emptyIfNull(subresults)) {
String s = subresult.findAsynchronousOperationReference();
if (s != null) {
return s;
}
}
return null;
}
public static boolean isTaskOid(String ref) {
return ref != null && ref.startsWith(TASK_OID_PREFIX);
}
public static String referenceToTaskOid(String ref) {
return isTaskOid(ref) ? ref.substring(TASK_OID_PREFIX.length()) : null;
}
public static String referenceToCaseOid(String ref) {
return ref != null && ref.startsWith(CASE_OID_PREFIX) ? ref.substring(CASE_OID_PREFIX.length()) : null;
}
/**
* Contains operation name. Operation name must be defined as {@link String}
* constant in module interface with description and possible parameters. It
* can be used for further processing. It will be used as key for
* translation in admin-gui.
*
* @return always return non null, non empty string
*/
public String getOperation() {
return operation;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public void incrementCount() {
this.count++;
}
public int getHiddenRecordsCount() {
return hiddenRecordsCount;
}
public void setHiddenRecordsCount(int hiddenRecordsCount) {
this.hiddenRecordsCount = hiddenRecordsCount;
}
public boolean representsHiddenRecords() {
return this.hiddenRecordsCount > 0;
}
public boolean isSummarizeErrors() {
return summarizeErrors;
}
public void setSummarizeErrors(boolean summarizeErrors) {
this.summarizeErrors = summarizeErrors;
}
public boolean isSummarizePartialErrors() {
return summarizePartialErrors;
}
public void setSummarizePartialErrors(boolean summarizePartialErrors) {
this.summarizePartialErrors = summarizePartialErrors;
}
public boolean isSummarizeSuccesses() {
return summarizeSuccesses;
}
public void setSummarizeSuccesses(boolean summarizeSuccesses) {
this.summarizeSuccesses = summarizeSuccesses;
}
public boolean isEmpty() {
return (status == null || status == OperationResultStatus.UNKNOWN) &&
(subresults == null || subresults.isEmpty());
}
/**
* Method returns list of operation subresults @{link
* {@link OperationResult}.
*
* @return never returns null
*/
@NotNull
public List<OperationResult> getSubresults() {
if (subresults == null) {
subresults = new ArrayList<>();
}
return subresults;
}
/**
* @return last subresult, or null if there are no subresults.
*/
public OperationResult getLastSubresult() {
if (subresults == null || subresults.isEmpty()) {
return null;
} else {
return subresults.get(subresults.size()-1);
}
}
public void removeLastSubresult() {
if (subresults != null && !subresults.isEmpty()) {
subresults.remove(subresults.size()-1);
}
}
/**
* @return last subresult status, or null if there are no subresults.
*/
public OperationResultStatus getLastSubresultStatus() {
OperationResult last = getLastSubresult();
return last != null ? last.getStatus() : null;
}
public void addSubresult(OperationResult subresult) {
getSubresults().add(subresult);
if (subresult.tracingProfile == null) {
subresult.tracingProfile = tracingProfile;
}
}
public OperationResult findSubresult(String operation) {
if (subresults == null) {
return null;
}
for (OperationResult subResult: getSubresults()) {
if (operation.equals(subResult.getOperation())) {
return subResult;
}
}
return null;
}
public List<OperationResult> findSubresults(String operation) {
List<OperationResult> found = new ArrayList<>();
if (subresults == null) {
return found;
}
for (OperationResult subResult: getSubresults()) {
if (operation.equals(subResult.getOperation())) {
found.add(subResult);
}
}
return found;
}
/**
* Contains operation status as defined in {@link OperationResultStatus}
*
* @return never returns null
*/
public OperationResultStatus getStatus() {
return status;
}
public void setStatus(OperationResultStatus status) {
this.status = status;
}
/**
* Returns true if the result is success.
*
* This returns true if the result is absolute success. Presence of partial
* failures or warnings fail this test.
*
* @return true if the result is success.
*/
public boolean isSuccess() {
return (status == OperationResultStatus.SUCCESS);
}
public boolean isWarning() {
return status == OperationResultStatus.WARNING;
}
/**
* Returns true if the result is acceptable for further processing.
*
* In other words: if there were no fatal errors. Warnings and partial
* errors are acceptable. Yet, this test also fails if the operation state
* is not known.
*
* @return true if the result is acceptable for further processing.
*/
public boolean isAcceptable() {
return (status != OperationResultStatus.FATAL_ERROR);
}
public boolean isUnknown() {
return (status == OperationResultStatus.UNKNOWN);
}
public boolean isInProgress() {
return (status == OperationResultStatus.IN_PROGRESS);
}
public boolean isError() {
return (status == OperationResultStatus.FATAL_ERROR) ||
(status == OperationResultStatus.PARTIAL_ERROR);
}
public boolean isFatalError() {
return (status == OperationResultStatus.FATAL_ERROR);
}
public boolean isPartialError() {
return (status == OperationResultStatus.PARTIAL_ERROR);
}
public boolean isHandledError() {
return (status == OperationResultStatus.HANDLED_ERROR);
}
public boolean isNotApplicable() {
return (status == OperationResultStatus.NOT_APPLICABLE);
}
/**
* Set all error status in this result and all subresults as handled.
*/
public void setErrorsHandled() {
if (isError()) {
setStatus(OperationResultStatus.HANDLED_ERROR);
}
for(OperationResult subresult: getSubresults()) {
subresult.setErrorsHandled();
}
}
/**
* Computes operation result status based on subtask status and sets an
* error message if the status is FATAL_ERROR.
*
* @param errorMessage
* error message
*/
public void computeStatus(String errorMessage) {
computeStatus(errorMessage, errorMessage);
}
public void computeStatus(String errorMessage, String warnMessage) {
Validate.notEmpty(errorMessage, "Error message must not be null.");
// computeStatus sets a message if none is set,
// therefore we need to check before calling computeStatus
boolean noMessage = StringUtils.isEmpty(message);
computeStatus();
switch (status) {
case FATAL_ERROR:
case PARTIAL_ERROR:
if (noMessage) {
message = errorMessage;
}
break;
case UNKNOWN:
case WARNING:
case NOT_APPLICABLE:
if (noMessage) {
if (StringUtils.isNotEmpty(warnMessage)) {
message = warnMessage;
} else {
message = errorMessage;
}
}
break;
}
}
/**
* Computes operation result status based on subtask status.
*/
public void computeStatus() {
computeStatus(false);
}
public void computeStatus(boolean skipFinish) {
if (!skipFinish) {
recordEnd();
}
if (getSubresults().isEmpty()) {
if (status == OperationResultStatus.UNKNOWN) {
status = OperationResultStatus.SUCCESS;
}
return;
}
if (status == OperationResultStatus.FATAL_ERROR) {
return;
}
OperationResultStatus newStatus = OperationResultStatus.UNKNOWN;
boolean allSuccess = true;
boolean allNotApplicable = true;
String newMessage = null;
LocalizableMessage newUserFriendlyMessage = null;
for (OperationResult sub : getSubresults()) {
if (sub == null) {
continue;
}
if (sub.getStatus() != OperationResultStatus.NOT_APPLICABLE) {
allNotApplicable = false;
}
if (sub.getStatus() == OperationResultStatus.FATAL_ERROR) {
status = OperationResultStatus.FATAL_ERROR;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ": " + sub.getMessage();
}
updateLocalizableMessage(sub);
return;
}
if (sub.getStatus() == OperationResultStatus.IN_PROGRESS) {
status = OperationResultStatus.IN_PROGRESS;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ": " + sub.getMessage();
}
updateLocalizableMessage(sub);
if (asynchronousOperationReference == null) {
asynchronousOperationReference = sub.getAsynchronousOperationReference();
}
return;
}
if (sub.getStatus() == OperationResultStatus.PARTIAL_ERROR) {
newStatus = OperationResultStatus.PARTIAL_ERROR;
newMessage = sub.getMessage();
newUserFriendlyMessage = sub.getUserFriendlyMessage();
}
if (newStatus != OperationResultStatus.PARTIAL_ERROR){
if (sub.getStatus() == OperationResultStatus.HANDLED_ERROR) {
newStatus = OperationResultStatus.HANDLED_ERROR;
newMessage = sub.getMessage();
newUserFriendlyMessage = sub.getUserFriendlyMessage();
}
}
if (sub.getStatus() != OperationResultStatus.SUCCESS
&& sub.getStatus() != OperationResultStatus.NOT_APPLICABLE) {
allSuccess = false;
}
if (newStatus != OperationResultStatus.HANDLED_ERROR) {
if (sub.getStatus() == OperationResultStatus.WARNING) {
newStatus = OperationResultStatus.WARNING;
newMessage = sub.getMessage();
newUserFriendlyMessage = sub.getUserFriendlyMessage();
}
}
}
if (allNotApplicable && !getSubresults().isEmpty()) {
status = OperationResultStatus.NOT_APPLICABLE;
} else if (allSuccess && !getSubresults().isEmpty()) {
status = OperationResultStatus.SUCCESS;
} else {
status = newStatus;
if (message == null) {
message = newMessage;
} else {
message = message + ": " + newMessage;
}
updateLocalizableMessage(newUserFriendlyMessage);
}
}
private void updateLocalizableMessage(OperationResult subResult) {
if (userFriendlyMessage == null) {
userFriendlyMessage = subResult.getUserFriendlyMessage();
} else {
updateLocalizableMessage(subResult.getUserFriendlyMessage());
}
}
private void updateLocalizableMessage(LocalizableMessage localizableMessage) {
if (localizableMessage == null) {
return;
}
if (userFriendlyMessage instanceof SingleLocalizableMessage) {
userFriendlyMessage = new LocalizableMessageListBuilder()
.message(userFriendlyMessage)
.message(localizableMessage)
.separator(LocalizableMessageList.SPACE).build();
} else if (userFriendlyMessage instanceof LocalizableMessageList) {
LocalizableMessageList userFriendlyMessageList = (LocalizableMessageList) this.userFriendlyMessage;
userFriendlyMessage = new LocalizableMessageList(
mergeMessages(userFriendlyMessageList, localizableMessage),
userFriendlyMessageList.getSeparator(),
userFriendlyMessageList.getPrefix(),
userFriendlyMessageList.getPostfix());
}
}
private List<LocalizableMessage> mergeMessages(LocalizableMessageList sum, LocalizableMessage increment) {
List<LocalizableMessage> rv = new ArrayList<>(sum.getMessages());
if (increment instanceof SingleLocalizableMessage) {
rv.add(increment);
} else if (increment instanceof LocalizableMessageList) {
rv.addAll(((LocalizableMessageList) increment).getMessages());
} else {
throw new IllegalArgumentException("increment: " + increment);
}
return rv;
}
/**
* Used when the result contains several composite sub-result that are of equivalent meaning.
* If all of them fail the result will be fatal error as well. If only some of them fail the
* result will be partial error. Handled error is considered a success.
*/
public void computeStatusComposite() {
recordEnd();
if (getSubresults().isEmpty()) {
if (status == OperationResultStatus.UNKNOWN) {
status = OperationResultStatus.NOT_APPLICABLE;
}
return;
}
boolean allFatalError = true;
boolean allNotApplicable = true;
boolean hasInProgress = false;
boolean hasHandledError = false;
boolean hasError = false;
boolean hasWarning = false;
for (OperationResult sub : getSubresults()) {
if (sub.getStatus() != OperationResultStatus.NOT_APPLICABLE) {
allNotApplicable = false;
}
if (sub.getStatus() != OperationResultStatus.FATAL_ERROR) {
allFatalError = false;
}
if (sub.getStatus() == OperationResultStatus.FATAL_ERROR) {
hasError = true;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ", " + sub.getMessage();
}
}
if (sub.getStatus() == OperationResultStatus.PARTIAL_ERROR) {
hasError = true;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ", " + sub.getMessage();
}
}
if (sub.getStatus() == OperationResultStatus.HANDLED_ERROR) {
hasHandledError = true;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ", " + sub.getMessage();
}
}
if (sub.getStatus() == OperationResultStatus.IN_PROGRESS) {
hasInProgress = true;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ", " + sub.getMessage();
}
if (asynchronousOperationReference == null) {
asynchronousOperationReference = sub.getAsynchronousOperationReference();
}
}
if (sub.getStatus() == OperationResultStatus.WARNING) {
hasWarning = true;
if (message == null) {
message = sub.getMessage();
} else {
message = message + ", " + sub.getMessage();
}
}
}
if (allNotApplicable) {
status = OperationResultStatus.NOT_APPLICABLE;
} else if (allFatalError) {
status = OperationResultStatus.FATAL_ERROR;
} else if (hasInProgress) {
status = OperationResultStatus.IN_PROGRESS;
} else if (hasError) {
status = OperationResultStatus.PARTIAL_ERROR;
} else if (hasWarning) {
status = OperationResultStatus.WARNING;
} else if (hasHandledError) {
status = OperationResultStatus.HANDLED_ERROR;
} else {
status = OperationResultStatus.SUCCESS;
}
}
public void addTrace(TraceType trace) {
traces.add(trace);
}
@Override
public OperationResultBuilder tracingProfile(CompiledTracingProfile profile) {
this.tracingProfile = profile;
return this;
}
public <T> T getFirstTrace(Class<T> traceClass) {
Optional<TraceType> first = traces.stream().filter(t -> traceClass.isAssignableFrom(t.getClass())).findFirst();
if (first.isPresent()) {
//noinspection unchecked
return (T) first.get();
} else {
for (OperationResult subresult : getSubresults()) {
T firstInSubresult = subresult.getFirstTrace(traceClass);
if (firstInSubresult != null) {
return firstInSubresult;
}
}
return null;
}
}
public void addReturnComment(String comment) {
addReturn(RETURN_COMMENT, comment);
}
public boolean isTracingNormal(Class<? extends TraceType> traceClass) {
return isTracing(traceClass, TracingLevelType.NORMAL);
}
public boolean isTracingMinimal(Class<? extends TraceType> traceClass) {
return isTracing(traceClass, TracingLevelType.MINIMAL);
}
public boolean isTracingDetailed(Class<? extends TraceType> traceClass) {
return isTracing(traceClass, TracingLevelType.DETAILED);
}
public boolean isTracing(Class<? extends TraceType> traceClass, TracingLevelType level) {
return getTracingLevel(traceClass).ordinal() >= level.ordinal();
}
@NotNull
public TracingLevelType getTracingLevel(Class<? extends TraceType> traceClass) {
if (tracingProfile != null) {
return tracingProfile.getLevel(traceClass);
} else {
return TracingLevelType.OFF;
}
}
public void clearTracingProfile() {
tracingProfile = null;
}
@Override
public void accept(Visitor<OperationResult> visitor) {
visitor.visit(this);
if (subresults != null) {
for (OperationResult subresult : subresults) {
subresult.accept(visitor);
}
}
}
public Stream<OperationResult> getResultStream() {
return Stream.concat(Stream.of(this),
getSubresults().stream()
.map(subresult -> subresult.getResultStream())
.flatMap(stream -> stream));
}
public static final class PreviewResult {
public final OperationResultStatus status;
public final String message;
private PreviewResult(OperationResultStatus status, String message) {
this.status = status;
this.message = message;
}
}
// This is quite ugly. We should compute the preview in a way that does not modify existing object.
public PreviewResult computePreview() {
OperationResultStatus origStatus = status;
String origMessage = message;
computeStatus(true);
PreviewResult rv = new PreviewResult(status, message);
status = origStatus;
message = origMessage;
return rv;
}
public OperationResultStatus getComputeStatus() {
return computePreview().status;