-
Notifications
You must be signed in to change notification settings - Fork 188
/
AbstractIntegrationTest.java
2916 lines (2513 loc) · 144 KB
/
AbstractIntegrationTest.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-2019 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.test;
import static org.testng.AssertJUnit.*;
import static com.evolveum.midpoint.test.PredefinedTestMethodTracing.OFF;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;
import javax.annotation.PostConstruct;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.JAXBElement;
import javax.xml.datatype.Duration;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.apache.commons.lang.SystemUtils;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.opends.server.types.Entry;
import org.opends.server.types.SearchResultEntry;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.crypto.password.LdapShaPasswordEncoder;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import org.springframework.test.context.web.ServletTestExecutionListener;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.ITestResult;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.w3c.dom.Element;
import com.evolveum.icf.dummy.resource.DummyResource;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.LocalizationService;
import com.evolveum.midpoint.common.LocalizationServiceImpl;
import com.evolveum.midpoint.common.crypto.CryptoUtil;
import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition;
import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchema;
import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl;
import com.evolveum.midpoint.prism.*;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.delta.*;
import com.evolveum.midpoint.prism.delta.builder.S_ItemEntry;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.path.ItemName;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.polystring.PolyString;
import com.evolveum.midpoint.prism.query.ObjectFilter;
import com.evolveum.midpoint.prism.query.ObjectQuery;
import com.evolveum.midpoint.prism.query.QueryConverter;
import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty;
import com.evolveum.midpoint.prism.util.PrismAsserts;
import com.evolveum.midpoint.prism.util.PrismTestUtil;
import com.evolveum.midpoint.prism.xml.XmlTypeConverter;
import com.evolveum.midpoint.repo.api.RepoAddOptions;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.*;
import com.evolveum.midpoint.schema.constants.ConnectorTestOperation;
import com.evolveum.midpoint.schema.constants.MidPointConstants;
import com.evolveum.midpoint.schema.constants.ObjectTypes;
import com.evolveum.midpoint.schema.constants.SchemaConstants;
import com.evolveum.midpoint.schema.internals.CachingStatistics;
import com.evolveum.midpoint.schema.internals.InternalCounters;
import com.evolveum.midpoint.schema.internals.InternalMonitor;
import com.evolveum.midpoint.schema.internals.InternalsConfig;
import com.evolveum.midpoint.schema.processor.ObjectFactory;
import com.evolveum.midpoint.schema.processor.*;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.*;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.task.api.Tracer;
import com.evolveum.midpoint.test.asserter.AbstractAsserter;
import com.evolveum.midpoint.test.asserter.ResourceAsserter;
import com.evolveum.midpoint.test.asserter.ShadowAsserter;
import com.evolveum.midpoint.test.asserter.prism.PolyStringAsserter;
import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter;
import com.evolveum.midpoint.test.asserter.refinedschema.RefinedResourceSchemaAsserter;
import com.evolveum.midpoint.test.ldap.OpenDJController;
import com.evolveum.midpoint.test.util.*;
import com.evolveum.midpoint.tools.testng.CurrentTestResultHolder;
import com.evolveum.midpoint.tools.testng.MidpointTestContext;
import com.evolveum.midpoint.util.*;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.xml.ns._public.common.common_3.*;
import com.evolveum.prism.xml.ns._public.types_3.PolyStringType;
import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType;
import com.evolveum.prism.xml.ns._public.types_3.RawType;
/**
* @author Radovan Semancik
*/
@Listeners({ CurrentTestResultHolder.class })
public abstract class AbstractIntegrationTest extends AbstractSpringTest
implements OperationResultTestMixin {
protected static final String USER_ADMINISTRATOR_USERNAME = "administrator";
public static final String COMMON_DIR_NAME = "common";
public static final File COMMON_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, COMMON_DIR_NAME);
protected static final String DEFAULT_INTENT = "default";
protected static final String OPENDJ_PEOPLE_SUFFIX = "ou=people,dc=example,dc=com";
protected static final String OPENDJ_GROUPS_SUFFIX = "ou=groups,dc=example,dc=com";
protected static final Random RND = new Random();
private static final String MACRO_TEST_NAME_TRACER_PARAM = "testName";
private static final String MACRO_TEST_NAME_SHORT_TRACER_PARAM = "testNameShort";
private static final float FLOAT_EPSILON = 0.001f;
// Values used to check if something is unchanged or changed properly
protected LdapShaPasswordEncoder ldapShaPasswordEncoder = new LdapShaPasswordEncoder();
private Map<InternalCounters, Long> lastCountMap = new HashMap<>();
private CachingStatistics lastResourceCacheStats;
@Autowired
@Qualifier("cacheRepositoryService")
protected RepositoryService repositoryService;
private long lastDummyResourceGroupMembersReadCount;
private long lastDummyResourceWriteOperationCount;
@Autowired protected Tracer tracer;
/**
* Task manager can be used directly in subclasses but prefer various provided methods
* like {@link #getTestTask()}, {@link #createPlainTask}, etc.
*/
@Autowired protected TaskManager taskManager;
@Autowired protected Protector protector;
@Autowired protected Clock clock;
@Autowired protected PrismContext prismContext;
@Autowired protected SchemaHelper schemaHelper;
@Autowired protected MatchingRuleRegistry matchingRuleRegistry;
@Autowired protected LocalizationService localizationService;
@Autowired(required = false)
@Qualifier("repoSimpleObjectResolver")
protected SimpleObjectResolver repoSimpleObjectResolver;
// Controllers for embedded OpenDJ and Derby. The abstract test will configure it, but
// it will not start only tests that need OpenDJ or derby should start it
protected static OpenDJController openDJController = new OpenDJController();
protected static DerbyController derbyController = new DerbyController();
/**
* Fast and simple way how to enable tracing of test methods.
* (Assuming that auto task management is enabled.)
*/
protected PredefinedTestMethodTracing predefinedTestMethodTracing;
private volatile boolean initSystemExecuted = false;
/**
* With TestNG+Spring we can use {@code PostConstruct} for class-wide initialization.
* All test methods run on a single instance (unlike with JUnit).
* Using {@code BeforeClass} is not good as the Spring wiring happens later.
* <p>
* There is still danger that annotation processor will run this multiple times
* for web/servlet-based tests, see text context attributes
* {@link DependencyInjectionTestExecutionListener#REINJECT_DEPENDENCIES_ATTRIBUTE}
* and {@link ServletTestExecutionListener#RESET_REQUEST_CONTEXT_HOLDER_ATTRIBUTE} for more.
* That's why we start with the guard enforcing once-only initSystem execution.
*/
@PostConstruct
public void initSystem() throws Exception {
if (initSystemExecuted) {
logger.trace("initSystem: already called for class {} - IGNORING", getClass().getName());
return;
}
initSystemExecuted = true;
// Check whether we are already initialized
assertNotNull("Repository is not wired properly", repositoryService);
assertNotNull("Task manager is not wired properly", taskManager);
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.setPrismContext(prismContext);
Task initTask = createPlainTask("INIT");
initTask.setChannel(SchemaConstants.CHANNEL_GUI_INIT_URI);
OperationResult result = initTask.getResult();
InternalMonitor.reset();
InternalsConfig.setPrismMonitoring(true);
prismContext.setMonitor(new InternalMonitor());
((LocalizationServiceImpl) localizationService).setOverrideLocale(Locale.US);
initSystem(initTask, result);
postInitSystem(initTask, result);
result.computeStatus();
IntegrationTestTools.display("initSystem result", result);
TestUtil.assertSuccessOrWarning("initSystem failed (result)", result, 1);
}
@Override
@Nullable
public MidpointTestContext getTestContext() {
return MidpointTestContextWithTask.get();
}
/**
* Test class initialization.
*/
protected void initSystem(Task task, OperationResult initResult) throws Exception {
// nothing by default
}
/**
* May be used to clean up initialized objects as all of the initialized objects should be
* available at this time.
*/
protected void postInitSystem(Task initTask, OperationResult initResult) throws Exception {
// Nothing to do by default
}
/**
* Creates test method context which includes customized {@link Task}
* (see {@link #createTask(String)}) and other test related info wrapped as
* {@link MidpointTestContextWithTask} and stores it in thread-local variable for future access.
* This implementation fully overrides version from {@link AbstractSpringTest}.
*/
@BeforeMethod
public void startTestContext(ITestResult testResult) throws SchemaException {
Class<?> testClass = testResult.getMethod().getTestClass().getRealClass();
String testMethodName = testResult.getMethod().getMethodName();
String testName = testClass.getSimpleName() + "." + testMethodName;
displayTestTitle(testName);
Task task = createTask(testMethodName);
// TODO inttest: add tracing facility - ideally without the need to create subresult
// OperationResult rootResult = task.getResult();
// TracingProfileType tracingProfile = getTestMethodTracingProfile();
// CompiledTracingProfile compiledTracingProfile = tracingProfile != null ?
// tracer.compileProfile(tracingProfile, rootResult) : null;
// OperationResult result = rootResult.subresult(task.getName() + "Run")
// .tracingProfile(compiledTracingProfile)
// .build();
// This is quite a hack. We need to provide traced result to all clients that need to access it via the task.
// (I.e. not via the test context.)
// task.setResult(result);
MidpointTestContextWithTask.create(testClass, testMethodName, task, task.getResult());
tracer.setTemplateParametersCustomizer(params -> {
params.put(MACRO_TEST_NAME_TRACER_PARAM, testName);
params.put(MACRO_TEST_NAME_SHORT_TRACER_PARAM, testMethodName);
});
}
/**
* Finish and destroy the test context, output duration and store the operation trace.
* This implementation fully overrides (without use) the one from {@link AbstractSpringTest}.
*/
@AfterMethod
public void finishTestContext(ITestResult testResult) {
MidpointTestContextWithTask context = MidpointTestContextWithTask.get();
MidpointTestContextWithTask.destroy(); // let's destroy it before anything else in this method
displayTestFooter(context.getTestName(), testResult);
Task task = context.getTask();
if (task != null) {
OperationResult result = context.getResult();
if (result != null) {
result.computeStatusIfUnknown();
if (result.isTraced()) {
System.out.println("Storing the trace.");
tracer.storeTrace(task, result, null);
}
task.getResult().computeStatusIfUnknown();
}
}
}
protected TracingProfileType getTestMethodTracingProfile() {
if (predefinedTestMethodTracing == null || predefinedTestMethodTracing == OFF) {
return null;
} else {
TracingProfileType profile;
switch (predefinedTestMethodTracing) {
case MODEL_LOGGING:
profile = createModelLoggingTracingProfile();
break;
case MODEL_WORKFLOW_LOGGING:
profile = createModelAndWorkflowLoggingTracingProfile();
break;
case MODEL_PROVISIONING_LOGGING:
profile = createModelAndProvisioningLoggingTracingProfile();
break;
default:
throw new AssertionError(predefinedTestMethodTracing.toString());
}
return profile
.fileNamePattern(TEST_METHOD_TRACING_FILENAME_PATTERN);
}
}
public PredefinedTestMethodTracing getPredefinedTestMethodTracing() {
return predefinedTestMethodTracing;
}
public void setPredefinedTestMethodTracing(PredefinedTestMethodTracing predefinedTestMethodTracing) {
this.predefinedTestMethodTracing = predefinedTestMethodTracing;
}
/**
* Returns default pre-created test-method-scoped {@link Task}.
* This fails if test-method context is not available.
*/
protected Task getTestTask() {
return MidpointTestContextWithTask.get().getTask();
}
/**
* Creates new {@link Task} with operation name prefixed with {@link #contextName()}.
* For many tests this is not necessary and the default test-method-scoped task
* that can be obtained with {@link #getTestTask()} should be enough.
* If more tasks are needed this method creates plain task without customization, see
* also {@link #createTask} for customized task.
* <p>
* This is useful for multi-threaded tests where we need local task.
* It is recommended to include method name and/or other info into parameter as only
* the current class name will be available as default contextual information - even
* this may be name of a inner class (e.g. anonymous runnable).
*/
protected Task createPlainTask(String operationName) {
String rootOpName = operationName != null
? contextName() + "." + operationName
: contextName();
return taskManager.createTaskInstance(rootOpName);
}
/**
* Creates new {@link Task} with {@link #contextName()} as root operation name.
*/
protected Task createPlainTask() {
return createPlainTask(null);
}
/**
* Just like {@link #createPlainTask(String)} but also calls overridable {@link #customizeTask}.
*/
protected Task createTask(String operationName) {
Task task = createPlainTask(operationName);
customizeTask(task);
return task;
}
/**
* Just like {@link #createPlainTask()} but also calls overridable {@link #customizeTask}.
*/
protected Task createTask() {
return createPlainTask(null);
}
/**
* Subclasses may override this if test task needs additional customization.
* Each task used or created by the test is customized - this applies to default
* method-scoped task and also to any task created by {@link #createTask(String)}.
*/
protected void customizeTask(Task task) {
// nothing by default
}
/**
* Creates new subresult for default pre-created test-method-scoped {@link Task}.
*/
protected OperationResult createSubresult(String subresultSuffix) {
return getTestOperationResult().createSubresult(getTestNameShort() + "." + subresultSuffix);
}
/**
* Returns default {@link OperationResult} for pre-created test-method-scoped {@link Task}.
* This result can be freely used in test for some "main scope", it is not asserted in any
* after method, only displayed.
*/
protected OperationResult getTestOperationResult() {
return MidpointTestContextWithTask.get().getResult();
}
public <C extends Containerable> S_ItemEntry deltaFor(Class<C> objectClass) throws SchemaException {
return prismContext.deltaFor(objectClass);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(String filePath,
OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return repoAddObjectFromFile(new File(filePath), parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(File file,
OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return repoAddObjectFromFile(file, false, parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAdd(TestResource resource, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, IOException, EncryptionException {
return repoAddObjectFromFile(resource.file, parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(
File file, @SuppressWarnings("unused") Class<T> type, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return repoAddObjectFromFile(file, false, parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(
File file, @SuppressWarnings("unused") Class<T> type, boolean metadata, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return repoAddObjectFromFile(file, metadata, parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(
File file, boolean metadata, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
OperationResult result = parentResult.createSubresult(AbstractIntegrationTest.class.getName()
+ ".repoAddObjectFromFile");
result.addParam("file", file.getPath());
logger.debug("addObjectFromFile: {}", file);
PrismObject<T> object;
try {
object = prismContext.parseObject(file);
} catch (SchemaException e) {
throw new SchemaException("Error parsing file " + file.getPath() + ": " + e.getMessage(), e);
}
if (metadata) {
addBasicMetadata(object);
}
logger.trace("Adding object:\n{}", object.debugDump());
repoAddObject(object, "from file " + file, result);
result.recordSuccess();
return object;
}
protected PrismObject<ShadowType> repoAddShadowFromFile(File file, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
OperationResult result = parentResult.createSubresult(AbstractIntegrationTest.class.getName()
+ ".repoAddShadowFromFile");
result.addParam("file", file.getPath());
logger.debug("addShadowFromFile: {}", file);
PrismObject<ShadowType> object = prismContext.parseObject(file);
PrismContainer<Containerable> attrCont = object.findContainer(ShadowType.F_ATTRIBUTES);
for (PrismProperty<?> attr : attrCont.getValue().getProperties()) {
if (attr.getDefinition() == null) {
ResourceAttributeDefinition<String> attrDef = ObjectFactory.createResourceAttributeDefinition(attr.getElementName(),
DOMUtil.XSD_STRING, prismContext);
attr.setDefinition((PrismPropertyDefinition) attrDef);
}
}
addBasicMetadata(object);
logger.trace("Adding object:\n{}", object.debugDump());
repoAddObject(object, "from file " + file, result);
result.recordSuccess();
return object;
}
protected <T extends ObjectType> void addBasicMetadata(PrismObject<T> object) {
// Add at least the very basic meta-data
MetadataType metaData = new MetadataType();
metaData.setCreateTimestamp(clock.currentTimeXMLGregorianCalendar());
object.asObjectable().setMetadata(metaData);
}
protected <T extends ObjectType> void repoAddObject(
PrismObject<T> object, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException {
repoAddObject(object, null, result);
}
protected <T extends ObjectType> void repoAddObject(
PrismObject<T> object, String contextDesc, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException {
if (object.canRepresent(TaskType.class)) {
Assert.assertNotNull(taskManager, "Task manager is not initialized");
try {
taskManager.addTask((PrismObject<TaskType>) object, result);
} catch (ObjectAlreadyExistsException | SchemaException ex) {
result.recordFatalError(ex.getMessage(), ex);
throw ex;
}
} else {
Assert.assertNotNull(repositoryService, "Repository service is not initialized");
try {
CryptoUtil.encryptValues(protector, object);
String oid = repositoryService.addObject(object, null, result);
object.setOid(oid);
} catch (ObjectAlreadyExistsException | SchemaException | EncryptionException ex) {
result.recordFatalError(ex.getMessage() + " while adding " + object + (contextDesc == null ? "" : " " + contextDesc), ex);
throw ex;
}
}
}
protected <T extends ObjectType> List<PrismObject<T>> repoAddObjectsFromFile(
String filePath, Class<T> type, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, IOException, EncryptionException {
return repoAddObjectsFromFile(new File(filePath), type, parentResult);
}
protected <T extends ObjectType> List<PrismObject<T>> repoAddObjectsFromFile(
File file, Class<T> type, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, IOException, EncryptionException {
OperationResult result = parentResult.createSubresult(AbstractIntegrationTest.class.getName()
+ ".addObjectsFromFile");
result.addParam("file", file.getPath());
logger.trace("addObjectsFromFile: {}", file);
List<PrismObject<T>> objects = (List) prismContext.parserFor(file).parseObjects();
for (PrismObject<T> object : objects) {
try {
repoAddObject(object, result);
} catch (ObjectAlreadyExistsException e) {
throw new ObjectAlreadyExistsException(e.getMessage() + " while adding " + object + " from file " + file, e);
} catch (SchemaException e) {
throw new SchemaException(e.getMessage() + " while adding " + object + " from file " + file, e);
} catch (EncryptionException e) {
throw new EncryptionException(e.getMessage() + " while adding " + object + " from file " + file, e);
}
}
result.recordSuccess();
return objects;
}
// these objects can be of various types
protected List<PrismObject> repoAddObjectsFromFile(File file, OperationResult parentResult)
throws SchemaException, ObjectAlreadyExistsException, IOException, EncryptionException {
OperationResult result = parentResult.createSubresult(
AbstractIntegrationTest.class.getName() + ".addObjectsFromFile");
result.addParam("file", file.getPath());
logger.trace("addObjectsFromFile: {}", file);
List<PrismObject> objects = (List) prismContext.parserFor(file).parseObjects();
for (PrismObject object : objects) {
try {
repoAddObject(object, result);
} catch (ObjectAlreadyExistsException e) {
throw new ObjectAlreadyExistsException(e.getMessage() + " while adding " + object + " from file " + file, e);
} catch (SchemaException e) {
throw new SchemaException(e.getMessage() + " while adding " + object + " from file " + file, e);
} catch (EncryptionException e) {
throw new EncryptionException(e.getMessage() + " while adding " + object + " from file " + file, e);
}
}
result.recordSuccess();
return objects;
}
protected <T extends ObjectType> T parseObjectTypeFromFile(String fileName, Class<T> clazz) throws SchemaException, IOException {
return parseObjectType(new File(fileName), clazz);
}
protected <T extends ObjectType> T parseObjectType(File file) throws SchemaException, IOException {
PrismObject<T> prismObject = prismContext.parseObject(file);
return prismObject.asObjectable();
}
protected <T extends ObjectType> T parseObjectType(File file, Class<T> clazz) throws SchemaException, IOException {
PrismObject<T> prismObject = prismContext.parseObject(file);
return prismObject.asObjectable();
}
protected static <T> T unmarshalValueFromFile(File file, Class<T> clazz)
throws IOException, SchemaException {
return PrismTestUtil.parseAnyValue(file);
}
protected static <T> T unmarshalValueFromFile(String filePath, Class<T> clazz)
throws IOException, SchemaException {
return PrismTestUtil.parseAnyValue(new File(filePath));
}
protected static ObjectType unmarshalValueFromFile(String filePath)
throws IOException, SchemaException {
return unmarshalValueFromFile(filePath, ObjectType.class);
}
protected PrismObject<ResourceType> addResourceFromFile(
File file, String connectorType, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return addResourceFromFile(file, connectorType, false, result);
}
protected PrismObject<ResourceType> addResourceFromFile(
File file, String connectorType, boolean overwrite, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return addResourceFromFile(file, Collections.singletonList(connectorType), overwrite, result);
}
protected PrismObject<ResourceType> addResourceFromFile(
File file, List<String> connectorTypes, boolean overwrite, OperationResult result)
throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
logger.trace("addObjectFromFile: {}, connector types {}", file, connectorTypes);
PrismObject<ResourceType> resource = prismContext.parseObject(file);
return addResourceFromObject(resource, connectorTypes, overwrite, result);
}
@NotNull
protected PrismObject<ResourceType> addResourceFromObject(PrismObject<ResourceType> resource, List<String> connectorTypes,
boolean overwrite, OperationResult result)
throws SchemaException, EncryptionException,
ObjectAlreadyExistsException {
for (int i = 0; i < connectorTypes.size(); i++) {
String type = connectorTypes.get(i);
if (i == 0) {
fillInConnectorRef(resource, type, result);
} else {
fillInAdditionalConnectorRef(resource, i - 1, type, result);
}
}
CryptoUtil.encryptValues(protector, resource);
display("Adding resource ", resource);
RepoAddOptions options = null;
if (overwrite) {
options = RepoAddOptions.createOverwrite();
}
String oid = repositoryService.addObject(resource, options, result);
resource.setOid(oid);
return resource;
}
protected PrismObject<ConnectorType> findConnectorByType(String connectorType, OperationResult result)
throws SchemaException {
ObjectQuery query = prismContext.queryFor(ConnectorType.class)
.item(ConnectorType.F_CONNECTOR_TYPE).eq(connectorType)
.build();
List<PrismObject<ConnectorType>> connectors = repositoryService.searchObjects(ConnectorType.class, query, null, result);
if (connectors.size() != 1) {
throw new IllegalStateException("Cannot find connector type " + connectorType + ", got " + connectors);
}
return connectors.get(0);
}
protected PrismObject<ConnectorType> findConnectorByTypeAndVersion(String connectorType, String connectorVersion, OperationResult result)
throws SchemaException {
ObjectQuery query = prismContext.queryFor(ConnectorType.class)
.item(ConnectorType.F_CONNECTOR_TYPE).eq(connectorType)
.and().item(ConnectorType.F_CONNECTOR_VERSION).eq(connectorVersion)
.build();
List<PrismObject<ConnectorType>> connectors = repositoryService.searchObjects(ConnectorType.class, query, null, result);
if (connectors.size() != 1) {
throw new IllegalStateException("Cannot find connector type " + connectorType + ", version " + connectorVersion + ", got "
+ connectors);
}
return connectors.get(0);
}
protected void fillInConnectorRef(PrismObject<ResourceType> resource, String connectorType, OperationResult result)
throws SchemaException {
ResourceType resourceType = resource.asObjectable();
PrismObject<ConnectorType> connector = findConnectorByType(connectorType, result);
if (resourceType.getConnectorRef() == null) {
resourceType.setConnectorRef(new ObjectReferenceType());
}
resourceType.getConnectorRef().setOid(connector.getOid());
resourceType.getConnectorRef().setType(ObjectTypes.CONNECTOR.getTypeQName());
}
protected void fillInAdditionalConnectorRef(PrismObject<ResourceType> resource,
String connectorName, String connectorType, OperationResult result)
throws SchemaException {
ResourceType resourceType = resource.asObjectable();
PrismObject<ConnectorType> connectorPrism = findConnectorByType(connectorType, result);
for (ConnectorInstanceSpecificationType additionalConnector : resourceType.getAdditionalConnector()) {
if (connectorName.equals(additionalConnector.getName())) {
ObjectReferenceType ref = new ObjectReferenceType().oid(connectorPrism.getOid());
additionalConnector.setConnectorRef(ref);
}
}
}
protected void fillInAdditionalConnectorRef(PrismObject<ResourceType> resource, int connectorIndex, String connectorType, OperationResult result)
throws SchemaException {
ResourceType resourceType = resource.asObjectable();
PrismObject<ConnectorType> connectorPrism = findConnectorByType(connectorType, result);
ConnectorInstanceSpecificationType additionalConnector = resourceType.getAdditionalConnector().get(connectorIndex);
ObjectReferenceType ref = new ObjectReferenceType().oid(connectorPrism.getOid());
additionalConnector.setConnectorRef(ref);
}
protected SystemConfigurationType getSystemConfiguration() throws SchemaException {
OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName() + ".getSystemConfiguration");
try {
PrismObject<SystemConfigurationType> sysConf = repositoryService.getObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result);
result.computeStatus();
TestUtil.assertSuccess("getObject(systemConfig) not success", result);
return sysConf.asObjectable();
} catch (ObjectNotFoundException e) {
// No big deal
return null;
}
}
protected void assumeAssignmentPolicy(AssignmentPolicyEnforcementType policy) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
SystemConfigurationType systemConfiguration = getSystemConfiguration();
AssignmentPolicyEnforcementType currentPolicy = getAssignmentPolicyEnforcementType(systemConfiguration);
if (currentPolicy == policy) {
return;
}
ProjectionPolicyType syncSettings = new ProjectionPolicyType();
syncSettings.setAssignmentPolicyEnforcement(policy);
applySyncSettings(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), SchemaConstants.C_SYSTEM_CONFIGURATION_GLOBAL_ACCOUNT_SYNCHRONIZATION_SETTINGS, syncSettings);
}
// very limited approach -- assumes that we set conflict resolution on a global level only
protected void assumeConflictResolutionAction(ConflictResolutionActionType action) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
SystemConfigurationType systemConfiguration = getSystemConfiguration();
List<ObjectPolicyConfigurationType> current = new ArrayList<>();
List<ObjectPolicyConfigurationType> currentForTasks = new ArrayList<>();
final ConflictResolutionActionType actionForTasks = ConflictResolutionActionType.NONE;
for (ObjectPolicyConfigurationType c : systemConfiguration.getDefaultObjectPolicyConfiguration()) {
if (c.getType() == null && c.getSubtype() == null && c.getConflictResolution() != null) {
current.add(c);
} else if (QNameUtil.match(c.getType(), TaskType.COMPLEX_TYPE) && c.getSubtype() == null && c.getConflictResolution() != null) {
currentForTasks.add(c);
}
}
List<ItemDelta<?, ?>> itemDeltas = new ArrayList<>();
if (current.size() != 1 || current.get(0).getConflictResolution().getAction() != action) {
ObjectPolicyConfigurationType newPolicy = new ObjectPolicyConfigurationType(prismContext)
.beginConflictResolution()
.action(action)
.end();
itemDeltas.add(prismContext.deltaFor(SystemConfigurationType.class)
.item(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION)
.add(newPolicy)
.deleteRealValues(current)
.asItemDelta());
}
if (currentForTasks.size() != 1 || currentForTasks.get(0).getConflictResolution().getAction() != actionForTasks) {
ObjectPolicyConfigurationType newPolicyForTasks = new ObjectPolicyConfigurationType(prismContext)
.type(TaskType.COMPLEX_TYPE)
.beginConflictResolution()
.action(actionForTasks)
.end();
itemDeltas.add(prismContext.deltaFor(SystemConfigurationType.class)
.item(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION)
.add(newPolicyForTasks)
.deleteRealValues(currentForTasks)
.asItemDelta());
}
if (!itemDeltas.isEmpty()) {
OperationResult result = new OperationResult("assumeConflictResolutionAction");
repositoryService.modifyObject(SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), itemDeltas, result);
invalidateSystemObjectsCache();
display("Applying conflict resolution action result", result);
result.computeStatus();
TestUtil.assertSuccess("Applying conflict resolution action failed (result)", result);
}
}
protected void assumeResourceAssigmentPolicy(
String resourceOid, AssignmentPolicyEnforcementType policy, boolean legalize)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
ProjectionPolicyType syncSettings = new ProjectionPolicyType();
syncSettings.setAssignmentPolicyEnforcement(policy);
syncSettings.setLegalize(legalize);
applySyncSettings(ResourceType.class, resourceOid, ResourceType.F_PROJECTION, syncSettings);
}
protected void deleteResourceAssigmentPolicy(
String oid, AssignmentPolicyEnforcementType policy, boolean legalize)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
ProjectionPolicyType syncSettings = new ProjectionPolicyType();
syncSettings.setAssignmentPolicyEnforcement(policy);
syncSettings.setLegalize(legalize);
ContainerDelta<ProjectionPolicyType> deleteAssigmentEnforcement = prismContext.deltaFactory().container()
.createModificationDelete(ResourceType.F_PROJECTION, ResourceType.class,
syncSettings.clone());
Collection<ItemDelta<?, ?>> modifications = new ArrayList<>();
modifications.add(deleteAssigmentEnforcement);
OperationResult result = createOperationResult("Applying sync settings");
repositoryService.modifyObject(ResourceType.class, oid, modifications, result);
display("Applying sync settings result", result);
result.computeStatus();
TestUtil.assertSuccess("Applying sync settings failed (result)", result);
}
protected AssignmentPolicyEnforcementType getAssignmentPolicyEnforcementType(SystemConfigurationType systemConfiguration) {
ProjectionPolicyType globalAccountSynchronizationSettings = systemConfiguration.getGlobalAccountSynchronizationSettings();
if (globalAccountSynchronizationSettings == null) {
return null;
}
return globalAccountSynchronizationSettings.getAssignmentPolicyEnforcement();
}
protected void applySyncSettings(Class clazz, String oid, ItemName itemName, ProjectionPolicyType syncSettings)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
PrismObjectDefinition<?> objectDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(clazz);
Collection<? extends ItemDelta> modifications = prismContext.deltaFactory().container()
.createModificationReplaceContainerCollection(itemName, objectDefinition, syncSettings.asPrismContainerValue());
OperationResult result = new OperationResult("Applying sync settings");
repositoryService.modifyObject(clazz, oid, modifications, result);
invalidateSystemObjectsCache();
display("Applying sync settings result", result);
result.computeStatus();
TestUtil.assertSuccess("Applying sync settings failed (result)", result);
}
protected void invalidateSystemObjectsCache() {
// Nothing to do here. For subclasses in model-common and higher components.
}
protected void assertNoChanges(ObjectDelta<?> delta) {
assertNull("Unexpected changes: " + delta, delta);
}
protected void assertNoChanges(String desc, ObjectDelta<?> delta) {
assertNull("Unexpected changes in " + desc + ": " + delta, delta);
}
protected <F extends FocusType> void assertEffectiveActivation(PrismObject<F> focus, ActivationStatusType expected) {
ActivationType activationType = focus.asObjectable().getActivation();
assertNotNull("No activation in " + focus, activationType);
assertEquals("Wrong effectiveStatus in activation in " + focus, expected, activationType.getEffectiveStatus());
}
protected <F extends FocusType> void assertEffectiveActivation(AssignmentType assignmentType, ActivationStatusType expected) {
ActivationType activationType = assignmentType.getActivation();
assertNotNull("No activation in " + assignmentType, activationType);
assertEquals("Wrong effectiveStatus in activation in " + assignmentType, expected, activationType.getEffectiveStatus());
}
protected <F extends FocusType> void assertValidityStatus(PrismObject<F> focus, TimeIntervalStatusType expected) {
ActivationType activationType = focus.asObjectable().getActivation();
assertNotNull("No activation in " + focus, activationType);
assertEquals("Wrong validityStatus in activation in " + focus, expected, activationType.getValidityStatus());
}
/**
* Deprecated: use ShadowAsserter instead.
*/
@Deprecated
protected void assertShadowSanity(PrismObject<? extends ShadowType> shadow) {
assertObjectSanity(shadow);
}
/**
* Deprecated: use ObjectAsserter instead.
*/
@Deprecated
protected void assertObjectSanity(PrismObject<? extends ObjectType> object) {
new PrismObjectAsserter<>(object).assertSanity();
}
protected ResourceAsserter<Void> assertResource(PrismObject<ResourceType> resource, String message) {
ResourceAsserter<Void> asserter = ResourceAsserter.forResource(resource, message);
initializeAsserter(asserter);
asserter.display();
return asserter;
}
protected void assertUser(PrismObject<UserType> user, String oid, String name, String fullName, String givenName, String familyName) {
assertUser(user, oid, name, fullName, givenName, familyName, null);
}
protected void assertUser(PrismObject<UserType> user, String oid, String name, String fullName, String givenName, String familyName, String location) {
assertObjectSanity(user);
UserType userType = user.asObjectable();
if (oid != null) {
assertEquals("Wrong " + user + " OID (prism)", oid, user.getOid());
assertEquals("Wrong " + user + " OID (jaxb)", oid, userType.getOid());
}
PrismAsserts.assertEqualsPolyString("Wrong " + user + " name", name, userType.getName());
PrismAsserts.assertEqualsPolyString("Wrong " + user + " fullName", fullName, userType.getFullName());
PrismAsserts.assertEqualsPolyString("Wrong " + user + " givenName", givenName, userType.getGivenName());
PrismAsserts.assertEqualsPolyString("Wrong " + user + " familyName", familyName, userType.getFamilyName());
if (location != null) {
PrismAsserts.assertEqualsPolyString("Wrong " + user + " location", location,
userType.getLocality());
}
}
protected <O extends ObjectType> void assertSubtype(PrismObject<O> object, String subtype) {
assertTrue("Object " + object + " does not have subtype " + subtype, FocusTypeUtil.hasSubtype(object, subtype));
}
protected void assertShadowCommon(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType, QName objectClass) throws SchemaException {
assertShadowCommon(accountShadow, oid, username, resourceType, objectClass, null, false);
}
protected void assertAccountShadowCommon(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType) throws SchemaException {
assertShadowCommon(accountShadow, oid, username, resourceType, getAccountObjectClass(resourceType), null, false);
}
protected void assertAccountShadowCommon(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType,
MatchingRule<String> nameMatchingRule, boolean requireNormalizedIdentfiers) throws SchemaException {
assertShadowCommon(accountShadow, oid, username, resourceType, getAccountObjectClass(resourceType), nameMatchingRule, requireNormalizedIdentfiers);
}
protected QName getAccountObjectClass(ResourceType resourceType) {
return new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "AccountObjectClass");
}
protected QName getGroupObjectClass(ResourceType resourceType) {
return new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "GroupObjectClass");
}
protected void assertShadowCommon(PrismObject<ShadowType> shadow, String oid, String username, ResourceType resourceType,
QName objectClass, MatchingRule<String> nameMatchingRule, boolean requireNormalizedIdentfiers) throws SchemaException {
assertShadowCommon(shadow, oid, username, resourceType, objectClass, nameMatchingRule, requireNormalizedIdentfiers, false);
}
protected void assertShadowCommon(PrismObject<ShadowType> shadow, String oid, String username, ResourceType resourceType,
QName objectClass, final MatchingRule<String> nameMatchingRule, boolean requireNormalizedIdentfiers, boolean useMatchingRuleForShadowName) throws SchemaException {
assertShadowSanity(shadow);
if (oid != null) {
assertEquals("Shadow OID mismatch (prism)", oid, shadow.getOid());
}
ShadowType resourceObjectShadowType = shadow.asObjectable();
if (oid != null) {
assertEquals("Shadow OID mismatch (jaxb)", oid, resourceObjectShadowType.getOid());
}
assertEquals("Shadow objectclass", objectClass, resourceObjectShadowType.getObjectClass());
assertEquals("Shadow resourceRef OID", resourceType.getOid(), shadow.asObjectable().getResourceRef().getOid());
PrismContainer<Containerable> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES);
assertNotNull("Null attributes in shadow for " + username, attributesContainer);
assertFalse("Empty attributes in shadow for " + username, attributesContainer.isEmpty());
if (useMatchingRuleForShadowName) {
MatchingRule<PolyString> polyMatchingRule = new MatchingRule<PolyString>() {
@Override
public QName getName() {
return nameMatchingRule.getName();
}
@Override
public boolean isSupported(QName xsdType) {
return nameMatchingRule.isSupported(xsdType);
}
@Override
public boolean match(PolyString a, PolyString b) throws SchemaException {
return nameMatchingRule.match(a.getOrig(), b.getOrig());
}
@Override
public boolean matchRegex(PolyString a, String regex) throws SchemaException {
return nameMatchingRule.matchRegex(a.getOrig(), regex);
}
@Override
public PolyString normalize(PolyString original) throws SchemaException {
return new PolyString(nameMatchingRule.normalize(original.getOrig()));
}