/
AbstractIntegrationTest.java
2298 lines (1975 loc) · 106 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-2017 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.midpoint.test;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertFalse;
import static org.testng.AssertJUnit.assertNull;
import static org.testng.AssertJUnit.assertTrue;
import com.evolveum.icf.dummy.resource.DummyResource;
import com.evolveum.midpoint.common.Clock;
import com.evolveum.midpoint.common.LocalizationService;
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.ConsistencyCheckScope;
import com.evolveum.midpoint.prism.Containerable;
import com.evolveum.midpoint.prism.ExpressionWrapper;
import com.evolveum.midpoint.prism.Item;
import com.evolveum.midpoint.prism.ItemDefinition;
import com.evolveum.midpoint.prism.PrismContainer;
import com.evolveum.midpoint.prism.PrismContext;
import com.evolveum.midpoint.prism.PrismObject;
import com.evolveum.midpoint.prism.PrismObjectDefinition;
import com.evolveum.midpoint.prism.PrismProperty;
import com.evolveum.midpoint.prism.PrismPropertyDefinition;
import com.evolveum.midpoint.prism.PrismPropertyValue;
import com.evolveum.midpoint.prism.PrismReference;
import com.evolveum.midpoint.prism.PrismReferenceValue;
import com.evolveum.midpoint.prism.PrismValue;
import com.evolveum.midpoint.prism.crypto.EncryptionException;
import com.evolveum.midpoint.prism.crypto.Protector;
import com.evolveum.midpoint.prism.delta.ItemDelta;
import com.evolveum.midpoint.prism.delta.ObjectDelta;
import com.evolveum.midpoint.prism.delta.PropertyDelta;
import com.evolveum.midpoint.prism.delta.builder.DeltaBuilder;
import com.evolveum.midpoint.prism.match.MatchingRule;
import com.evolveum.midpoint.prism.match.MatchingRuleRegistry;
import com.evolveum.midpoint.prism.path.ItemPath;
import com.evolveum.midpoint.prism.path.NameItemPathSegment;
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.builder.QueryBuilder;
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.repo.api.RepoAddOptions;
import com.evolveum.midpoint.repo.api.RepositoryService;
import com.evolveum.midpoint.schema.MidPointPrismContextFactory;
import com.evolveum.midpoint.schema.ResultHandler;
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.*;
import com.evolveum.midpoint.schema.result.OperationResult;
import com.evolveum.midpoint.schema.result.OperationResultStatus;
import com.evolveum.midpoint.schema.util.FocusTypeUtil;
import com.evolveum.midpoint.schema.util.ObjectTypeUtil;
import com.evolveum.midpoint.schema.util.ResourceTypeUtil;
import com.evolveum.midpoint.schema.util.ShadowUtil;
import com.evolveum.midpoint.task.api.Task;
import com.evolveum.midpoint.task.api.TaskManager;
import com.evolveum.midpoint.test.ldap.OpenDJController;
import com.evolveum.midpoint.test.util.DerbyController;
import com.evolveum.midpoint.test.util.MidPointTestConstants;
import com.evolveum.midpoint.test.util.MultithreadRunner;
import com.evolveum.midpoint.test.util.ParallelTestThread;
import com.evolveum.midpoint.test.util.TestUtil;
import com.evolveum.midpoint.tools.testng.CurrentTestResultHolder;
import com.evolveum.midpoint.util.*;
import com.evolveum.midpoint.util.exception.*;
import com.evolveum.midpoint.util.logging.Trace;
import com.evolveum.midpoint.util.logging.TraceManager;
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 org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.SystemUtils;
import org.opends.server.types.Entry;
import org.opends.server.types.SearchResultEntry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.encoding.LdapShaPasswordEncoder;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.AssertJUnit;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.w3c.dom.Element;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.datatype.XMLGregorianCalendar;
import javax.xml.namespace.QName;
import java.io.File;
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.stream.Collectors;
import static org.testng.AssertJUnit.assertNotNull;
/**
* @author Radovan Semancik
*
*/
@Listeners({ CurrentTestResultHolder.class })
public abstract class AbstractIntegrationTest extends AbstractTestNGSpringContextTests {
public static final String COMMON_DIR_NAME = "common";
@Deprecated
public static final String COMMON_DIR_PATH = MidPointTestConstants.TEST_RESOURCES_PATH + "/" + COMMON_DIR_NAME;
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";
private static final Trace LOGGER = TraceManager.getTrace(AbstractIntegrationTest.class);
protected static final Random RND = new Random();
// 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;
protected static Set<Class> initializedClasses = new HashSet<Class>();
private long lastDummyResourceGroupMembersReadCount;
private long lastDummyResourceWriteOperationCount;
@Autowired protected TaskManager taskManager;
@Autowired protected Protector protector;
@Autowired protected Clock clock;
@Autowired protected PrismContext prismContext;
@Autowired protected MatchingRuleRegistry matchingRuleRegistry;
@Autowired protected LocalizationService localizationService;
// 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();
// We need this complicated init as we want to initialize repo only once.
// JUnit will
// create new class instance for every test, so @Before and @PostInit will
// not work
// directly. We also need to init the repo after spring autowire is done, so
// @BeforeClass won't work either.
@BeforeMethod
public void initSystemConditional() throws Exception {
// Check whether we are already initialized
assertNotNull("Repository is not wired properly", repositoryService);
assertNotNull("Task manager is not wired properly", taskManager);
LOGGER.trace("initSystemConditional: {} systemInitialized={}", this.getClass(), isSystemInitialized());
if (!isSystemInitialized()) {
PrettyPrinter.setDefaultNamespacePrefix(MidPointConstants.NS_MIDPOINT_PUBLIC_PREFIX);
PrismTestUtil.resetPrismContext(MidPointPrismContextFactory.FACTORY);
LOGGER.trace("initSystemConditional: invoking initSystem");
Task initTask = taskManager.createTaskInstance(this.getClass().getName() + ".initSystem");
initTask.setChannel(SchemaConstants.CHANNEL_GUI_INIT_URI);
OperationResult result = initTask.getResult();
InternalMonitor.reset();
InternalsConfig.setPrismMonitoring(true);
prismContext.setMonitor(new InternalMonitor());
initSystem(initTask, result);
postInitSystem(initTask, result);
result.computeStatus();
IntegrationTestTools.display("initSystem result", result);
TestUtil.assertSuccessOrWarning("initSystem failed (result)", result, 1);
setSystemInitialized();
}
}
protected boolean isSystemInitialized() {
return initializedClasses.contains(this.getClass());
}
private void setSystemInitialized() {
initializedClasses.add(this.getClass());
}
protected void unsetSystemInitialized() {
initializedClasses.remove(this.getClass());
}
abstract public void initSystem(Task initTask, OperationResult initResult) throws Exception;
/**
* 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
};
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> repoAddObjectFromFile(File file, Class<T> type,
OperationResult parentResult) throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return repoAddObjectFromFile(file, false, parentResult);
}
protected <T extends ObjectType> PrismObject<T> repoAddObjectFromFile(File file, 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 = new ResourceAttributeDefinitionImpl<>(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 ex) {
result.recordFatalError(ex.getMessage(), ex);
throw ex;
} catch (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 ex){
result.recordFatalError(ex.getMessage()+" while adding "+object+(contextDesc==null?"":" "+contextDesc), ex);
throw ex;
} catch(SchemaException ex){
result.recordFatalError(ex.getMessage()+" while adding "+object+(contextDesc==null?"":" "+contextDesc), ex);
throw ex;
} catch (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 {
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 {
OperationResult result = parentResult.createSubresult(AbstractIntegrationTest.class.getName()
+ ".addObjectsFromFile");
result.addParam("file", file.getPath());
LOGGER.trace("addObjectsFromFile: {}", file);
List<PrismObject<T>> objects = (List) PrismTestUtil.parseObjects(file);
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) {
new SchemaException(e.getMessage()+" while adding "+object+" from file "+file, e);
} catch (EncryptionException e) {
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 {
OperationResult result = parentResult.createSubresult(AbstractIntegrationTest.class.getName()
+ ".addObjectsFromFile");
result.addParam("file", file.getPath());
LOGGER.trace("addObjectsFromFile: {}", file);
List<PrismObject> objects = (List) PrismTestUtil.parseObjects(file);
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) {
new SchemaException(e.getMessage()+" while adding "+object+" from file "+file, e);
} catch (EncryptionException e) {
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 unmarshallValueFromFile(File file, Class<T> clazz)
throws IOException, JAXBException, SchemaException {
return PrismTestUtil.parseAnyValue(file);
}
protected static <T> T unmarshallValueFromFile(String filePath, Class<T> clazz)
throws IOException, JAXBException, SchemaException {
return PrismTestUtil.parseAnyValue(new File(filePath));
}
protected static ObjectType unmarshallValueFromFile(String filePath) throws IOException,
JAXBException, SchemaException {
return unmarshallValueFromFile(filePath, ObjectType.class);
}
protected PrismObject<ResourceType> addResourceFromFile(File file, String connectorType, OperationResult result)
throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
return addResourceFromFile(file, connectorType, false, result);
}
protected PrismObject<ResourceType> addResourceFromFile(File file, String connectorType, boolean overwrite, OperationResult result)
throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException {
LOGGER.trace("addObjectFromFile: {}, connector type {}", file, connectorType);
PrismObject<ResourceType> resource = prismContext.parseObject(file);
fillInConnectorRef(resource, connectorType, 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 = QueryBuilder.queryFor(ConnectorType.class, prismContext)
.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 = QueryBuilder.queryFor(ConnectorType.class, prismContext)
.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 SystemConfigurationType getSystemConfiguration() throws ObjectNotFoundException, 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 ACTION_FOR_TASKS = 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(DeltaBuilder.deltaFor(SystemConfigurationType.class, prismContext)
.item(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION)
.add(newPolicy)
.deleteRealValues(current)
.asItemDelta());
}
if (currentForTasks.size() != 1 || currentForTasks.get(0).getConflictResolution().getAction() != ACTION_FOR_TASKS) {
ObjectPolicyConfigurationType newPolicyForTasks = new ObjectPolicyConfigurationType(prismContext)
.type(TaskType.COMPLEX_TYPE)
.beginConflictResolution()
.action(ACTION_FOR_TASKS)
.end();
itemDeltas.add(DeltaBuilder.deltaFor(SystemConfigurationType.class, prismContext)
.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(Boolean.valueOf(legalize));
applySyncSettings(ResourceType.class, resourceOid, ResourceType.F_PROJECTION, syncSettings);
}
protected void deleteResourceAssigmentPolicy(String oid, AssignmentPolicyEnforcementType policy, boolean legalize) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException{
PrismObjectDefinition<ResourceType> objectDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(ResourceType.class);
ProjectionPolicyType syncSettings = new ProjectionPolicyType();
syncSettings.setAssignmentPolicyEnforcement(policy);
syncSettings.setLegalize(Boolean.valueOf(legalize));
ItemDelta deleteAssigmentEnforcement = PropertyDelta
.createModificationDeleteProperty(new ItemPath(ResourceType.F_PROJECTION),
objectDefinition.findPropertyDefinition(ResourceType.F_PROJECTION), syncSettings);
Collection<ItemDelta> modifications = new ArrayList<ItemDelta>();
modifications.add(deleteAssigmentEnforcement);
OperationResult result = new OperationResult("Aplying sync settings");
repositoryService.modifyObject(ResourceType.class, oid, modifications, result);
display("Aplying sync settings result", result);
result.computeStatus();
TestUtil.assertSuccess("Aplying 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, QName path, ProjectionPolicyType syncSettings)
throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException {
PrismObjectDefinition<?> objectDefinition = prismContext.getSchemaRegistry()
.findObjectDefinitionByCompileTimeClass(clazz);
Collection<? extends ItemDelta> modifications = PropertyDelta
.createModificationReplacePropertyCollection(
path,
objectDefinition, syncSettings);
OperationResult result = new OperationResult("Aplying sync settings");
repositoryService.modifyObject(clazz, oid, modifications, result);
invalidateSystemObjectsCache();
display("Aplying sync settings result", result);
result.computeStatus();
TestUtil.assertSuccess("Aplying 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());
}
protected void assertShadow(PrismObject<? extends ShadowType> shadow) {
assertObject(shadow);
}
protected void assertObject(PrismObject<? extends ObjectType> object) {
object.checkConsistence(true, true, ConsistencyCheckScope.THOROUGH);
assertTrue("Incomplete definition in "+object, object.hasCompleteDefinition());
assertFalse("No OID", StringUtils.isEmpty(object.getOid()));
assertNotNull("Null name in "+object, object.asObjectable().getName());
}
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) {
assertObject(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 {
assertShadow(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()));
}
};
PrismAsserts.assertPropertyValueMatch(shadow, ShadowType.F_NAME, polyMatchingRule, PrismTestUtil.createPolyString(username));
} else {
PrismAsserts.assertPropertyValue(shadow, ShadowType.F_NAME, PrismTestUtil.createPolyString(username));
}
RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceType);
ObjectClassComplexTypeDefinition ocDef = rSchema.findObjectClassDefinition(objectClass);
if (ocDef.getSecondaryIdentifiers().isEmpty()) {
ResourceAttributeDefinition idDef = ocDef.getPrimaryIdentifiers().iterator().next();
PrismProperty<String> idProp = attributesContainer.findProperty(idDef.getName());
assertNotNull("No primary identifier ("+idDef.getName()+") attribute in shadow for "+username, idProp);
if (nameMatchingRule == null) {
assertEquals("Unexpected primary identifier in shadow for "+username, username, idProp.getRealValue());
} else {
if (requireNormalizedIdentfiers) {
assertEquals("Unexpected primary identifier in shadow for "+username, nameMatchingRule.normalize(username), idProp.getRealValue());
} else {
PrismAsserts.assertEquals("Unexpected primary identifier in shadow for "+username, nameMatchingRule, username, idProp.getRealValue());
}
}
} else {
boolean found = false;
String expected = username;
if (requireNormalizedIdentfiers && nameMatchingRule != null) {
expected = nameMatchingRule.normalize(username);
}
List<String> wasValues = new ArrayList<>();
for (ResourceAttributeDefinition idSecDef: ocDef.getSecondaryIdentifiers()) {
PrismProperty<String> idProp = attributesContainer.findProperty(idSecDef.getName());
wasValues.addAll(idProp.getRealValues());
assertNotNull("No secondary identifier ("+idSecDef.getName()+") attribute in shadow for "+username, idProp);
if (nameMatchingRule == null) {
if (username.equals(idProp.getRealValue())) {
found = true;
break;
}
} else {
if (requireNormalizedIdentfiers) {
if (expected.equals(idProp.getRealValue())) {
found = true;
break;
}
} else if (nameMatchingRule.match(username, idProp.getRealValue())) {
found = true;
break;
}
}
}
if (!found) {
fail("Unexpected secondary identifier in shadow for "+username+", expected "+expected+" but was "+wasValues);
}
}
}
protected void assertShadowSecondaryIdentifier(PrismObject<ShadowType> shadow, String expectedIdentifier, ResourceType resourceType, MatchingRule<String> nameMatchingRule) throws SchemaException {
RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceType);
ObjectClassComplexTypeDefinition ocDef = rSchema.findObjectClassDefinition(shadow.asObjectable().getObjectClass());
ResourceAttributeDefinition idSecDef = ocDef.getSecondaryIdentifiers().iterator().next();
PrismContainer<Containerable> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES);
PrismProperty<String> idProp = attributesContainer.findProperty(idSecDef.getName());
assertNotNull("No secondary identifier ("+idSecDef.getName()+") attribute in shadow for "+expectedIdentifier, idProp);
if (nameMatchingRule == null) {
assertEquals("Unexpected secondary identifier in shadow for "+expectedIdentifier, expectedIdentifier, idProp.getRealValue());
} else {
PrismAsserts.assertEquals("Unexpected secondary identifier in shadow for "+expectedIdentifier, nameMatchingRule, expectedIdentifier, idProp.getRealValue());
}
}
protected void assertShadowName(PrismObject<ShadowType> shadow, String expectedName) {
PrismAsserts.assertEqualsPolyString("Shadow name is wrong in "+shadow, expectedName, shadow.asObjectable().getName());
}
protected void assertShadowName(ShadowType shadowType, String expectedName) {
assertShadowName(shadowType.asPrismObject(), expectedName);
}
protected void assertShadowRepo(String oid, String username, ResourceType resourceType, QName objectClass) throws ObjectNotFoundException, SchemaException {
OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName()+".assertShadowRepo");
PrismObject<ShadowType> shadow = repositoryService.getObject(ShadowType.class, oid, null, result);
result.computeStatus();
TestUtil.assertSuccess(result);
assertShadowRepo(shadow, oid, username, resourceType, objectClass);
}
protected void assertAccountShadowRepo(String oid, String username, ResourceType resourceType) throws ObjectNotFoundException, SchemaException {
assertShadowRepo(oid,username,resourceType,getAccountObjectClass(resourceType));
}
protected void assertShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType,
QName objectClass) throws SchemaException {
assertShadowRepo(accountShadow, oid, username, resourceType, objectClass, null);
}
protected void assertAccountShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType) throws SchemaException {
assertShadowRepo(accountShadow, oid, username, resourceType, getAccountObjectClass(resourceType), null);
}
protected void assertAccountShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType, MatchingRule<String> matchingRule) throws SchemaException {
assertShadowRepo(accountShadow, oid, username, resourceType, getAccountObjectClass(resourceType), matchingRule);
}
protected void assertShadowRepo(PrismObject<ShadowType> accountShadow, String oid, String username, ResourceType resourceType,
QName objectClass, MatchingRule<String> nameMatchingRule) throws SchemaException {
assertShadowCommon(accountShadow, oid, username, resourceType, objectClass, nameMatchingRule, true);
PrismContainer<Containerable> attributesContainer = accountShadow.findContainer(ShadowType.F_ATTRIBUTES);
List<Item<?,?>> attributes = attributesContainer.getValue().getItems();
// Collection secIdentifiers = ShadowUtil.getSecondaryIdentifiers(accountShadow);
if (attributes == null){
AssertJUnit.fail("No attributes in repo shadow");
}
RefinedResourceSchema refinedSchema = null;
try {
refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resourceType);
} catch (SchemaException e) {
AssertJUnit.fail(e.getMessage());
}
ObjectClassComplexTypeDefinition objClassDef = refinedSchema.getRefinedDefinition(objectClass);
Collection secIdentifiers = objClassDef.getSecondaryIdentifiers();
if (secIdentifiers == null){
AssertJUnit.fail("No secondary identifiers in repo shadow");
}
// repo shadow should contains all secondary identifiers + ICF_UID
assertRepoShadowAttributes(attributes, secIdentifiers.size()+1);
}
protected void assertRepoShadowAttributes(List<Item<?,?>> attributes, int expectedNumberOfIdentifiers) {
assertEquals("Unexpected number of attributes in repo shadow", expectedNumberOfIdentifiers, attributes.size());
}
protected String getIcfUid(PrismObject<ShadowType> shadow) {
PrismContainer<Containerable> attributesContainer = shadow.findContainer(ShadowType.F_ATTRIBUTES);
assertNotNull("Null attributes in "+shadow, attributesContainer);
assertFalse("Empty attributes in "+shadow, attributesContainer.isEmpty());
PrismProperty<String> icfUidProp = attributesContainer.findProperty(new QName(SchemaConstants.NS_ICF_SCHEMA,"uid"));
assertNotNull("No ICF name attribute in "+shadow, icfUidProp);
return icfUidProp.getRealValue();
}
protected void rememberCounter(InternalCounters counter) {
lastCountMap.put(counter, InternalMonitor.getCount(counter));
}
protected long getLastCount(InternalCounters counter) {
Long lastCount = lastCountMap.get(counter);
if (lastCount == null) {
return 0;
} else {
return lastCount;
}
}
protected long getCounterIncrement(InternalCounters counter) {
return InternalMonitor.getCount(counter) - getLastCount(counter);
}
protected void assertCounterIncrement(InternalCounters counter, int expectedIncrement) {
long currentCount = InternalMonitor.getCount(counter);
long actualIncrement = currentCount - getLastCount(counter);
assertEquals("Unexpected increment in "+counter.getLabel(), (long)expectedIncrement, actualIncrement);
lastCountMap.put(counter, currentCount);
}
protected void assertCounterIncrement(InternalCounters counter, int expectedIncrementMin, int expectedIncrementMax) {
long currentCount = InternalMonitor.getCount(counter);
long actualIncrement = currentCount - getLastCount(counter);
assertTrue("Unexpected increment in "+counter.getLabel()+". Expected "
+expectedIncrementMin+"-"+expectedIncrementMax+" but was "+actualIncrement,
actualIncrement >= expectedIncrementMin && actualIncrement <= expectedIncrementMax);
lastCountMap.put(counter, currentCount);
}
protected void rememberResourceCacheStats() {
lastResourceCacheStats = InternalMonitor.getResourceCacheStats().clone();
}
protected void assertResourceCacheHitsIncrement(int expectedIncrement) {
assertCacheHits(lastResourceCacheStats, InternalMonitor.getResourceCacheStats(), "resouce cache", expectedIncrement);
}
protected void assertResourceCacheMissesIncrement(int expectedIncrement) {
assertCacheMisses(lastResourceCacheStats, InternalMonitor.getResourceCacheStats(), "resouce cache", expectedIncrement);
}
protected void assertCacheHits(CachingStatistics lastStats, CachingStatistics currentStats, String desc, int expectedIncrement) {
long actualIncrement = currentStats.getHits() - lastStats.getHits();
assertEquals("Unexpected increment in "+desc+" hit count", (long)expectedIncrement, actualIncrement);
lastStats.setHits(currentStats.getHits());
}
protected void assertCacheMisses(CachingStatistics lastStats, CachingStatistics currentStats, String desc, int expectedIncrement) {
long actualIncrement = currentStats.getMisses() - lastStats.getMisses();
assertEquals("Unexpected increment in "+desc+" miss count", (long)expectedIncrement, actualIncrement);
lastStats.setMisses(currentStats.getMisses());
}
protected void assertSteadyResources() {
assertCounterIncrement(InternalCounters.RESOURCE_REPOSITORY_READ_COUNT, 0);
assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0);
assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT, 0);
assertCounterIncrement(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT, 0);
assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0);
assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0);
}
protected void rememberSteadyResources() {
rememberCounter(InternalCounters.RESOURCE_REPOSITORY_READ_COUNT);
rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT);
rememberCounter(InternalCounters.RESOURCE_SCHEMA_PARSE_COUNT);
rememberCounter(InternalCounters.CONNECTOR_CAPABILITIES_FETCH_COUNT);
rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT);
rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT);
}
protected void rememberDummyResourceGroupMembersReadCount(String instanceName) {
lastDummyResourceGroupMembersReadCount = DummyResource.getInstance(instanceName).getGroupMembersReadCount();
}
protected void assertDummyResourceGroupMembersReadCountIncrement(String instanceName, int expectedIncrement) {
long currentDummyResourceGroupMembersReadCount = DummyResource.getInstance(instanceName).getGroupMembersReadCount();
long actualIncrement = currentDummyResourceGroupMembersReadCount - lastDummyResourceGroupMembersReadCount;
assertEquals("Unexpected increment in group members read count in dummy resource '"+instanceName+"'", (long)expectedIncrement, actualIncrement);
lastDummyResourceGroupMembersReadCount = currentDummyResourceGroupMembersReadCount;
}
protected void rememberDummyResourceWriteOperationCount(String instanceName) {
lastDummyResourceWriteOperationCount = DummyResource.getInstance(instanceName).getWriteOperationCount();
}
protected void assertDummyResourceWriteOperationCountIncrement(String instanceName, int expectedIncrement) {
long currentCount = DummyResource.getInstance(instanceName).getWriteOperationCount();